Compare commits
380 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
443c569d1c | |
|
|
7b91ede033 | |
|
|
ed653c5698 | |
|
|
c72835b1f2 | |
|
|
043fd88c61 | |
|
|
fb94c3c03f | |
|
|
c9bb03c645 | |
|
|
2a90330f7a | |
|
|
ae43dbe8b0 | |
|
|
a7a7cec041 | |
|
|
b3f136e004 | |
|
|
ab073e876b | |
|
|
796b16d36f | |
|
|
5912b21ae8 | |
|
|
dc522c6ec3 | |
|
|
5e6ee08273 | |
|
|
e8f13a5825 | |
|
|
c06039a2c8 | |
|
|
f3d00009c3 | |
|
|
dfa3fa7ee4 | |
|
|
531b78df82 | |
|
|
c71d0003b8 | |
|
|
156a1d1b28 | |
|
|
b4dacb23ea | |
|
|
1c88944d1d | |
|
|
33c3d01abe | |
|
|
a09b73e583 | |
|
|
76bd5a4f96 | |
|
|
a7b51cb24f | |
|
|
c29b6aa8f1 | |
|
|
ccdfb5af4e | |
|
|
ab8209301a | |
|
|
0c37ad60fd | |
|
|
0e86af51e3 | |
|
|
d8f9242d0f | |
|
|
0dc7ec0106 | |
|
|
bf5f2b86d2 | |
|
|
9b27c94593 | |
|
|
f14e5e65bf | |
|
|
3fdb9879ad | |
|
|
ba9a671d65 | |
|
|
c12bdf22db | |
|
|
c87bc0de91 | |
|
|
49c576351b | |
|
|
89697bd1a2 | |
|
|
3dff673d0d | |
|
|
533173b42c | |
|
|
ed07d5c00d | |
|
|
defc55a73e | |
|
|
ffe65d13a4 | |
|
|
a1df81ff78 | |
|
|
5b501af6f7 | |
|
|
dd9f7ad40c | |
|
|
66385e8bd7 | |
|
|
f332150947 | |
|
|
c9880a5aeb | |
|
|
feb0e1dd51 | |
|
|
f88450be83 | |
|
|
6ba5b06e90 | |
|
|
ba67f21c83 | |
|
|
508f2344f0 | |
|
|
e94bbbacb9 | |
|
|
ae0a7ee8c7 | |
|
|
d21fb9cf2a | |
|
|
f4f1e44742 | |
|
|
841ade21e6 | |
|
|
2388d9e4c0 | |
|
|
a281d48315 | |
|
|
5c81657d39 | |
|
|
753d3d081e | |
|
|
a1133cb8d2 | |
|
|
c8b4201d2c | |
|
|
06ee4e8cf8 | |
|
|
db42916959 | |
|
|
d0f0edc82f | |
|
|
02ca8af9e2 | |
|
|
8747ce5271 | |
|
|
a8bcf7ff7b | |
|
|
839e2154d1 | |
|
|
3eccae3b80 | |
|
|
94b1053823 | |
|
|
6167159bde | |
|
|
fd9b0c115c | |
|
|
5c57669831 | |
|
|
6dc5385eda | |
|
|
0997583ba3 | |
|
|
8f3095f777 | |
|
|
8de8a374ae | |
|
|
42a92b8f1a | |
|
|
d92c4f5c9f | |
|
|
f63d4f31a8 | |
|
|
399350871a | |
|
|
f5ac790a6d | |
|
|
4ec925d1fa | |
|
|
a0c87608ec | |
|
|
a5f6391606 | |
|
|
5f9a704fe0 | |
|
|
b95210616a | |
|
|
8769caec00 | |
|
|
90fb8ad7dc | |
|
|
6a51d2266b | |
|
|
e440d91ed5 | |
|
|
88d6eee625 | |
|
|
a0dd8dfb20 | |
|
|
e6809eb021 | |
|
|
2aa4c72a00 | |
|
|
0a5f893bad | |
|
|
0939223405 | |
|
|
f7a0938ca3 | |
|
|
5408ead056 | |
|
|
2c4d8f1ed4 | |
|
|
1156edff33 | |
|
|
54832b3715 | |
|
|
274934e079 | |
|
|
7626515dd2 | |
|
|
ee67c7761f | |
|
|
a7038e5f0a | |
|
|
59a342cbc3 | |
|
|
c64fbd58f4 | |
|
|
01f2986006 | |
|
|
07380b0a9d | |
|
|
a977e70311 | |
|
|
9feec20019 | |
|
|
e8dfdb03ef | |
|
|
35f6ac6165 | |
|
|
e38e40530d | |
|
|
310caa15d3 | |
|
|
7cdf3a054f | |
|
|
a9b82c89ff | |
|
|
dcc0c4bc12 | |
|
|
66075aaf71 | |
|
|
20dd6c69eb | |
|
|
0fdaf4cc9c | |
|
|
993b0b1b75 | |
|
|
028c3d3aee | |
|
|
8a2e08397c | |
|
|
fa738f0ec4 | |
|
|
ade0c0ab1b | |
|
|
2ce3c0c09f | |
|
|
cba34688f5 | |
|
|
90115412b9 | |
|
|
98a0911899 | |
|
|
1313776589 | |
|
|
ab09812e5f | |
|
|
5cf3096c41 | |
|
|
b251798b46 | |
|
|
8322eab735 | |
|
|
1be695b847 | |
|
|
2e46ec0b58 | |
|
|
e93b9050e8 | |
|
|
ea4f5eec65 | |
|
|
649222026b | |
|
|
baaf41057c | |
|
|
6e635afabc | |
|
|
f54f1b8853 | |
|
|
fa093538a1 | |
|
|
65299e1d6f | |
|
|
ad7c48f49b | |
|
|
1f083f99a7 | |
|
|
a3eead3600 | |
|
|
1c2b829899 | |
|
|
43cb7dec6f | |
|
|
e1ba18652d | |
|
|
b13f9f73e8 | |
|
|
c4b269319c | |
|
|
655cc03357 | |
|
|
c6c943e5b5 | |
|
|
67b4cd20e1 | |
|
|
932b707680 | |
|
|
ec371e00d2 | |
|
|
1cdf66941b | |
|
|
5dc151cba2 | |
|
|
793c3cb9d0 | |
|
|
1d4616abe9 | |
|
|
56d49c06ca | |
|
|
e87db59790 | |
|
|
df0ee4cf5d | |
|
|
56fdbd310f | |
|
|
d10530d80c | |
|
|
0cc2738238 | |
|
|
40a4a664b3 | |
|
|
d25d7a265b | |
|
|
1849729f8d | |
|
|
0bef5b93a2 | |
|
|
975f5a382a | |
|
|
c8389c9ef7 | |
|
|
229412af22 | |
|
|
e6ebc114b2 | |
|
|
dc5c4f14fe | |
|
|
573c44e8db | |
|
|
02956594b2 | |
|
|
35ceab2846 | |
|
|
d0195893a8 | |
|
|
3908647328 | |
|
|
952c407346 | |
|
|
3d3c35730d | |
|
|
333e247c7e | |
|
|
833f32a5eb | |
|
|
d76895c914 | |
|
|
a3012f34c8 | |
|
|
8dffb43379 | |
|
|
052a7cdaa8 | |
|
|
32ea37f06f | |
|
|
a54a5bbd25 | |
|
|
1076ef05fd | |
|
|
03f0221bff | |
|
|
fe172dab79 | |
|
|
23f927914a | |
|
|
38f04b9e71 | |
|
|
87daa7d8fa | |
|
|
feb829ae02 | |
|
|
4f90ec760e | |
|
|
5390b5da7b | |
|
|
8ea50141e6 | |
|
|
cbb1681b04 | |
|
|
46ff587d83 | |
|
|
02934437e4 | |
|
|
63415c7019 | |
|
|
e0fbb04086 | |
|
|
2f39cd3001 | |
|
|
11df894b32 | |
|
|
6ab4100527 | |
|
|
f0da880d35 | |
|
|
38a0179d2f | |
|
|
6a45ddf155 | |
|
|
0d0a7970c4 | |
|
|
d752d9b118 | |
|
|
3b7e4250a8 | |
|
|
9058801b02 | |
|
|
6cd65d3ac5 | |
|
|
31456b31a1 | |
|
|
3446e4ca35 | |
|
|
00a43e815e | |
|
|
bb045ec527 | |
|
|
269b58b383 | |
|
|
c33f6ecd3c | |
|
|
e6f2200469 | |
|
|
0623037e5d | |
|
|
116b67e51f | |
|
|
290511c23c | |
|
|
53af775d5a | |
|
|
eb14255759 | |
|
|
18542445d1 | |
|
|
fa0da926aa | |
|
|
55bba19a3f | |
|
|
f70042e9b0 | |
|
|
3e90fa6d10 | |
|
|
c064d3ab57 | |
|
|
b7fd107d35 | |
|
|
dd59463247 | |
|
|
4a5c09dbe3 | |
|
|
3caec10c6c | |
|
|
3fc16e0849 | |
|
|
212deff99e | |
|
|
5c0cb31095 | |
|
|
eb3d3c8b6b | |
|
|
9ce5686c40 | |
|
|
43785609c0 | |
|
|
116bce6253 | |
|
|
12c7eadc27 | |
|
|
aceab5554b | |
|
|
7e470542ff | |
|
|
9fce395af7 | |
|
|
245c17c2d0 | |
|
|
14f641276b | |
|
|
0cffbe6201 | |
|
|
63e4aeb061 | |
|
|
66f2d49096 | |
|
|
639886b864 | |
|
|
88e943415f | |
|
|
ae73bbc8bd | |
|
|
ba86598e0e | |
|
|
520144710f | |
|
|
a32a40f416 | |
|
|
71370ed09d | |
|
|
9804869ea2 | |
|
|
2c3e3c3c00 | |
|
|
e6a2f8f899 | |
|
|
a7b044b586 | |
|
|
1e13c7d189 | |
|
|
ba6d7b8938 | |
|
|
facdf28467 | |
|
|
5cc792a386 | |
|
|
03bb0a459b | |
|
|
2b70b6272e | |
|
|
9a9be38af4 | |
|
|
c663f32ccc | |
|
|
a6739ff0a9 | |
|
|
4c2b1fcbf1 | |
|
|
e8c72ed9fa | |
|
|
0c51c8d22a | |
|
|
39d5bb1fe7 | |
|
|
53f0d1fd88 | |
|
|
ac1787fb45 | |
|
|
5aaf5cae85 | |
|
|
6447dacdd9 | |
|
|
bcb0cce6be | |
|
|
2f1aa8dd45 | |
|
|
ccdd89184a | |
|
|
23d805dedc | |
|
|
a4c4c7dc73 | |
|
|
d148c1e55c | |
|
|
993db72668 | |
|
|
8d2b2eefd0 | |
|
|
fcb81e2e7c | |
|
|
6c8b581599 | |
|
|
41dc17c2c7 | |
|
|
f1657fb59a | |
|
|
9617fa77c2 | |
|
|
c7d88cfc0a | |
|
|
c0716e80e1 | |
|
|
94a5caa30b | |
|
|
624d96d3ba | |
|
|
db91470e89 | |
|
|
cbbd22427c | |
|
|
52135e34d0 | |
|
|
7f652f32b2 | |
|
|
12ae1f3985 | |
|
|
5c36132c79 | |
|
|
35c7a90841 | |
|
|
0d5648da59 | |
|
|
b1ca75a399 | |
|
|
c009c5cb38 | |
|
|
2d8deb10cd | |
|
|
db290555a5 | |
|
|
e93bc13206 | |
|
|
72c8d511d2 | |
|
|
b7dcb576c0 | |
|
|
daf78d2618 | |
|
|
2567907223 | |
|
|
4747e5165d | |
|
|
c5b3bc6638 | |
|
|
57ff1526b7 | |
|
|
f26715b1ad | |
|
|
b25eb0a481 | |
|
|
588c2a8e71 | |
|
|
61c3cbe885 | |
|
|
4d2dc1de95 | |
|
|
de72069577 | |
|
|
68aa45bb72 | |
|
|
4ffed61769 | |
|
|
93a5c75bd2 | |
|
|
6777174beb | |
|
|
2b355ff755 | |
|
|
5256936bf4 | |
|
|
e56934f6b7 | |
|
|
a6c05d112c | |
|
|
7c6a028210 | |
|
|
6481333a48 | |
|
|
6d82edca99 | |
|
|
31b94943f6 | |
|
|
1f76e7d24d | |
|
|
00aa9439fe | |
|
|
e42fdcd20f | |
|
|
a143f677b2 | |
|
|
6c52dfe893 | |
|
|
e9fb447df0 | |
|
|
eb7031c32e | |
|
|
c20b50b507 | |
|
|
22f6ec367d | |
|
|
307cbfad99 | |
|
|
bb13e2b6fa | |
|
|
5e3d3236b7 | |
|
|
58aeb56a36 | |
|
|
f04c774101 | |
|
|
9e5c870a5f | |
|
|
ef604c6004 | |
|
|
74de54eb2d | |
|
|
3132dc50e5 | |
|
|
9443b7e789 | |
|
|
a83d8d47c0 | |
|
|
a96507e2b3 | |
|
|
86e55b01a3 | |
|
|
1499e45add | |
|
|
9c23645df8 | |
|
|
ccc990723a | |
|
|
b5555b2cf2 | |
|
|
b0fb3b6996 | |
|
|
5a28720fea | |
|
|
48414bf279 |
|
|
@ -1,2 +1,3 @@
|
||||||
[alias]
|
[alias]
|
||||||
coverage = "llvm-cov --locked --workspace --all-features --json --summary-only --output-path coverage/summary.json"
|
# Production defaults include every GUI/PDF feature.
|
||||||
|
coverage = "llvm-cov --locked --workspace --json --summary-only --output-path coverage/summary.json"
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,2 @@
|
||||||
|
# CAD text fixtures retain the format's CRLF line endings.
|
||||||
|
*.dxf -text whitespace=cr-at-eol
|
||||||
|
|
@ -160,3 +160,13 @@ cython_debug/
|
||||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||||
#.idea/
|
#.idea/
|
||||||
|
|
||||||
|
# Local rundowns and generated exports; only the regression corpus is tracked.
|
||||||
|
/rundowns/*
|
||||||
|
!/rundowns/README.md
|
||||||
|
!/rundowns/sources.json
|
||||||
|
!/rundowns/estivales-2025-plenieres.xlsx
|
||||||
|
!/rundowns/moebius-apres-midi-sante-mentale.xlsx
|
||||||
|
!/rundowns/moebius-matin-pleniere-sante-environnement.xlsx
|
||||||
|
!/rundowns/gifav-2026-auditorium.xlsx
|
||||||
|
!/rundowns/pleniere-2.xlsx
|
||||||
|
|
|
||||||
52
AGENTS.md
|
|
@ -1,11 +1,16 @@
|
||||||
# beffroi-tools
|
# beffroi-tools
|
||||||
|
|
||||||
This repository contains a Rust PPTX reporter and Python command-line tools
|
This repository contains Rust reporting/conversion apps and Python command-line tools
|
||||||
for everyday local document and media workflows. Keep them simple to run. Keep `README.md` minimal,
|
for everyday local document and media workflows. Keep them simple to run. Keep `README.md` minimal,
|
||||||
with quick-start examples and links to detailed documentation in `docs/`.
|
with quick-start examples and links to detailed documentation in `docs/`.
|
||||||
|
|
||||||
## Current tools
|
## Current tools
|
||||||
|
|
||||||
|
- `crates/ascii-names/` is the sequential ASCII filename cleaner: one Rust binary
|
||||||
|
with egui drag-and-drop and CLI modes. Keep renames paced and single-threaded,
|
||||||
|
preserve file contents, never overwrite collision targets, and skip symlinks.
|
||||||
|
The selected root stays unchanged; descendants are processed inside out.
|
||||||
|
|
||||||
- `crates/pptx-reporter/` is the Rust reporter: shared core, CLI and egui desktop interface.
|
- `crates/pptx-reporter/` is the Rust reporter: shared core, CLI and egui desktop interface.
|
||||||
PDF compilation and DejaVu fonts are embedded. Discover FFprobe beside the app,
|
PDF compilation and DejaVu fonts are embedded. Discover FFprobe beside the app,
|
||||||
under `bin/`, or on PATH. It is the sole PPTX video reporter; the Python
|
under `bin/`, or on PATH. It is the sole PPTX video reporter; the Python
|
||||||
|
|
@ -15,6 +20,16 @@ with quick-start examples and links to detailed documentation in `docs/`.
|
||||||
in reports, and omit those cases from Ontime and playback totals.
|
in reports, and omit those cases from Ontime and playback totals.
|
||||||
The document exporter remains Python.
|
The document exporter remains Python.
|
||||||
|
|
||||||
|
- `crates/rundown-converter/` is the spreadsheet rundown converter: shared Rust
|
||||||
|
core, CLI and egui interface. Keep inference, untimed-gap identification, IR
|
||||||
|
construction, consistency validation and Ontime export separate. A timing
|
||||||
|
column must have a consistent meaning across all relevant rows. Ambiguities
|
||||||
|
block export; explicit starts and untimed gaps must survive conversion.
|
||||||
|
The five user-approved XLSX fixtures listed in `rundowns/sources.json` are tracked
|
||||||
|
and exercised by `tests/supplied_corpus.rs`; other local examples, generated exports
|
||||||
|
and public downloads stay untracked. Keep synthetic tests for isolated cases.
|
||||||
|
PDF, XLS/ODS readers and buffer correction remain future work.
|
||||||
|
|
||||||
- `tools/progress.py` provides shared transient terminal progress and plain logs
|
- `tools/progress.py` provides shared transient terminal progress and plain logs
|
||||||
for redirected output; `tests/test_progress.py` checks display cleanup.
|
for redirected output; `tests/test_progress.py` checks display cleanup.
|
||||||
- `tools/exporter.py` uses DeckCraft to export PPTX presentations to PDF or PNG slides,
|
- `tools/exporter.py` uses DeckCraft to export PPTX presentations to PDF or PNG slides,
|
||||||
|
|
@ -27,7 +42,9 @@ with quick-start examples and links to detailed documentation in `docs/`.
|
||||||
- `tests/test_exporter.py` covers exporter validation, no-op behavior, conversion
|
- `tests/test_exporter.py` covers exporter validation, no-op behavior, conversion
|
||||||
failures, and overwrite behavior.
|
failures, and overwrite behavior.
|
||||||
- `Jenkinsfile` runs Python/Rust tests, lint, docs and coverage on
|
- `Jenkinsfile` runs Python/Rust tests, lint, docs and coverage on
|
||||||
`rust_no_docker`. The explicitly requested badge workflow archives exactly
|
`rust_no_docker` in a FreeBSD jail. ASCII cleaner tests must verify safe refusal
|
||||||
|
when the jail lacks the native no-overwrite API; exercise successful renames
|
||||||
|
on supported hosts as well. The explicitly requested badge workflow archives exactly
|
||||||
three SVGs and publishes them only from main during cleanup. CI never creates
|
three SVGs and publishes them only from main during cleanup. CI never creates
|
||||||
releases or uploads release binaries. Cross and `rust_realease` are separate,
|
releases or uploads release binaries. Cross and `rust_realease` are separate,
|
||||||
manually invoked build/release preparation tools.
|
manually invoked build/release preparation tools.
|
||||||
|
|
@ -41,6 +58,19 @@ with quick-start examples and links to detailed documentation in `docs/`.
|
||||||
from pinned FFmpeg source, with source, LGPL notices and the recipe bundled.
|
from pinned FFmpeg source, with source, LGPL notices and the recipe bundled.
|
||||||
Include upstream notices/provenance, never commit binaries.
|
Include upstream notices/provenance, never commit binaries.
|
||||||
|
|
||||||
|
- `companion-modules/media-player-classic/` is the local MPC-HC module for Companion 5.1.
|
||||||
|
Prefer JSON status with HTML fallback; drive feedback from player state,
|
||||||
|
clear stale state on failures, and keep polling serialized and cancellable.
|
||||||
|
Preserve numeric action IDs and upstream MIT attribution. Use Node.js 22.20+
|
||||||
|
(22.x); run `npm test`, `npm run check`, and `npm run package` in the module.
|
||||||
|
`setup.py` installs locked dependencies and can back up/configure the launcher.
|
||||||
|
Keep dependencies, packages, and caches untracked; real-player playback checks
|
||||||
|
are separate from automated mock HTTP tests.
|
||||||
|
|
||||||
|
- PDF Presenter is a standalone sibling at `../pdf-presenter`, Gitea
|
||||||
|
`idle-org/pdf-presenter`. This repository links to it; do not add it as a workspace
|
||||||
|
member or publish its badges. It is currently a foundation, not a working presenter.
|
||||||
|
|
||||||
## Repository layout
|
## Repository layout
|
||||||
|
|
||||||
- `tools/` and `tests/`: Python prototypes and their regression tests.
|
- `tools/` and `tests/`: Python prototypes and their regression tests.
|
||||||
|
|
@ -62,6 +92,10 @@ with quick-start examples and links to detailed documentation in `docs/`.
|
||||||
- Keep tools in `tools/`, tests in `tests/`, and specialized documentation in
|
- Keep tools in `tools/`, tests in `tests/`, and specialized documentation in
|
||||||
`docs/`. Update the relevant docs when options or workflows change; keep the
|
`docs/`. Update the relevant docs when options or workflows change; keep the
|
||||||
README's examples and links current.
|
README's examples and links current.
|
||||||
|
- For each tool change, add a succinct entry to its changelog linked from
|
||||||
|
`docs/changelogs.md`: what changed and any useful testing note or limitation.
|
||||||
|
Use Unreleased until tagged; add new tools to the index. Keep shared changes
|
||||||
|
in affected tools’ logs, without duplicating implementation details.
|
||||||
- Run checks appropriate to the change before committing. Python exporter, CI and packaging
|
- Run checks appropriate to the change before committing. Python exporter, CI and packaging
|
||||||
tests run with
|
tests run with
|
||||||
`python3 -m unittest discover -s tests -v`. For rendering changes,
|
`python3 -m unittest discover -s tests -v`. For rendering changes,
|
||||||
|
|
@ -73,6 +107,20 @@ with quick-start examples and links to detailed documentation in `docs/`.
|
||||||
Run `python3 scripts/ci.py coverage` for the whole Rust application; do not
|
Run `python3 scripts/ci.py coverage` for the whole Rust application; do not
|
||||||
exclude production GUI/PDF code to raise the reported percentage.
|
exclude production GUI/PDF code to raise the reported percentage.
|
||||||
|
|
||||||
|
## Save/export interfaces
|
||||||
|
|
||||||
|
- Document every persistent save and export format under `docs/interfaces/`,
|
||||||
|
including field names, units, precision, versioning, validation, omissions,
|
||||||
|
import/round-trip behavior, and compatibility expectations.
|
||||||
|
- Whenever a save-file schema or export representation changes, update the
|
||||||
|
corresponding interface documentation, examples, and regression tests in the
|
||||||
|
same task. Do not leave `interfaces` out of a schema change.
|
||||||
|
- Version breaking changes explicitly; provide a tested migration or a clear
|
||||||
|
unsupported-version error rather than silently interpreting incompatible data.
|
||||||
|
- Canvas Pilot has moved to `../canvas-pilot` and its own Gitea repository,
|
||||||
|
`idle-org/canvas-pilot`. Its code, contracts, fixtures, probe and book belong there.
|
||||||
|
This repository links to its manual but never publishes or deletes that book.
|
||||||
|
|
||||||
## Commit every task
|
## Commit every task
|
||||||
|
|
||||||
- Every completed task that changes repository files must end with a Git commit.
|
- Every completed task that changes repository files must end with a Git commit.
|
||||||
|
|
|
||||||
|
|
@ -201,6 +201,21 @@ version = "1.0.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
|
checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ascii-names"
|
||||||
|
version = "0.7.0"
|
||||||
|
dependencies = [
|
||||||
|
"clap",
|
||||||
|
"eframe",
|
||||||
|
"libc",
|
||||||
|
"rfd",
|
||||||
|
"rustix 1.1.5",
|
||||||
|
"tempfile",
|
||||||
|
"unicode-normalization",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
"winresource",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ash"
|
name = "ash"
|
||||||
version = "0.38.0+1.3.281"
|
version = "0.38.0+1.3.281"
|
||||||
|
|
@ -3190,7 +3205,7 @@ checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pptx-reporter"
|
name = "pptx-reporter"
|
||||||
version = "0.2.0"
|
version = "0.7.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
|
|
@ -3537,6 +3552,27 @@ version = "0.20.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
|
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rundown-converter"
|
||||||
|
version = "0.7.0"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"clap",
|
||||||
|
"csv",
|
||||||
|
"directories",
|
||||||
|
"eframe",
|
||||||
|
"open",
|
||||||
|
"rfd",
|
||||||
|
"roxmltree",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"tempfile",
|
||||||
|
"unicode-normalization",
|
||||||
|
"uuid",
|
||||||
|
"winresource",
|
||||||
|
"zip",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rust_decimal"
|
name = "rust_decimal"
|
||||||
version = "1.43.0"
|
version = "1.43.0"
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,10 @@
|
||||||
[workspace]
|
[workspace]
|
||||||
members = ["crates/pptx-reporter"]
|
members = ["crates/pptx-reporter", "crates/rundown-converter", "crates/ascii-names"]
|
||||||
default-members = ["crates/pptx-reporter"]
|
default-members = ["crates/pptx-reporter"]
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.2.0"
|
version = "0.7.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
repository = "https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools"
|
repository = "https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools"
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,24 @@
|
||||||
|
# Future ideas
|
||||||
|
|
||||||
|
These are feasibility notes for possible tools, not implemented features or
|
||||||
|
committed delivery plans.
|
||||||
|
|
||||||
|
See the [future program task list](docs/planning/program-task-list.md) for the planned
|
||||||
|
DMX driver/firmware project and far-future Dante virtual soundcard research.
|
||||||
|
|
||||||
|
## Flipper Link: USB control from the web and Stream Deck
|
||||||
|
|
||||||
|
**Feasible for selected actions with official Flipper Zero firmware.** A small
|
||||||
|
service on the computer connected to the Flipper would translate HTTP commands
|
||||||
|
into USB serial CLI commands or structured protobuf RPC requests. Bitfocus
|
||||||
|
Companion could call that service from Stream Deck buttons.
|
||||||
|
|
||||||
|
Start with device status and saved infrared remote buttons. Prove the workflow
|
||||||
|
using Companion's Generic HTTP module, then build a dedicated Companion module
|
||||||
|
with action selection, variables and feedback. Remote support varies by Flipper
|
||||||
|
application; exposing every internal action is not guaranteed. USB ownership,
|
||||||
|
reconnection and stopping held actions need particular care.
|
||||||
|
|
||||||
|
See [Flipper Link feasibility and proposed design](docs/planning/flipper-link.md) for
|
||||||
|
the supported interfaces, limitations, architecture, implementation stages and
|
||||||
|
primary sources. Hardware validation is still required.
|
||||||
|
|
@ -4,6 +4,7 @@ pipeline {
|
||||||
|
|
||||||
options {
|
options {
|
||||||
skipDefaultCheckout(true)
|
skipDefaultCheckout(true)
|
||||||
|
disableConcurrentBuilds()
|
||||||
timeout(time: 45, unit: 'MINUTES')
|
timeout(time: 45, unit: 'MINUTES')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -13,6 +14,7 @@ pipeline {
|
||||||
NO_COLOR = '1'
|
NO_COLOR = '1'
|
||||||
CARGO_TERM_COLOR = 'never'
|
CARGO_TERM_COLOR = 'never'
|
||||||
BADGE_ROOT = '/mnt/assets/coverage'
|
BADGE_ROOT = '/mnt/assets/coverage'
|
||||||
|
MANUALS_ROOT = '/mnt/books/manuals'
|
||||||
}
|
}
|
||||||
|
|
||||||
stages {
|
stages {
|
||||||
|
|
@ -30,11 +32,17 @@ pipeline {
|
||||||
set -eu
|
set -eu
|
||||||
python3 -c 'import sys; assert sys.version_info >= (3, 11), "Python 3.11+ required for CI"'
|
python3 -c 'import sys; assert sys.version_info >= (3, 11), "Python 3.11+ required for CI"'
|
||||||
test -n "${BRANCH_NAME:?Configure this job as a Multibranch Pipeline}"
|
test -n "${BRANCH_NAME:?Configure this job as a Multibranch Pipeline}"
|
||||||
|
uname -sr
|
||||||
rustc --version
|
rustc --version
|
||||||
if ! cargo llvm-cov --version | grep -Fx 'cargo-llvm-cov 0.9.1'; then
|
if ! cargo llvm-cov --version | grep -Fx 'cargo-llvm-cov 0.9.1'; then
|
||||||
cargo install cargo-llvm-cov --version 0.9.1 --locked
|
cargo install cargo-llvm-cov --version 0.9.1 --locked
|
||||||
fi
|
fi
|
||||||
rustup component add llvm-tools-preview clippy rustfmt
|
rustup component add llvm-tools-preview clippy rustfmt
|
||||||
|
mdbook_version=$(cat docs/manuals/mdbook-version)
|
||||||
|
if ! mdbook --version 2>/dev/null | grep -Fx "mdbook v${mdbook_version}"; then
|
||||||
|
cargo install mdbook --version "$mdbook_version" --locked
|
||||||
|
fi
|
||||||
|
command -v rsync
|
||||||
'''
|
'''
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -64,9 +72,22 @@ pipeline {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
stage('Build manuals') {
|
||||||
|
steps { sh 'python3 scripts/manuals.py build' }
|
||||||
|
}
|
||||||
stage('Coverage') {
|
stage('Coverage') {
|
||||||
steps { sh 'python3 scripts/ci.py coverage' }
|
steps { sh 'python3 scripts/ci.py coverage' }
|
||||||
}
|
}
|
||||||
|
stage('Publish manuals') {
|
||||||
|
when {
|
||||||
|
allOf {
|
||||||
|
branch 'main'
|
||||||
|
not { changeRequest() }
|
||||||
|
expression { currentBuild.currentResult == 'SUCCESS' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
steps { sh 'python3 scripts/manuals.py publish --destination "$MANUALS_ROOT"' }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
post {
|
post {
|
||||||
|
|
|
||||||
146
README.md
|
|
@ -1,46 +1,140 @@
|
||||||
# beffroi-tools
|
<h1 align="center">beffroi-tools</h1>
|
||||||
|
|
||||||

|
<p align="center">Local tools for presentations, show timing, screen layouts and media workflows.</p>
|
||||||

|
|
||||||

|
|
||||||
|
|
||||||
Local document and media tools: a Rust PPTX video reporter with a drag-and-drop
|
<p align="center">
|
||||||
app, and Python tools for prototyping and document exports.
|
<img src="https://assets.dandaedre.com/coverage/Beffroi/beffroi-tools/main/version.svg" alt="Current version">
|
||||||
|
<img src="https://assets.dandaedre.com/coverage/Beffroi/beffroi-tools/main/test.svg" alt="Test status">
|
||||||
|
<img src="https://assets.dandaedre.com/coverage/Beffroi/beffroi-tools/main/coverage.svg" alt="Line coverage">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/development/releases.md">Portable releases</a> ·
|
||||||
|
<a href="#quick-start">Quick start</a> ·
|
||||||
|
<a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/README.md">Documentation</a> ·
|
||||||
|
<a href="https://books.dandaedre.com/manuals/">Full manuals</a> ·
|
||||||
|
<a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/changelogs.md">What's new</a> ·
|
||||||
|
<a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/development/README.md">Development</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
## Choose your tool
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td width="50%" valign="top">
|
||||||
|
<a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/pptx-reporter/README.md"><img src="crates/pptx-reporter/assets/app-icon.png" width="72" height="72" alt="PPTX Reporter icon"></a>
|
||||||
|
<h3><a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/pptx-reporter/README.md">PPTX Reporter</a></h3>
|
||||||
|
<p>Inspect presentation videos, read playback timings, and export reports or Ontime rundowns.</p>
|
||||||
|
<p><strong>Desktop app · CLI</strong></p>
|
||||||
|
<p><a href="https://books.dandaedre.com/manuals/pptx-reporter/">Full manual</a> · <a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/pptx-reporter/visual-guide.md">Visual walkthrough</a> · <a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/pptx-reporter/README.md">Guide</a> · <a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/pptx-reporter/report-formats.md">Report formats</a></p>
|
||||||
|
</td>
|
||||||
|
<td width="50%" valign="top">
|
||||||
|
<a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/rundown-converter/README.md"><img src="crates/rundown-converter/assets/app-icon.png" width="72" height="72" alt="Rundown Converter icon"></a>
|
||||||
|
<h3><a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/rundown-converter/README.md">Rundown Converter</a></h3>
|
||||||
|
<p>Turn spreadsheet rundowns into Ontime schedules, with timing checks before export.</p>
|
||||||
|
<p><strong>Desktop app · CLI</strong></p>
|
||||||
|
<p><a href="https://books.dandaedre.com/manuals/rundown-converter/">Full manual</a> · <a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/rundown-converter/README.md">Guide</a> · <a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/rundown-converter/corpus.md">Sample findings</a></p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td valign="top">
|
||||||
|
<a href="https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/README.md"><img src="https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/raw/branch/main/crates/canvas-pilot/assets/app-icon.png" width="72" height="72" alt="Canvas Pilot icon"></a>
|
||||||
|
<h3><a href="https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/README.md">Canvas Pilot</a></h3>
|
||||||
|
<p>Arrange screen layers, exchange geometry, and review transfers to Midra and Aquilon devices.</p>
|
||||||
|
<p><strong>Desktop app · separate repository</strong></p>
|
||||||
|
<p><a href="https://books.dandaedre.com/manuals/canvas-pilot/">Full manual</a> · <a href="https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/README.md">Guide</a> · <a href="#canvas-pilot-templates">Templates</a> · <a href="https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/interfaces/canvas-pilot-exchange.md">Geometry formats</a></p>
|
||||||
|
</td>
|
||||||
|
<td valign="top">
|
||||||
|
<a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/ascii-names/README.md"><img src="crates/ascii-names/assets/app-icon.png" width="72" height="72" alt="ASCII Names icon"></a>
|
||||||
|
<h3><a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/ascii-names/README.md">ASCII Names</a></h3>
|
||||||
|
<p>Clean up filenames to ASCII with paced renames, collision protection, and unchanged file contents.</p>
|
||||||
|
<p><strong>Desktop app · CLI</strong></p>
|
||||||
|
<p><a href="https://books.dandaedre.com/manuals/ascii-names/">Full manual</a> · <a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/ascii-names/README.md">Guide</a></p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td valign="top">
|
||||||
|
<a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/exporter/README.md"><img src="tools/assets/exporter/app-icon.png" width="72" height="72" alt="Document Exporter icon"></a>
|
||||||
|
<h3><a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/exporter/README.md">Document Exporter</a></h3>
|
||||||
|
<p>Export PPTX to PDF or slide images, render PDF pages, and compress PDFs to a target size.</p>
|
||||||
|
<p><strong>Python CLI</strong></p>
|
||||||
|
<p><a href="https://books.dandaedre.com/manuals/exporter/">Full manual</a> · <a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/exporter/README.md">Guide and dependencies</a></p>
|
||||||
|
</td>
|
||||||
|
<td valign="top">
|
||||||
|
<a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/companion-modules/media-player-classic/README.md"><img src="companion-modules/media-player-classic/companion/assets/app-icon.png" width="72" height="72" alt="MPC-HC Companion icon"></a>
|
||||||
|
<h3><a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/companion-modules/media-player-classic/README.md">MPC-HC Companion</a></h3>
|
||||||
|
<p>Control Media Player Classic Home Cinema from Companion with playback actions and player feedback.</p>
|
||||||
|
<p><strong>Companion 5.1 module</strong></p>
|
||||||
|
<p><a href="https://books.dandaedre.com/manuals/media-player-classic/">Full manual</a> · <a href="https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/companion-modules/media-player-classic/README.md">Setup and development</a></p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td valign="top" colspan="2">
|
||||||
|
<a href="https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter"><img src="https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter/raw/branch/main/crates/pdf-presenter/assets/app-icon.png" width="72" height="72" alt="PDF Presenter icon"></a>
|
||||||
|
<h3><a href="https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter">PDF Presenter</a></h3>
|
||||||
|
<p>Standalone multiscreen PDF presenter project, inspired by Pympress and PowerPoint workflows.</p>
|
||||||
|
<p><strong>Repository foundation · separate repository · access required</strong></p>
|
||||||
|
<p>PDF rendering and desktop presentation are planned. <a href="https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter/src/branch/main/docs/development/plan.md">Implementation plan</a> · <a href="https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter/src/branch/main/docs/development/ci.md">Development and CI</a></p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
On Windows, extract the portable ZIP and open `pptx-reporter-gui.exe`.
|
**Start with a portable app:** see [release bundles and platform instructions](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/development/releases.md).
|
||||||
Drop PPTX files or a video folder into the window, select report formats, and generate.
|
For PPTX Reporter, extract the ZIP and open `pptx-reporter-gui.exe` on Windows
|
||||||
Keep the bundled `ffprobe.exe` beside the app.
|
or run `./pptx-reporter-gui` on macOS 13+. Choose the macOS archive for
|
||||||
|
[Apple Silicon or Intel](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/development/releases.md#macos). Keep the bundled FFprobe beside the app.
|
||||||
|
|
||||||
On macOS 13+, extract the portable ZIP for Apple Silicon (`aarch64`) or Intel
|
Drop a presentation or video folder into the reporter, choose report formats,
|
||||||
(`x86_64`) and run `./pptx-reporter-gui`. FFprobe is included; keep it beside the app.
|
and generate. The [illustrated guide](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/pptx-reporter/visual-guide.md) walks through each step;
|
||||||
See [macOS release details](docs/releases.md#macos).
|
a [Windows quick start](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/pptx-reporter/windows-quickstart.txt) is also available.
|
||||||
|
|
||||||
To run from source:
|
<details>
|
||||||
|
<summary><strong>Run from source</strong> — Rust apps and Python exporter</summary>
|
||||||
|
|
||||||
|
Run these commands from the repository root:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
# PPTX Reporter: desktop, full report, or Ontime timings
|
||||||
cargo run --locked --bin pptx-reporter-gui
|
cargo run --locked --bin pptx-reporter-gui
|
||||||
cargo run --locked --bin pptx-reporter -- presentation.pptx --report all
|
cargo run --locked --bin pptx-reporter -- presentation.pptx --report all
|
||||||
cargo run --locked --bin pptx-reporter -- ./show --timings-only --report ontime
|
cargo run --locked --bin pptx-reporter -- ./show --timings-only --report ontime
|
||||||
|
|
||||||
|
# Other desktop apps
|
||||||
|
cargo run --locked -p rundown-converter --bin rundown-converter-gui
|
||||||
|
cargo run --locked -p ascii-names
|
||||||
|
|
||||||
|
# Document exports
|
||||||
python3 tools/exporter.py presentation.pptx --output pdf,images
|
python3 tools/exporter.py presentation.pptx --output pdf,images
|
||||||
```
|
```
|
||||||
|
|
||||||
The reporter needs FFprobe (included in portable bundles); PDF generation is
|
The reporter needs FFprobe; PDF generation is built in. The exporter needs
|
||||||
built in. The exporter needs DeckCraft for PPTX or PdfCraft for PDF input.
|
DeckCraft for PPTX or PdfCraft for PDF input. CLI tools support `--help`.
|
||||||
Run source commands from the repository root; CLI tools support `--help`.
|
See [development setup](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/development/README.md) for prerequisites and checks.
|
||||||
|
|
||||||
## Visual guide
|
</details>
|
||||||
|
|
||||||
**[Follow the illustrated user guide →](docs/user-guide.md)**
|
Canvas Pilot now has its own [repository](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot). Build and run it there.
|
||||||
|
|
||||||
Screenshots walk you through choosing a presentation, selecting formats,
|
## Canvas Pilot templates
|
||||||
opening reports, and reading video timings.
|
|
||||||
|
|
||||||
## More documentation
|
[**Download all templates as ZIP**](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/raw/branch/main/docs/templates/canvas-pilot/canvas-pilot-all-templates.zip) · [Browse individual starter files →](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/templates/canvas-pilot/README.md)
|
||||||
|
|
||||||
- [Reporter](docs/rust-reporter.md) · [Windows quick start](docs/windows-quickstart.txt)
|
Matching Full HD and UHD 4K layouts are available in SVG, draw.io, geometry JSON,
|
||||||
- [Report formats and timing semantics](docs/pptx-videos.md)
|
CSV, DXF/DWG, HTML, PPTX, Figma FIG, FigCraft and Illustrator AI. The catalog contains every
|
||||||
- [Document exports](docs/exporter.md)
|
base file, import guidance and format dependencies.
|
||||||
- [Development](docs/development.md) · [CI and coverage](docs/ci.md)
|
|
||||||
- [Cross builds and portable releases](docs/releases.md)
|
**Prefer SVG for Illustrator exchange.** AI is an optional compatibility target
|
||||||
|
and requires a separately installed **VectorCraft CLI** for import and export.
|
||||||
|
[AI requirements and setup](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/guide/files.md#illustrator-ai-optional-converter-required).
|
||||||
|
|
||||||
|
## Explore further
|
||||||
|
|
||||||
|
| Resource | Links |
|
||||||
|
| --- | --- |
|
||||||
|
| Updates | [Per-tool changelogs](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/changelogs.md) |
|
||||||
|
| Build and contribute | [Development](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/development/README.md) · [CI and coverage](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/development/ci.md) · [Cross builds and releases](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/development/releases.md) |
|
||||||
|
| Desktop integration | [App icons and launchers](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/development/releases.md#application-artwork) |
|
||||||
|
| Midra internals | [Project format](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/interfaces/canvas-pilot.md) · [Device checks](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/device-check.md) · [Plan](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/plan.md) |
|
||||||
|
| What's next | [Ideas](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/Ideas.md) · [Program task list](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools/src/branch/main/docs/planning/program-task-list.md) |
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,5 @@
|
||||||
|
node_modules/
|
||||||
|
pkg/
|
||||||
|
*.tgz
|
||||||
|
.npm-cache/
|
||||||
|
DEBUG-PACKAGED
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
node_modules
|
||||||
|
pkg
|
||||||
|
package-lock.json
|
||||||
|
*.tgz
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
The MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2019 Bitfocus AS & Andreas H. Thomsen (McHauge)
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
|
@ -0,0 +1,469 @@
|
||||||
|
# MPC-HC Companion module — local development
|
||||||
|
|
||||||
|
[Read the full manual →](https://books.dandaedre.com/manuals/media-player-classic/)
|
||||||
|
|
||||||
|
<img src="companion/assets/app-icon.png" width="96" alt="Media Player Classic module icon">
|
||||||
|
|
||||||
|
A local development port of the original Media Player Classic module for
|
||||||
|
**Companion 5.1.0**, using Companion module API 2 and Node.js 22. It preserves
|
||||||
|
all 138 original numeric command IDs, adds live player feedback, and provides
|
||||||
|
transport and timing presets.
|
||||||
|
See [UPSTREAM.md](UPSTREAM.md) for provenance and [LICENSE](LICENSE) for attribution.
|
||||||
|
|
||||||
|
## Install on this computer
|
||||||
|
|
||||||
|
From the repository root:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 companion-modules/media-player-classic/setup.py \
|
||||||
|
--node-bin /home/beffroi/Softs/companion-x64/resources/node-runtimes/node22/bin \
|
||||||
|
--companion-config /home/beffroi/.config/companion/config.json \
|
||||||
|
--package
|
||||||
|
```
|
||||||
|
|
||||||
|
The helper installs dependencies from `package-lock.json`, runs tests and
|
||||||
|
format checks, optionally builds a `.tgz`, and enables the developer folder.
|
||||||
|
It backs up the launcher configuration before changing it and preserves other
|
||||||
|
settings. It refuses to replace an existing different developer folder.
|
||||||
|
It does not restart Companion, alter connections, or send player commands.
|
||||||
|
Restart Companion after changing its launcher settings.
|
||||||
|
|
||||||
|
Alternatively, install **Node.js 22.20+ (22.x) with npm**, run `python3 setup.py`
|
||||||
|
inside this module, and configure Companion manually:
|
||||||
|
|
||||||
|
1. Open the Companion launcher settings (cog).
|
||||||
|
2. Enable **Developer Modules** and select the **parent** folder:
|
||||||
|
`/home/beffroi/Documents/Git/beffroi-tools/companion-modules`.
|
||||||
|
3. In Connections, add **MPC-HC: Media Player Classic**, selecting version **dev**.
|
||||||
|
Use a distinct label such as `MPC_DEV` while testing.
|
||||||
|
4. Set host **192.168.10.146** and port **13579** for the current player.
|
||||||
|
5. In MPC-HC, enable **View → Options → Player → Web Interface → Listen on port**.
|
||||||
|
Allow remote access from this Companion computer if the player is on another host.
|
||||||
|
6. Confirm the connection is OK, then use its presets on a spare button page.
|
||||||
|
|
||||||
|
The module appears in Connections; a development module need not appear as an
|
||||||
|
installed store version on the Modules page. Existing connections remain on
|
||||||
|
their selected version until you explicitly change them.
|
||||||
|
|
||||||
|
## Transport presets and feedback
|
||||||
|
|
||||||
|
Open **Presets → MPC_DEV → Transport & timing** and drag the buttons onto a
|
||||||
|
spare page. These presets already include their feedback and variable references:
|
||||||
|
|
||||||
|
| Preset | Behavior |
|
||||||
|
| --------------------- | ------------------------------------------------------------------------ |
|
||||||
|
| ▶ Play | Subdued blue while stopped; full green while playing, amber while paused |
|
||||||
|
| ■ Stop | Subdued red while playing; full red while stopped |
|
||||||
|
| ◀◀ Previous / ▶▶ Next | Previous/next **playlist item**, not chapter or seek |
|
||||||
|
| Mute | Neutral when unmuted; full red **MUTED** while muted |
|
||||||
|
| Pause | Pause command; amber while paused |
|
||||||
|
| Remaining | Live media countdown and progress bar |
|
||||||
|
| Elapsed | Live elapsed media time and progress bar |
|
||||||
|
| Playback state | Playing, paused, stopped, idle, or offline with matching colors |
|
||||||
|
|
||||||
|
The Previous/Next transport presets use command IDs verified against this
|
||||||
|
player's `/commands.json`: Previous → `919`, Next → `920`. The old catalog was
|
||||||
|
outdated: `918` is **After Playback: Turn off the monitor**, not navigation.
|
||||||
|
Navigation-related labels are corrected; numeric action IDs still send their
|
||||||
|
same numeric commands. Re-add copied presets to existing buttons to apply
|
||||||
|
this correction; linked presets follow the module update.
|
||||||
|
|
||||||
|
Transport buttons use white labels on filled backgrounds. Play is subdued blue
|
||||||
|
until playing, when it becomes full green; Stop is subdued red until stopped,
|
||||||
|
when it becomes full red. Previous/Next stay subdued blue. Mute is neutral when
|
||||||
|
unmuted and full red with **MUTED** text when muted. Playback state is full green
|
||||||
|
while playing, full red while stopped, and amber while paused. Timers stay dark
|
||||||
|
with progress bars; backup sync keeps its original status colors.
|
||||||
|
Presets keep Companion’s standard top bar with the button location.
|
||||||
|
Re-add copied presets to apply styling updates; linked presets update automatically.
|
||||||
|
|
||||||
|
The progress bar fills from left to right. It turns amber with 30 seconds left
|
||||||
|
and red with 10 seconds left. Timing displays are passive: pressing them does
|
||||||
|
not send a player command. Transport presets use symbols, colors, and labels;
|
||||||
|
all original text presets remain in **All commands**.
|
||||||
|
|
||||||
|
Feedback comes from the player, including changes made using the mouse,
|
||||||
|
keyboard, or another controller. It never assumes a command succeeded merely
|
||||||
|
because a button was pressed. A successful HTTP command response alone does
|
||||||
|
not change playback or mute feedback. The next player status determines it.
|
||||||
|
|
||||||
|
Status uses `/status.json` where available (verified on MPC-HC **2.8.5.0**),
|
||||||
|
with automatic `/variables.html` fallback for older builds. The module polls
|
||||||
|
at **500 ms** by default, configurable from **250–5000 ms**, and refreshes after
|
||||||
|
commands. Requests do not overlap, and polling resumes after network failures.
|
||||||
|
|
||||||
|
On a failed status request, active state feedback and stale timing values are
|
||||||
|
cleared; transport presets show **OFFLINE**. Requests time out after 2.5 seconds.
|
||||||
|
There can therefore be a polling interval plus timeout before loss is shown.
|
||||||
|
`idle` means MPC reports no active media graph; it is distinct from `stopped`.
|
||||||
|
Unknown duration shows `--:--` with no bar. Countdown reflects media time, pauses
|
||||||
|
with the player, follows seeks, and does not predict wall-clock completion at
|
||||||
|
nonstandard playback speeds. Playback state is MPC's reported state, not proof
|
||||||
|
that frames or audio are physically reaching an output device.
|
||||||
|
|
||||||
|
## Large three-button timers
|
||||||
|
|
||||||
|
Open **Presets → MPC_DEV → Timers — large HH / MM / SS**. Place **Remaining HH
|
||||||
|
(1/3)**, **Remaining MM (2/3)**, and **Remaining SS (3/3)** in three adjacent slots,
|
||||||
|
left to right. For example, one hour, two minutes and three seconds displays:
|
||||||
|
|
||||||
|
| HH | MM | SS |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 01 | 02 | 03 |
|
||||||
|
|
||||||
|
There is a matching **Elapsed** set. Inspired by Ontime's separate timer-component
|
||||||
|
presets, each button shows only large auto-sized digits on a dark background,
|
||||||
|
with Companion's standard location bar. Buttons are passive; pressing them does
|
||||||
|
not control playback. The hours field does not wrap at 24 hours.
|
||||||
|
|
||||||
|
Remaining time rounds up once before splitting; elapsed time rounds down. Both
|
||||||
|
follow the same player snapshots as the existing timers and freeze when paused.
|
||||||
|
All remaining digits turn amber at 30 seconds left and red at 10 seconds left.
|
||||||
|
Elapsed digits stay white. Offline/idle displays grey **-- | -- | --**; unknown
|
||||||
|
duration also makes the remaining timer unavailable. Elapsed time still works
|
||||||
|
when position is known but duration is not.
|
||||||
|
|
||||||
|
Custom buttons can use `remaining_hh`, `remaining_mm`, `remaining_ss`,
|
||||||
|
`elapsed_hh`, `elapsed_mm`, and `elapsed_ss`. These are zero-padded display strings;
|
||||||
|
existing total-second variables are unchanged. Backup equivalents have `backup_`
|
||||||
|
prefixes. The new presets follow the main player.
|
||||||
|
|
||||||
|
## Playlist — direct playback
|
||||||
|
|
||||||
|
**Presets → MPC_DEV → Playlist** contains **Play item 1–10**. Each sends MPC-HC's
|
||||||
|
normal indexed playlist selection command, which opens and plays that item.
|
||||||
|
These presets do **not** mute, stop, retry Stop, or run the experimental loading
|
||||||
|
sequence. Existing mute remains unchanged. Even the currently selected item is
|
||||||
|
sent through MPC-HC's normal open/play path.
|
||||||
|
|
||||||
|
The reusable **Play playlist item** action accepts a 1-based item number from
|
||||||
|
1–10000. Duplicate a preset, change its action number and button text to create
|
||||||
|
additional positions. The action checks `/playlist.json` before sending selection;
|
||||||
|
missing items send no playback command. Positions follow the current playlist
|
||||||
|
order, so keep main/backup playlists aligned. Player target defaults to Both.
|
||||||
|
|
||||||
|
The buttons stay muted blue with a play icon; they do not claim individual-item
|
||||||
|
playing feedback. Normal player feedback updates after selection. These actions
|
||||||
|
leave **Last load result** unchanged because they are not experimental loads.
|
||||||
|
Like other transport actions, they are ignored while an experimental load is running.
|
||||||
|
|
||||||
|
## EXPERIMENTAL — Load next / previous / playlist item: not a guaranteed cue/preload
|
||||||
|
|
||||||
|
> **EXPERIMENTAL: these buttons deliberately start the next or previous video,
|
||||||
|
> then try to stop it. They do not load an item paused, and cannot guarantee that
|
||||||
|
> no moving frames reach the output. Load next has been reported working on the
|
||||||
|
> user's MPC-HC setup. Load previous shares that sequence but still needs its own
|
||||||
|
> real-player check. Both remain experimental; success on one setup does not
|
||||||
|
> establish reliable production cue/preload behavior for other media or systems.**
|
||||||
|
|
||||||
|
Find **Load previous** and **Load next** under **Presets → MPC_DEV → Experimental**.
|
||||||
|
The folder identifies their experimental nature; names and button labels omit
|
||||||
|
EXP. Existing copied buttons need re-adding to remove the old label; linked
|
||||||
|
presets update. These buttons remain separate from regular transport presets.
|
||||||
|
|
||||||
|
**Do not first test this on a live program output.** Use a spare button and an
|
||||||
|
output where brief playback is acceptable. Observe the actual video and listen
|
||||||
|
to the actual audio; a green connection indicator or successful HTTP response
|
||||||
|
is not proof that the output was silent or that no frames played.
|
||||||
|
|
||||||
|
**What this experiment does and does not guarantee:**
|
||||||
|
|
||||||
|
- It waits for MPC-HC's _reported_ mute state before advancing. This is not a
|
||||||
|
measurement of physical audio output, and another controller can change mute.
|
||||||
|
- It intentionally sends the normal autoplaying Next or Previous command. Stop can arrive
|
||||||
|
before loading finishes or take effect late; retries reduce this risk but do
|
||||||
|
not remove it. Network delays and player behavior affect the result.
|
||||||
|
- **LOADED NEXT / LOADED PREV is a status-based confirmation, not a guarantee of seamless
|
||||||
|
preload.** It means a different reported filename remained stopped for at
|
||||||
|
least 500 ms and the original mute setting was confirmed. It does not prove
|
||||||
|
which playlist entry was selected, that no frames played, or where playback
|
||||||
|
will resume. Check these on your player and media.
|
||||||
|
- Failure can leave the new file playing but muted if Stop cannot be delivered
|
||||||
|
or applied. **FAILED NEXT / FAILED PREV does not mean the player is safely stopped.** Inspect
|
||||||
|
MPC-HC before manually unmuting, playing, or pressing either Load button again.
|
||||||
|
- A configured backup has its own outcome. Main success does not certify the
|
||||||
|
backup. A player that was already muted stays muted after success.
|
||||||
|
|
||||||
|
### Experimental sequence
|
||||||
|
|
||||||
|
1. Read fresh state and remember the current file and mute setting.
|
||||||
|
2. Mute if needed and wait for player feedback confirming mute. Never retry a
|
||||||
|
mute toggle blindly; if mute cannot be confirmed, do not advance.
|
||||||
|
3. Send Next File (`920`) or Previous File (`919`) once, then Stop (`890`) immediately after its HTTP
|
||||||
|
response, without waiting for a status poll in between.
|
||||||
|
4. Check about every 50 ms (plus HTTP latency), retrying Stop while not stopped.
|
||||||
|
Require a different nonempty filename and stopped state continuously observed
|
||||||
|
for at least 500 ms. Each confirmation phase has a 5-second deadline; an
|
||||||
|
in-flight request can add its normal 2.5-second timeout.
|
||||||
|
5. Only then restore the original mute setting and confirm it. A player that
|
||||||
|
started muted stays muted.
|
||||||
|
|
||||||
|
Each navigation button shows **LOADING**, then **LOADED** or **FAILED** with
|
||||||
|
**NEXT** or **PREV**. Two seconds after completion it returns to **LOAD NEXT** or
|
||||||
|
**LOAD PREV** (with its arrow icon). This display reset does not send a command
|
||||||
|
or erase the result. Offline still overrides the navigation buttons.
|
||||||
|
|
||||||
|
Add the passive **Last load result** preset from **Experimental** for a retained
|
||||||
|
record. It shows **NO LOAD YET** initially, amber **LOADING**, blue **LOADED** plus the start of the video name,
|
||||||
|
or red **LAST FAILED**, with the direction. The latest result stays until the
|
||||||
|
next load attempt, even after Play, Stop, a file change, or a disconnect. This is
|
||||||
|
**history, not confirmation that the player is still stopped or connected**.
|
||||||
|
Connection reconfiguration or module restart resets it. Pressing it does nothing.
|
||||||
|
|
||||||
|
`load_result_status`, `load_result_direction`, `load_result_file`, and
|
||||||
|
`load_result_detail` expose the retained result; add `backup_` for the backup.
|
||||||
|
The filename is recorded on success; failure details explain the problem.
|
||||||
|
The result button displays up to 16 visible characters of the basename (extension
|
||||||
|
omitted), split over two lines and ending with an ellipsis when truncated. The
|
||||||
|
full filename remains in `load_result_file`; `file` is the current player filename.
|
||||||
|
The display uses the retained successful-load filename, not a later playing file.
|
||||||
|
`load_next_status` / `load_next_detail` and `load_previous_status` /
|
||||||
|
`load_previous_detail` retain their existing operation/current-state behavior.
|
||||||
|
Starting one direction resets the other direction's result to idle. These
|
||||||
|
variables are not subject to the two-second button-display reset.
|
||||||
|
|
||||||
|
The presets follow the main player. Each targeted player runs independently.
|
||||||
|
The default target is Both; no backup is required. Main success does not imply
|
||||||
|
backup success—check backup/sync status and the backup result variables.
|
||||||
|
|
||||||
|
Repeated presses while running, including the opposite direction, are coalesced;
|
||||||
|
they do not queue another navigation. Other module commands are ignored
|
||||||
|
until the sequence finishes, to prevent Play or Mute from interfering. Direct
|
||||||
|
MPC-HC control or another connection can still interfere. Reconfiguration and
|
||||||
|
module shutdown cancel the sequence without attempting to unmute.
|
||||||
|
|
||||||
|
If loading cannot be confirmed, the action attempts a final Stop and does not
|
||||||
|
restore audio. Check the player before manually unmuting or trying again. If a
|
||||||
|
network error occurs during the final unmute, its outcome is unknown; the action
|
||||||
|
reports failure and never blindly repeats the toggle.
|
||||||
|
|
||||||
|
The web status reports a filename, not a playlist-entry identity. Consecutive
|
||||||
|
entries with the same reported filename, a single-item loop, or reaching either end
|
||||||
|
without changing files cannot be confirmed and remain muted. A different filename
|
||||||
|
following the single navigation command is the available evidence of movement;
|
||||||
|
external playlist changes cannot be distinguished. True preload without any
|
||||||
|
playback still requires an MPC-HC open-paused API or a helper on the player PC.
|
||||||
|
|
||||||
|
### Load a specific playlist item
|
||||||
|
|
||||||
|
**Load playlist item 1–10** presets are in **Experimental**. They use the same
|
||||||
|
experimental mute → select → Stop → verify → restore-mute sequence and the same
|
||||||
|
two-second result display. **Last load result** retains the outcome as **#1**, **#2**,
|
||||||
|
on failures/in-progress; successful results show the video name.
|
||||||
|
`load_result_direction` contains `item_1`, `item_2`, etc.
|
||||||
|
|
||||||
|
Load next / previous use separate symbol and label layers, with the symbol raised
|
||||||
|
to leave room for larger text. Re-add existing copied presets to get the new layout.
|
||||||
|
|
||||||
|
Numbered Load presets use Companion 5 layered graphics: a small **↓ LOAD** title
|
||||||
|
above a large item number. Re-add existing copied presets to get this layout;
|
||||||
|
linked presets update automatically.
|
||||||
|
|
||||||
|
The action is reusable, not limited to ten items. Duplicate a numbered preset
|
||||||
|
and edit **Playlist item number (1 = first)** in its action and all three **Load
|
||||||
|
playlist item state** feedbacks to the same number. Set the large number text
|
||||||
|
layer to match. The small title and large number are separate editable layers.
|
||||||
|
Numbers from 1 to 10000 are supported, subject to the actual playlist length.
|
||||||
|
The title changes for loading, loaded, failed, or offline; the large number stays visible.
|
||||||
|
|
||||||
|
These are **playlist positions, not saved file identities**. Reordering a playlist
|
||||||
|
changes what a numbered button loads. Presets remain available even if the
|
||||||
|
playlist has fewer than ten entries. Each press fetches `/playlist.json` and
|
||||||
|
rejects absent items before muting or navigating. An unsupported or malformed
|
||||||
|
playlist response also aborts without starting the sequence; relative Load
|
||||||
|
next/previous do not require this endpoint. Names are not embedded in presets,
|
||||||
|
so a copied button cannot silently retain an old filename label after reordering.
|
||||||
|
|
||||||
|
Each player validates its own playlist and selects the same item number. Keep
|
||||||
|
main and backup playlists in matching order. The action does not map filenames
|
||||||
|
between players, and main success does not imply backup success.
|
||||||
|
|
||||||
|
Indexed loading uses MPC-HC's `wm_command=-3&index=N` with zero-based numbering
|
||||||
|
internally. It checks the selected index as well as stopped state and a changed
|
||||||
|
filename, and aborts if the playlist entries/labels/durations change during the
|
||||||
|
sequence. A selected index can update before the media has loaded, so it is not
|
||||||
|
sufficient evidence by itself. Different entries with the same reported filename
|
||||||
|
still cannot be confirmed safely and leave audio muted after timeout.
|
||||||
|
|
||||||
|
If the requested item is already selected with media loaded, it is stopped in
|
||||||
|
place without reopening it; the original mute setting is preserved. If the
|
||||||
|
player is idle, it opens the selected item instead. **Indexed loading can briefly
|
||||||
|
play video too. It remains experimental and needs real-player testing.** Failed
|
||||||
|
validation before muting leaves the original audio setting untouched.
|
||||||
|
|
||||||
|
### Before considering this usable for your show
|
||||||
|
|
||||||
|
Test stopped and playing starting states; initially muted and unmuted audio;
|
||||||
|
slow-loading files; the first and last playlist entries; repeat/loop behavior; duplicate
|
||||||
|
filenames; connection loss; repeated presses; and main/backup failures. Confirm
|
||||||
|
that Play starts the loaded media from the expected position. Keep using the
|
||||||
|
regular transport controls until this experiment is satisfactory with your
|
||||||
|
actual player, media, network, and output routing. This label remains experimental
|
||||||
|
until explicitly reviewed and promoted; success in mocks alone is insufficient.
|
||||||
|
|
||||||
|
## Optional backup player
|
||||||
|
|
||||||
|
In this connection's configuration, keep your existing **Main player** host/port
|
||||||
|
and optionally fill in **Backup IP address or hostname** and its web-interface
|
||||||
|
port. Leave the backup host blank when using one player. The module does not
|
||||||
|
infer a backup address from other connections.
|
||||||
|
|
||||||
|
All actions now have a **Player target** option: **Both players** (default),
|
||||||
|
**Main only**, or **Backup only**. Existing buttons without the option also
|
||||||
|
use Both. With no backup configured, Both sends only to the main. Each player
|
||||||
|
receives its command independently; failure or delay on one does not prevent
|
||||||
|
delivery to the other. Commands are not retried.
|
||||||
|
|
||||||
|
The main player remains authoritative for normal transport feedback, countdown,
|
||||||
|
progress, existing variables, and connection health. Backup failures do not
|
||||||
|
turn this connection red or generate recurring error logs. The module does not
|
||||||
|
promote the backup to main or switch video outputs automatically.
|
||||||
|
|
||||||
|
Add **Backup sync status** from **Transport & timing**. This is a passive display:
|
||||||
|
pressing it does not start playback or force synchronization.
|
||||||
|
|
||||||
|
| Display | Color | Meaning |
|
||||||
|
| ------------------------- | ----- | ---------------------------------------------------- |
|
||||||
|
| No backup | Grey | Backup address is blank |
|
||||||
|
| Backup offline | Blue | Configured backup has no available status |
|
||||||
|
| Backup empty | Blue | Backup responds but has no active media |
|
||||||
|
| Backup config | Blue | Invalid backup address/port or same endpoint as main |
|
||||||
|
| In sync | Green | Both players agree within the configured tolerance |
|
||||||
|
| Out of sync | Red | Media, state, speed, or timing differs |
|
||||||
|
| Main offline / Main empty | Amber | Main cannot provide a usable reference |
|
||||||
|
| Checking sync | Blue | Waiting for fresh samples |
|
||||||
|
|
||||||
|
Comparison uses case-insensitive filenames (allowing different media folders),
|
||||||
|
duration, playback state, playback rate, and estimated position. The default
|
||||||
|
**Playback sync tolerance** is **1000 ms**, configurable from 100–10000 ms.
|
||||||
|
Sample timestamps and playback rates compensate for different poll arrival
|
||||||
|
times; this is a monitoring estimate, not frame-accurate synchronization or a
|
||||||
|
media-content checksum. A brief mismatch can appear while files load or commands
|
||||||
|
reach the two players. Use the same ordered playlists on both machines.
|
||||||
|
|
||||||
|
**Include mute and volume in sync comparison** is off by default, allowing an
|
||||||
|
intentionally silent backup. Enable it if audio settings should match too.
|
||||||
|
Toggle commands (such as Mute) are sent to each player as-is; they do not copy
|
||||||
|
the main's state to the backup or repair an existing mismatch. Use Main only or
|
||||||
|
Backup only actions to correct the relevant player independently.
|
||||||
|
|
||||||
|
Use distinct player addresses. An identical configured endpoint is rejected as
|
||||||
|
a backup to prevent double commands; different hostnames resolving to the same
|
||||||
|
machine are not detected. Unavailable backup states remain informational.
|
||||||
|
|
||||||
|
For custom buttons, `sync_label` provides display text, `sync_status` a stable
|
||||||
|
code (`no_backup`, `backup_offline`, `backup_empty`, `backup_config`, `in_sync`,
|
||||||
|
`out_of_sync`, `main_offline`, `main_empty`, `checking`), and `sync_detail` explains
|
||||||
|
the comparison. `backup_offset_ms` is estimated backup minus main position;
|
||||||
|
positive means ahead. Every main variable also has a `backup_` counterpart,
|
||||||
|
plus `backup_configured` and `backup_status`. Unknown values are cleared;
|
||||||
|
Companion can display null values as empty strings. **Backup in sync with main**,
|
||||||
|
**Backup out of sync with main**, and **Backup sync status** feedbacks are available
|
||||||
|
for custom buttons.
|
||||||
|
|
||||||
|
## Variables and custom feedback
|
||||||
|
|
||||||
|
The elapsed preset uses **ELAPSED** with size 14 text to avoid wrapping. The
|
||||||
|
playback-state preset uses size 14 text to display **Playing**, **Paused**,
|
||||||
|
**Stopped**, or **Idle** without clipping.
|
||||||
|
|
||||||
|
These are connection/module variables, not button-local variables. With the
|
||||||
|
connection labelled `MPC_DEV`, use `$(MPC_DEV:remaining)` in button text.
|
||||||
|
Presets are wired automatically to the connection label.
|
||||||
|
|
||||||
|
| Variables | Values |
|
||||||
|
| ---------------------------------------------------------- | ----------------------------------------------------------- |
|
||||||
|
| `state`, `connected` | Playback state string and status availability boolean |
|
||||||
|
| `playing`, `stopped`, `paused`, `muted` | Booleans; null when status is unavailable |
|
||||||
|
| `volume`, `file`, `version`, `rate` | Volume percent, filename, player version, playback rate |
|
||||||
|
| `elapsed`, `duration`, `remaining` | Formatted time (`MM:SS` or `H:MM:SS`); `--:--` when unknown |
|
||||||
|
| `elapsed_seconds`, `duration_seconds`, `remaining_seconds` | Numeric media seconds; null when unknown |
|
||||||
|
| `progress` | Percentage from 0 to 100; null when duration is unknown |
|
||||||
|
|
||||||
|
`state_label` provides capitalized display text; `state` retains lowercase values
|
||||||
|
for expressions and existing buttons.
|
||||||
|
|
||||||
|
Mute is separate from volume zero: `muted` follows MPC's mute switch.
|
||||||
|
For existing/custom buttons, add **Playing**, **Stopped**, **Paused**, **Audio
|
||||||
|
muted**, **No active media (idle)**, **Status unavailable**, or **Playback progress
|
||||||
|
bar** from the module's Feedbacks list. Existing buttons are not rewritten;
|
||||||
|
replace them with transport presets or add feedback manually.
|
||||||
|
|
||||||
|
## Edit, test, and update
|
||||||
|
|
||||||
|
On this machine, use the bundled runtime in a terminal:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
export PATH="/home/beffroi/Softs/companion-x64/resources/node-runtimes/node22/bin:$PATH"
|
||||||
|
cd companion-modules/media-player-classic
|
||||||
|
npm test
|
||||||
|
npm run check
|
||||||
|
npm run format # apply formatting after edits
|
||||||
|
npm run package # produce media-player-classic-1.3.0-dev.0.tgz
|
||||||
|
```
|
||||||
|
|
||||||
|
Companion watches the developer folder and reloads the module after source
|
||||||
|
changes. No copying or packaging is needed for everyday edits. Disable and
|
||||||
|
re-enable `MPC_DEV` if a reload does not occur. Changes briefly interrupt only
|
||||||
|
connections using this development module.
|
||||||
|
|
||||||
|
After pulling dependency updates, rerun `setup.py` (without
|
||||||
|
`--companion-config` if already configured). It uses `npm ci` to reproduce the
|
||||||
|
locked dependency versions. Keep the lockfile committed. Packages, dependencies,
|
||||||
|
and npm caches are ignored by Git.
|
||||||
|
|
||||||
|
For another computer later, build the package and import the `.tgz` through
|
||||||
|
Companion's Modules page. Test the packaged build separately from source.
|
||||||
|
No fork, publishing, or additional update server is required for local use.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
- `src/main.js`: Companion lifecycle, configuration, and connection status.
|
||||||
|
- `src/client.js`: HTTP transport, timeout, and cancellation.
|
||||||
|
- `src/player.js`: independent player polling and command lifecycle.
|
||||||
|
- `src/redundancy.js`: backup comparison and variables.
|
||||||
|
- `src/commands.js`: original command catalog and stable action IDs.
|
||||||
|
- `src/definitions.js`: action and preset definitions.
|
||||||
|
- `src/state.js`: JSON/HTML normalization, timing, and module variables.
|
||||||
|
- `src/feedbacks.js`: state feedback and RGBA progress graphics.
|
||||||
|
- `test/`: mock HTTP integration tests; never contact the real player.
|
||||||
|
- `companion/HELP.md`: help displayed inside Companion.
|
||||||
|
|
||||||
|
## Battle-testing checklist
|
||||||
|
|
||||||
|
Automated tests exercise all 138 command URLs against a mock server, HTTP errors,
|
||||||
|
redirect refusal, timeout, cancellation, JSON/HTML parsing, feedback states,
|
||||||
|
countdown/progress edge cases, polling recovery, independent dual-player delivery,
|
||||||
|
main authority, optional backup failures, comparison tolerance, and configuration validation. They do
|
||||||
|
not establish that every legacy command still works in current MPC-HC.
|
||||||
|
|
||||||
|
On a spare page with a disposable media file:
|
||||||
|
|
||||||
|
- Record the exact MPC-HC version, Companion version, and module Git commit.
|
||||||
|
- Check Play, Pause, Stop, seeking, volume, mute, fullscreen, and playlist navigation.
|
||||||
|
- Check presets render and trigger the expected action once.
|
||||||
|
- Disable the player web interface, trigger an action, and confirm a useful error.
|
||||||
|
Re-enable it and confirm the next action succeeds; commands are never retried.
|
||||||
|
- Edit the module and verify reload; disable/re-enable its connection.
|
||||||
|
- Restart Companion and verify the developer connection returns.
|
||||||
|
- Test existing button compatibility before moving your normal MPC connection to dev.
|
||||||
|
- Import and smoke-test a packaged build before upstreaming.
|
||||||
|
|
||||||
|
Live validation reads status and renders presets inside Companion without
|
||||||
|
sending playback commands. Use the checklist above to test actual playback,
|
||||||
|
mute/unmute, seeks, end-of-file behavior, and playlist navigation on your media.
|
||||||
|
Open File opens the player's dialog; it does not accept or upload a path.
|
||||||
|
|
||||||
|
To roll back, select the official version for any connection using dev, or remove
|
||||||
|
`MPC_DEV`, disable Developer Modules, and restart Companion. The helper's
|
||||||
|
`config.json.before-mpc-dev-*` backup can restore launcher settings while Companion
|
||||||
|
is stopped. Your normal button configuration is not changed by the helper.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- [Companion developer folders](https://companion.free/for-developers/module-development/local-modules/)
|
||||||
|
- [Module packaging](https://companion.free/for-developers/module-development/module-lifecycle/module-packaging/)
|
||||||
|
- [Original MPC module](https://github.com/bitfocus/companion-module-media-player-classic)
|
||||||
|
|
||||||
|
- [MPC-HC status endpoints](https://github.com/clsid2/mpc-hc/blob/develop/src/mpc-hc/WebClientSocket.cpp)
|
||||||
|
- [Ontime progress feedback reference](https://github.com/bitfocus/companion-module-getontime-ontime/blob/main/src/feedbacks/progress.ts)
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
# Upstream provenance
|
||||||
|
|
||||||
|
Based on https://github.com/bitfocus/companion-module-media-player-classic
|
||||||
|
commit `2ed43ac76a1d69f3e27bdb07ceb84233065ced2b` (version 1.0.1). The command catalog and preset behavior
|
||||||
|
come from that MIT-licensed module. Its copyright notice is preserved in LICENSE.
|
||||||
|
|
||||||
|
This is a local development port to Companion API 2, not an upstream release.
|
||||||
|
Existing numeric action IDs and host/port configuration keys are preserved.
|
||||||
|
No public fork or pull request has been created.
|
||||||
|
|
@ -0,0 +1,159 @@
|
||||||
|
# Media Player Classic — local development
|
||||||
|
|
||||||
|
Enable **View → Options → Player → Web Interface → Listen on port** in MPC-HC.
|
||||||
|
The default port is **13579**. Enter the player computer's IP address and port
|
||||||
|
in this connection. Allow remote access from the Companion computer if needed.
|
||||||
|
|
||||||
|
## Ready-to-use presets
|
||||||
|
|
||||||
|
Choose **Transport & timing** in this connection's Presets:
|
||||||
|
|
||||||
|
- **Play**: subdued blue while stopped; full green while playing; amber while paused. Press to play/resume.
|
||||||
|
- **Stop**: subdued red while playing; full red while stopped.
|
||||||
|
- **Previous / Next**: navigate playlist items (verified command IDs 919/920).
|
||||||
|
These load and start playback; the web API has no reliable open-next-paused
|
||||||
|
command.
|
||||||
|
- **Mute**: red **MUTED** when the player mute switch is on.
|
||||||
|
- **Pause**: amber while paused.
|
||||||
|
- **Remaining / Elapsed**: live time with a progress bar (passive displays).
|
||||||
|
- **Playback state**: current state with matching color.
|
||||||
|
|
||||||
|
The bar fills left to right, turning amber with 30 media seconds left and red
|
||||||
|
with 10 seconds left. All 138 original command presets remain in **All commands**.
|
||||||
|
Open File opens a dialog on the player computer; it does not upload a file.
|
||||||
|
|
||||||
|
Transport buttons use white labels on filled backgrounds. Play is subdued blue
|
||||||
|
until playing, when it becomes full green; Stop is subdued red until stopped,
|
||||||
|
when it becomes full red. Previous/Next stay subdued blue. Mute is neutral when
|
||||||
|
unmuted and full red with **MUTED** text when muted. Playback state is full green
|
||||||
|
while playing, full red while stopped, and amber while paused. Timers stay dark
|
||||||
|
with progress bars; backup sync keeps its original status colors.
|
||||||
|
Re-add copied presets to apply styling updates; linked presets update automatically.
|
||||||
|
|
||||||
|
## Large timers
|
||||||
|
|
||||||
|
In **Timers — large HH / MM / SS**, place **Remaining HH (1/3)**, **Remaining MM
|
||||||
|
(2/3)**, and **Remaining SS (3/3)** next to one another. A matching **Elapsed** set
|
||||||
|
is available. These passive buttons show large zero-padded digits, following the
|
||||||
|
main player's position; no playback commands are sent when pressed.
|
||||||
|
|
||||||
|
Remaining digits turn amber at 30 seconds left and red at 10 seconds. Unavailable
|
||||||
|
values show grey **--**. Remaining rounds up, elapsed rounds down, and hours do
|
||||||
|
not wrap at 24. Custom display variables are `remaining_hh/mm/ss` and
|
||||||
|
`elapsed_hh/mm/ss` (each suffix is a separate variable).
|
||||||
|
|
||||||
|
## Playlist — direct playback
|
||||||
|
|
||||||
|
The **Playlist** folder has **Play item 1–10** presets. These directly select and
|
||||||
|
play the numbered item using MPC-HC's normal command; there is no mute/Stop
|
||||||
|
sequence. Mute remains unchanged. Duplicate a preset and change the action's item
|
||||||
|
number and button text for other positions. Numbers follow current playlist order;
|
||||||
|
keep backup order aligned. Missing items are rejected before selection.
|
||||||
|
|
||||||
|
## EXPERIMENTAL — Load next / Load previous
|
||||||
|
|
||||||
|
Find **Load previous** and **Load next** in the separate **Experimental** preset
|
||||||
|
section. Names and button labels omit EXP; their experimental status has not changed.
|
||||||
|
|
||||||
|
**These deliberately start the selected video and then try to stop it. They are
|
||||||
|
not true paused loading, and moving video can briefly reach the output. Load next
|
||||||
|
has been reported working on the user's real MPC-HC setup; Load previous still
|
||||||
|
needs its own real-player check. Both remain experimental.**
|
||||||
|
|
||||||
|
It confirms mute, sends Next or Previous once and Stop immediately, retries Stop, and restores
|
||||||
|
the original mute state only after a changed filename stays stopped for 500 ms.
|
||||||
|
Already-muted players stay muted. Duplicate reported filenames cannot be verified.
|
||||||
|
Other module commands are ignored while it runs. The button follows the main;
|
||||||
|
backup results are in `backup_load_next_status` / `backup_load_next_detail` (or `load_previous` equivalents).
|
||||||
|
|
||||||
|
**FAILED NEXT / FAILED PREV does not guarantee playback stopped.** Failed loading does not
|
||||||
|
restore audio; a lost response during final unmute leaves the mute outcome
|
||||||
|
uncertain. Inspect MPC-HC before manually unmuting or retrying. **LOADED NEXT / LOADED PREV**
|
||||||
|
is based on reported state, not proof of silent or seamless preload.
|
||||||
|
|
||||||
|
Test on non-live output and read the README's experimental section before use.
|
||||||
|
Re-add existing copied presets to remove the EXP label; linked presets update.
|
||||||
|
|
||||||
|
### Load playlist items 1–10
|
||||||
|
|
||||||
|
The **Experimental** folder also contains ten numbered **Load playlist item**
|
||||||
|
presets. To make another, duplicate one and set its action's item number and
|
||||||
|
**Load playlist item state** feedbacks' item numbers to match (1 = first),
|
||||||
|
and update the large number text layer. A small title sits above the large number.
|
||||||
|
The action accepts 1–10000, but checks the actual playlist before muting.
|
||||||
|
Missing items or unavailable `/playlist.json` abort without navigation.
|
||||||
|
|
||||||
|
Numbers follow playlist order, not file identity; keep main/backup orders aligned.
|
||||||
|
The same experimental brief-playback limitation applies. Selection is verified
|
||||||
|
by index, changed filename, and stable stopped state; playlist changes abort.
|
||||||
|
An already selected, loaded item is stopped without reopening. Duplicate reported
|
||||||
|
filenames across different entries cannot be confirmed. Last load result shows the video name on success and **#N** on failure, and `load_result_direction` uses `item_N`. Results reset after two seconds
|
||||||
|
on the numbered buttons and remain on the last-result display.
|
||||||
|
|
||||||
|
### Load status display
|
||||||
|
|
||||||
|
Load previous/next show their result for two seconds, then return to their normal
|
||||||
|
labels. Add **Last load result** from **Experimental** to keep the latest result:
|
||||||
|
neutral **NO LOAD YET**, amber **LOADING**, blue **LOADED** with the video name, or red **LAST FAILED**,
|
||||||
|
with NEXT/PREV. This passive button keeps the result until the next load attempt,
|
||||||
|
even after playback changes or disconnection. It records history, not current
|
||||||
|
player readiness. Reconfiguration/restart clears it.
|
||||||
|
|
||||||
|
Successful results show the first 16 characters of the filename without its
|
||||||
|
extension; the full name is in `load_result_file`. Re-add copied numbered Load
|
||||||
|
presets for the new layered layout.
|
||||||
|
|
||||||
|
Use `load_result_status`, `load_result_direction`, `load_result_file`, and
|
||||||
|
`load_result_detail` for details; backup equivalents have a `backup_` prefix.
|
||||||
|
|
||||||
|
## Optional backup
|
||||||
|
|
||||||
|
Configure a backup host and port to send commands to both players. Leave the host
|
||||||
|
blank when unused. Every action offers **Both players** (default), **Main only**,
|
||||||
|
or **Backup only**. Existing actions without a target default to Both.
|
||||||
|
|
||||||
|
The main is the authority for normal feedback, timing, variables, and connection
|
||||||
|
health. Backup failures do not turn the connection into an error. Both players
|
||||||
|
receive commands independently; neither can block delivery to the other.
|
||||||
|
|
||||||
|
Add the **Backup sync status** preset:
|
||||||
|
|
||||||
|
- Grey **No backup**: no backup host configured.
|
||||||
|
- Blue **Backup offline / Backup empty / Backup config**: optional backup unavailable.
|
||||||
|
- Green **In sync**: playback agrees within tolerance.
|
||||||
|
- Red **Out of sync**: media, state, rate, or timing differs.
|
||||||
|
- Amber **Main offline / Main empty**: no usable main reference.
|
||||||
|
|
||||||
|
The preset is informational; pressing it does not synchronize players. Default
|
||||||
|
position tolerance is 1000 ms (configurable). Filenames and durations identify
|
||||||
|
media; different folders are allowed. Use matching ordered playlists. Timing
|
||||||
|
comparison estimates position from poll timestamps, not frame-accurate sync.
|
||||||
|
Mute/volume comparison is optional and off by default for silent backups.
|
||||||
|
|
||||||
|
Use `sync_label`, `sync_status`, `sync_detail`, and `backup_offset_ms` variables
|
||||||
|
for more detail; main variables also have `backup_` equivalents. Toggle commands
|
||||||
|
are sent as-is and do not repair mismatches. No automatic failover or video-output
|
||||||
|
switching is performed.
|
||||||
|
|
||||||
|
## Live state
|
||||||
|
|
||||||
|
Feedback follows MPC-HC, including changes made outside Companion. The module
|
||||||
|
prefers `/status.json`, falling back to `/variables.html` for older versions.
|
||||||
|
Status polling defaults to 500 ms (configurable 250–5000 ms). Commands also
|
||||||
|
request fresh status. Regular commands are not automatically retried; experimental loading retries Stop.
|
||||||
|
|
||||||
|
Unavailable status clears active feedback; presets show **OFFLINE**. Requests
|
||||||
|
have a 2.5-second timeout and polling recovers automatically. Idle (no active
|
||||||
|
media graph) is distinct from stopped. Unknown duration displays `--:--` and
|
||||||
|
hides the bar. Countdown is remaining media time, not a prediction adjusted
|
||||||
|
for playback speed. Mute state is separate from a volume setting of zero.
|
||||||
|
|
||||||
|
For custom buttons use connection variables, for example
|
||||||
|
`$(MPC_DEV:remaining)`, `$(MPC_DEV:elapsed)`, `$(MPC_DEV:state)`, or
|
||||||
|
`$(MPC_DEV:progress)` (replace MPC_DEV with your connection label).
|
||||||
|
Numeric seconds, volume, mute, filename, rate, version, and connection status
|
||||||
|
are also exposed. State/audio booleans become null when unavailable.
|
||||||
|
Add the module's boolean state feedbacks or **Playback progress bar** to
|
||||||
|
existing buttons; they are not modified automatically.
|
||||||
|
|
||||||
|
This is a local test build. Select **dev** as the connection's module version.
|
||||||
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 364 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
|
@ -0,0 +1,27 @@
|
||||||
|
{
|
||||||
|
"$schema": "../node_modules/@companion-module/base/assets/manifest.schema.json",
|
||||||
|
"type": "connection",
|
||||||
|
"id": "media-player-classic",
|
||||||
|
"name": "Media Player Classic (local development)",
|
||||||
|
"shortname": "MPC",
|
||||||
|
"description": "Local MPC-HC development module",
|
||||||
|
"version": "1.3.0-dev.0",
|
||||||
|
"license": "MIT",
|
||||||
|
"maintainers": [
|
||||||
|
{
|
||||||
|
"name": "Beffroi"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"runtime": {
|
||||||
|
"type": "node22",
|
||||||
|
"api": "nodejs-ipc",
|
||||||
|
"apiVersion": "2.1.3",
|
||||||
|
"entrypoint": "../src/main.js"
|
||||||
|
},
|
||||||
|
"legacyIds": [],
|
||||||
|
"manufacturer": "MPC-HC",
|
||||||
|
"products": ["Media Player Classic"],
|
||||||
|
"keywords": ["Video", "Media"],
|
||||||
|
"repository": "git+https://git.dandaedre.com/Beffroi/beffroi-tools.git",
|
||||||
|
"bugs": "https://git.dandaedre.com/Beffroi/beffroi-tools/issues"
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
{
|
||||||
|
"name": "media-player-classic",
|
||||||
|
"version": "1.3.0-dev.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"main": "src/main.js",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": "^22.20"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"test": "node --test test/*.test.js",
|
||||||
|
"check": "prettier --check .",
|
||||||
|
"format": "prettier --write .",
|
||||||
|
"package": "companion-module-build"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@companion-module/base": "2.1.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@companion-module/tools": "3.1.1",
|
||||||
|
"prettier": "3.9.9"
|
||||||
|
},
|
||||||
|
"prettier": "@companion-module/tools/.prettierrc.json"
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,65 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Install/update dependencies and validate the local Companion module."""
|
||||||
|
import argparse
|
||||||
|
import datetime
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('--node-bin', type=Path, help='Directory containing Node.js 22.20+ and npm')
|
||||||
|
parser.add_argument('--companion-config', type=Path, help='Enable developer modules in this launcher config.json; restart Companion afterward')
|
||||||
|
parser.add_argument('--package', action='store_true', help='Also build an importable .tgz')
|
||||||
|
args = parser.parse_args()
|
||||||
|
root = Path(__file__).resolve().parent
|
||||||
|
env = os.environ.copy()
|
||||||
|
if args.node_bin:
|
||||||
|
env['PATH'] = str(args.node_bin.resolve()) + os.pathsep + env.get('PATH', '')
|
||||||
|
node = shutil.which('node', path=env.get('PATH'))
|
||||||
|
npm = shutil.which('npm', path=env.get('PATH'))
|
||||||
|
if not node or not npm:
|
||||||
|
parser.error('Install Node.js 22.20+ (22.x) with npm, or pass --node-bin.')
|
||||||
|
version = subprocess.check_output([node, '--version'], text=True, env=env).strip()
|
||||||
|
parts = version.lstrip('v').split('.')
|
||||||
|
if int(parts[0]) != 22 or int(parts[1]) < 20:
|
||||||
|
parser.error(f'Found {version}; use Node.js 22.20+ (22.x) for the pinned module build tools.')
|
||||||
|
for command in [['ci', '--no-audit', '--no-fund', '--cache', str(root / '.npm-cache')], ['test'], ['run', 'check']]:
|
||||||
|
subprocess.run([npm, *command], cwd=root, env=env, check=True)
|
||||||
|
if args.package:
|
||||||
|
subprocess.run([npm, 'run', 'package'], cwd=root, env=env, check=True)
|
||||||
|
dev_path = root.parent
|
||||||
|
if args.companion_config:
|
||||||
|
config_path = args.companion_config.expanduser().resolve(strict=True)
|
||||||
|
config = json.loads(config_path.read_text())
|
||||||
|
current = config.get('dev_modules_path')
|
||||||
|
if current and Path(current).resolve() != dev_path:
|
||||||
|
parser.error(f'Existing developer folder is {current}; refusing to replace it. Add this module there manually.')
|
||||||
|
if not config.get('enable_developer') or current != str(dev_path):
|
||||||
|
stamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f')
|
||||||
|
backup = config_path.with_name(config_path.name + '.before-mpc-dev-' + stamp)
|
||||||
|
shutil.copy2(config_path, backup)
|
||||||
|
config.update(enable_developer=True, dev_modules_path=str(dev_path))
|
||||||
|
temporary = None
|
||||||
|
try:
|
||||||
|
with tempfile.NamedTemporaryFile(mode='w', dir=config_path.parent, delete=False) as file:
|
||||||
|
temporary = Path(file.name)
|
||||||
|
json.dump(config, file, indent=2)
|
||||||
|
file.write('\n')
|
||||||
|
shutil.copymode(config_path, temporary)
|
||||||
|
os.replace(temporary, config_path)
|
||||||
|
finally:
|
||||||
|
if temporary and temporary.exists():
|
||||||
|
temporary.unlink()
|
||||||
|
print(f'Launcher configuration updated; backup: {backup}')
|
||||||
|
print('Restart Companion to load the developer settings. Existing connections retain their selected version.')
|
||||||
|
print(f'Developer modules folder: {dev_path}')
|
||||||
|
print('Enable developer modules in the Companion launcher and select the dev version of MPC-HC in Connections.')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,94 @@
|
||||||
|
import { normalizeStatus, parseVariables } from './state.js'
|
||||||
|
|
||||||
|
export function endpoint(config) {
|
||||||
|
const host = String(config.host ?? '').trim()
|
||||||
|
const port = Number(config.port ?? 13579)
|
||||||
|
if (!host || /[\s/@?#]/.test(host) || !Number.isInteger(port) || port < 1 || port > 65535) {
|
||||||
|
throw new Error('Set a valid MPC-HC host and port (1–65535).')
|
||||||
|
}
|
||||||
|
const url = new URL(`http://${host.includes(':') && !host.startsWith('[') ? `[${host}]` : host}:${port}/`)
|
||||||
|
return url
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MpcClient {
|
||||||
|
constructor(config, timeout = 5000) {
|
||||||
|
this.url = endpoint(config)
|
||||||
|
this.timeout = timeout
|
||||||
|
this.abort = new AbortController()
|
||||||
|
}
|
||||||
|
|
||||||
|
async request(path, readBody = false) {
|
||||||
|
const response = await fetch(new URL(path, this.url), {
|
||||||
|
signal: AbortSignal.any([this.abort.signal, AbortSignal.timeout(this.timeout)]),
|
||||||
|
redirect: 'error',
|
||||||
|
})
|
||||||
|
if (!response.ok) {
|
||||||
|
await response.body?.cancel()
|
||||||
|
const error = new Error(`MPC-HC returned HTTP ${response.status}`)
|
||||||
|
error.status = response.status
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
if (readBody) return response.text()
|
||||||
|
await response.body?.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
async command(id) {
|
||||||
|
if (!/^\d+$/.test(String(id))) throw new Error('Invalid MPC-HC command ID')
|
||||||
|
await this.request(`/command.html?wm_command=${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async playlist() {
|
||||||
|
const data = JSON.parse(await this.request('/playlist.json', true))
|
||||||
|
if (
|
||||||
|
!data ||
|
||||||
|
!Array.isArray(data.items) ||
|
||||||
|
!Number.isInteger(data.active) ||
|
||||||
|
data.active < -1 ||
|
||||||
|
data.active >= data.items.length ||
|
||||||
|
data.items.some(
|
||||||
|
(item, index) =>
|
||||||
|
!item ||
|
||||||
|
item.index !== index ||
|
||||||
|
typeof item.label !== 'string' ||
|
||||||
|
!Number.isFinite(item.duration) ||
|
||||||
|
item.duration < 0,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw new Error('Invalid MPC-HC playlist response')
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
async selectPlaylistItem(index) {
|
||||||
|
if (!Number.isSafeInteger(index) || index < 0) throw new Error('Invalid playlist index')
|
||||||
|
await this.request(`/command.html?wm_command=-3&index=${index}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async status() {
|
||||||
|
if (this.statusSource !== 'html') {
|
||||||
|
try {
|
||||||
|
const body = await this.request('/status.json', true)
|
||||||
|
// Older servers can return the home page with HTTP 200 for unknown paths.
|
||||||
|
if (!body.trimStart().startsWith('<')) {
|
||||||
|
const state = normalizeStatus(JSON.parse(body))
|
||||||
|
this.statusSource = 'json'
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (![404, 405, 501].includes(error.status)) throw error
|
||||||
|
}
|
||||||
|
const state = parseVariables(await this.request('/variables.html', true))
|
||||||
|
this.statusSource = 'html'
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
return parseVariables(await this.request('/variables.html', true))
|
||||||
|
}
|
||||||
|
|
||||||
|
async probe() {
|
||||||
|
return this.status()
|
||||||
|
}
|
||||||
|
|
||||||
|
close() {
|
||||||
|
this.abort.abort()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,141 @@
|
||||||
|
// Command IDs and labels from the upstream MPC module; see UPSTREAM.md and LICENSE.
|
||||||
|
export const commands = {
|
||||||
|
800: 'Open File',
|
||||||
|
801: 'Open DVD',
|
||||||
|
802: 'Open Device',
|
||||||
|
804: 'Close',
|
||||||
|
805: 'Save As',
|
||||||
|
806: 'Save Image',
|
||||||
|
807: 'Save Image (auto)',
|
||||||
|
808: 'Save thumbnails',
|
||||||
|
809: 'Load Subtitle',
|
||||||
|
810: 'Save Subtitle',
|
||||||
|
814: 'Properties',
|
||||||
|
816: 'Exit',
|
||||||
|
817: 'Toggle Caption&Menu',
|
||||||
|
818: 'Toggle Seeker',
|
||||||
|
819: 'Toggle Controls',
|
||||||
|
820: 'Toggle Information',
|
||||||
|
821: 'Toggle Statistics',
|
||||||
|
822: 'Toggle Status',
|
||||||
|
823: 'Toggle Subresync Bar',
|
||||||
|
824: 'Toggle Playlist Bar',
|
||||||
|
825: 'Toggle Capture Bar',
|
||||||
|
826: 'Toggle Shader Editor Bar',
|
||||||
|
827: 'View Minimal',
|
||||||
|
828: 'View Compact',
|
||||||
|
829: 'View Normal',
|
||||||
|
830: 'Fullscreen',
|
||||||
|
831: 'Fullscreen (w/o res.change)',
|
||||||
|
832: 'Zoom 50%',
|
||||||
|
833: 'Zoom 100%',
|
||||||
|
834: 'Zoom 200`%',
|
||||||
|
835: 'VidFrm Half',
|
||||||
|
836: 'VidFrm Normal',
|
||||||
|
837: 'VidFrm Double',
|
||||||
|
838: 'VidFrm Stretch',
|
||||||
|
839: 'VidFrm Inside',
|
||||||
|
840: 'VidFrm Outside',
|
||||||
|
860: 'Next AR Preset',
|
||||||
|
861: 'PnS Reset',
|
||||||
|
862: 'PnS Inc Size',
|
||||||
|
863: 'PnS Dec Size',
|
||||||
|
864: 'PnS Inc Width',
|
||||||
|
865: 'PnS Dec Width',
|
||||||
|
866: 'PnS Inc Height',
|
||||||
|
867: 'PnS Dec Height',
|
||||||
|
868: 'PnS Left',
|
||||||
|
869: 'PnS Right',
|
||||||
|
870: 'PnS Up',
|
||||||
|
871: 'PnS Down',
|
||||||
|
872: 'PnS Up/Left',
|
||||||
|
873: 'PnS Up/Right',
|
||||||
|
874: 'PnS Down/Left',
|
||||||
|
875: 'PnS Down/Right',
|
||||||
|
876: 'PnS Center',
|
||||||
|
877: 'PnS Rotate X+',
|
||||||
|
878: 'PnS Rotate X-',
|
||||||
|
879: 'PnS Rotate Y+',
|
||||||
|
880: 'PnS Rotate Y-',
|
||||||
|
881: 'PnS Rotate Z+',
|
||||||
|
882: 'PnS Rotate Z-',
|
||||||
|
884: 'Always On Top',
|
||||||
|
886: 'Options',
|
||||||
|
887: 'Play',
|
||||||
|
888: 'Pause',
|
||||||
|
889: 'Play/Pause',
|
||||||
|
890: 'Stop',
|
||||||
|
891: 'Framestep',
|
||||||
|
892: 'Framestep back',
|
||||||
|
893: 'Go To',
|
||||||
|
894: 'Decrease Rate',
|
||||||
|
895: 'Increase Rate',
|
||||||
|
896: 'Reset Rate',
|
||||||
|
897: 'Jump Backward (keyframe)',
|
||||||
|
898: 'Jump Forward (keyframe)',
|
||||||
|
899: 'Jump Backward (small)',
|
||||||
|
900: 'Jump Forward (small)',
|
||||||
|
901: 'Jump Backward (medium)',
|
||||||
|
902: 'Jump Forward (medium)',
|
||||||
|
903: 'Jump Backward (large)',
|
||||||
|
904: 'Jump Forward (large)',
|
||||||
|
905: 'Audio Delay +10ms',
|
||||||
|
906: 'Audio Delay -10ms',
|
||||||
|
907: 'Volume Up',
|
||||||
|
908: 'Volume Down',
|
||||||
|
909: 'Volume Mute',
|
||||||
|
918: 'After Playback: Turn off the monitor',
|
||||||
|
919: 'Previous Playlist Item',
|
||||||
|
920: 'Next Playlist Item',
|
||||||
|
921: 'Previous (chapter/file)',
|
||||||
|
922: 'Next (chapter/file)',
|
||||||
|
923: 'DVD Root Menu',
|
||||||
|
924: 'DVD Subtitle Menu',
|
||||||
|
925: 'DVD Audio Menu',
|
||||||
|
926: 'DVD Angle Menu',
|
||||||
|
927: 'DVD Chapter Menu',
|
||||||
|
928: 'DVD Menu Left',
|
||||||
|
929: 'DVD Menu Right',
|
||||||
|
930: 'DVD Menu Up',
|
||||||
|
931: 'DVD Menu Down',
|
||||||
|
932: 'DVD Menu Activate',
|
||||||
|
933: 'DVD Menu Back',
|
||||||
|
934: 'DVD Menu Leave',
|
||||||
|
943: 'Boss key',
|
||||||
|
948: 'Player Menu (short)',
|
||||||
|
949: 'Player Menu (long)',
|
||||||
|
950: 'Filters Menu',
|
||||||
|
951: 'Next Audio',
|
||||||
|
952: 'Prev Audio',
|
||||||
|
953: 'Next Subtitle',
|
||||||
|
954: 'Prev Subtitle',
|
||||||
|
955: 'On/Off Subtitle',
|
||||||
|
956: 'Next Audio (OGM)',
|
||||||
|
957: 'Prev Audio (OGM)',
|
||||||
|
958: 'Next Subtitle (OGM)',
|
||||||
|
959: 'Prev Subtitle (OGM)',
|
||||||
|
960: 'Next Angle (DVD)',
|
||||||
|
961: 'Prev Angle (DVD)',
|
||||||
|
962: 'Next Audio (DVD)',
|
||||||
|
963: 'Prev Audio (DVD)',
|
||||||
|
964: 'Next Subtitle (DVD)',
|
||||||
|
965: 'Prev Subtitle (DVD)',
|
||||||
|
966: 'On/Off Subtitle (DVD)',
|
||||||
|
967: 'Zoom Auto Fit',
|
||||||
|
969: 'Volume boost increase',
|
||||||
|
970: 'Volume boost decrease',
|
||||||
|
971: 'Volume boost Min',
|
||||||
|
972: 'Volume boost Max',
|
||||||
|
2302: 'Reload Subtitles',
|
||||||
|
24000: 'Subtitle Delay -',
|
||||||
|
24001: 'Subtitle Delay +',
|
||||||
|
32769: 'Tearing Test',
|
||||||
|
32770: 'Toggle Pixel Shader',
|
||||||
|
32778: 'Remaining Time',
|
||||||
|
32779: 'Toggle Direct3D fullscreen',
|
||||||
|
32780: 'Goto Prev Subtitle',
|
||||||
|
32781: 'Goto Next Subtitle',
|
||||||
|
32782: 'Shift Subtitle Left',
|
||||||
|
32783: 'Shift Subtitle Right',
|
||||||
|
32784: 'Display Stats',
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,402 @@
|
||||||
|
import { commands } from './commands.js'
|
||||||
|
import { colors } from './feedbacks.js'
|
||||||
|
|
||||||
|
export function actions(send, loadNext, loadPrevious, loadPlaylistItem, playPlaylistItem) {
|
||||||
|
const definitions = Object.fromEntries(
|
||||||
|
Object.entries(commands).map(([id, name]) => [
|
||||||
|
id,
|
||||||
|
{
|
||||||
|
name,
|
||||||
|
options: [
|
||||||
|
{
|
||||||
|
type: 'dropdown',
|
||||||
|
id: 'target',
|
||||||
|
label: 'Player target',
|
||||||
|
default: 'both',
|
||||||
|
choices: [
|
||||||
|
{ id: 'both', label: 'Both players' },
|
||||||
|
{ id: 'main', label: 'Main only' },
|
||||||
|
{ id: 'backup', label: 'Backup only' },
|
||||||
|
],
|
||||||
|
disableAutoExpression: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
callback: async (action) => send(id, action?.options?.target ?? 'both'),
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
for (const [direction, callback] of [
|
||||||
|
['next', loadNext],
|
||||||
|
['previous', loadPrevious],
|
||||||
|
]) {
|
||||||
|
if (callback)
|
||||||
|
definitions[`load_${direction}`] = {
|
||||||
|
name: `Load ${direction}`,
|
||||||
|
options: definitions['887'].options,
|
||||||
|
callback: (action) => callback(action?.options?.target ?? 'both'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [id, name, callback] of [
|
||||||
|
['load_playlist_item', 'Load playlist item', loadPlaylistItem],
|
||||||
|
['play_playlist_item', 'Play playlist item', playPlaylistItem],
|
||||||
|
]) {
|
||||||
|
if (callback)
|
||||||
|
definitions[id] = {
|
||||||
|
name,
|
||||||
|
options: [
|
||||||
|
{
|
||||||
|
type: 'number',
|
||||||
|
id: 'item',
|
||||||
|
label: 'Playlist item number (1 = first)',
|
||||||
|
default: 1,
|
||||||
|
min: 1,
|
||||||
|
max: 10000,
|
||||||
|
step: 1,
|
||||||
|
},
|
||||||
|
...definitions['887'].options,
|
||||||
|
],
|
||||||
|
callback: (action) => callback(action?.options?.item ?? 1, action?.options?.target ?? 'both'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return definitions
|
||||||
|
}
|
||||||
|
|
||||||
|
export function presets(label = 'MPC_DEV') {
|
||||||
|
const catalog = Object.fromEntries(
|
||||||
|
Object.entries(commands).map(([id, name]) => [
|
||||||
|
id,
|
||||||
|
{
|
||||||
|
type: 'simple',
|
||||||
|
name,
|
||||||
|
style: { text: name, size: 'auto', color: 0xffffff, bgcolor: 0 },
|
||||||
|
steps: [{ down: [{ actionId: id, options: { target: 'both' } }], up: [] }],
|
||||||
|
feedbacks: [],
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
|
||||||
|
const offline = {
|
||||||
|
feedbackId: 'offline',
|
||||||
|
options: {},
|
||||||
|
style: { text: 'OFFLINE', bgcolor: colors.dark, color: 0x889099 },
|
||||||
|
}
|
||||||
|
const active = (feedbackId, bgcolor, text) => ({
|
||||||
|
feedbackId,
|
||||||
|
options: {},
|
||||||
|
style: { bgcolor, color: bgcolor === colors.amber ? colors.dark : colors.white, ...(text ? { text } : {}) },
|
||||||
|
})
|
||||||
|
const button = (name, text, id, feedback = [], size = '18', bgcolor = colors.dark) => ({
|
||||||
|
type: 'simple',
|
||||||
|
name,
|
||||||
|
style: { text, size, color: colors.white, bgcolor, show_topbar: true },
|
||||||
|
steps: [{ down: id ? [{ actionId: id, options: { target: 'both' } }] : [], up: [] }],
|
||||||
|
feedbacks: [...feedback, offline],
|
||||||
|
})
|
||||||
|
const transport = {
|
||||||
|
transport_redundancy: {
|
||||||
|
type: 'simple',
|
||||||
|
name: 'Backup sync status',
|
||||||
|
style: { text: 'No\nbackup', size: '14', color: 0x99a4af, bgcolor: colors.dark, show_topbar: true },
|
||||||
|
steps: [{ down: [], up: [] }],
|
||||||
|
feedbacks: [{ feedbackId: 'redundancy', options: {} }],
|
||||||
|
},
|
||||||
|
transport_load_result: {
|
||||||
|
type: 'simple',
|
||||||
|
name: 'Last load result',
|
||||||
|
style: { text: 'NO LOAD\nYET', size: 'auto', color: colors.white, bgcolor: colors.dark, show_topbar: true },
|
||||||
|
steps: [{ down: [], up: [] }],
|
||||||
|
feedbacks: [{ feedbackId: 'load_result', options: {} }],
|
||||||
|
},
|
||||||
|
...Object.fromEntries(
|
||||||
|
['next', 'previous'].map((direction) => [
|
||||||
|
`transport_load_${direction}`,
|
||||||
|
{
|
||||||
|
type: 'layered',
|
||||||
|
name: `Load ${direction}`,
|
||||||
|
canvas: { decoration: 'topbar' },
|
||||||
|
elements: [
|
||||||
|
{ id: 'background', type: 'box', x: 0, y: 0, width: 100, height: 100, color: 0x243b50 },
|
||||||
|
{
|
||||||
|
id: 'icon',
|
||||||
|
type: 'text',
|
||||||
|
text: direction === 'next' ? '↦' : '↤',
|
||||||
|
x: 5,
|
||||||
|
y: -4,
|
||||||
|
width: 90,
|
||||||
|
height: 30,
|
||||||
|
fontsize: 100,
|
||||||
|
fontsizeAllowShrink: true,
|
||||||
|
color: colors.white,
|
||||||
|
halign: 'center',
|
||||||
|
valign: 'center',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'title',
|
||||||
|
type: 'text',
|
||||||
|
text: 'LOAD',
|
||||||
|
x: 3,
|
||||||
|
y: 27,
|
||||||
|
width: 94,
|
||||||
|
height: 33,
|
||||||
|
fontsize: 100,
|
||||||
|
fontsizeAllowShrink: true,
|
||||||
|
color: colors.white,
|
||||||
|
halign: 'center',
|
||||||
|
valign: 'center',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'direction',
|
||||||
|
type: 'text',
|
||||||
|
text: direction === 'next' ? 'NEXT' : 'PREV',
|
||||||
|
x: 3,
|
||||||
|
y: 62,
|
||||||
|
width: 94,
|
||||||
|
height: 35,
|
||||||
|
fontsize: 100,
|
||||||
|
fontsizeAllowShrink: true,
|
||||||
|
color: colors.white,
|
||||||
|
halign: 'center',
|
||||||
|
valign: 'center',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
steps: [{ down: [{ actionId: `load_${direction}`, options: { target: 'both' } }], up: [] }],
|
||||||
|
feedbacks: [
|
||||||
|
...['loading', 'ready', 'failed'].map((state) => ({
|
||||||
|
feedbackId: 'load_direction_state',
|
||||||
|
options: { direction, state },
|
||||||
|
styleOverrides: [
|
||||||
|
{
|
||||||
|
elementId: 'title',
|
||||||
|
elementProperty: 'text',
|
||||||
|
override: { loading: 'LOADING', ready: 'LOADED', failed: 'FAILED' }[state],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
elementId: 'background',
|
||||||
|
elementProperty: 'color',
|
||||||
|
override: { loading: colors.amber, ready: colors.blue, failed: colors.red }[state],
|
||||||
|
},
|
||||||
|
...['icon', 'title', 'direction'].map((elementId) => ({
|
||||||
|
elementId,
|
||||||
|
elementProperty: 'color',
|
||||||
|
override: state === 'loading' ? colors.dark : colors.white,
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
})),
|
||||||
|
{
|
||||||
|
feedbackId: 'offline',
|
||||||
|
options: {},
|
||||||
|
styleOverrides: [
|
||||||
|
{ elementId: 'title', elementProperty: 'text', override: 'OFFLINE' },
|
||||||
|
{ elementId: 'background', elementProperty: 'color', override: colors.dark },
|
||||||
|
...['icon', 'title', 'direction'].map((elementId) => ({
|
||||||
|
elementId,
|
||||||
|
elementProperty: 'color',
|
||||||
|
override: 0x889099,
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
transport_play: button(
|
||||||
|
'Play — green while playing',
|
||||||
|
'▶\nPLAY',
|
||||||
|
'887',
|
||||||
|
[active('playing', colors.green), active('paused', colors.amber, 'Ⅱ\nPAUSED')],
|
||||||
|
'18',
|
||||||
|
0x243b50,
|
||||||
|
),
|
||||||
|
transport_stop: button(
|
||||||
|
'Stop — red while stopped',
|
||||||
|
'■\nSTOP',
|
||||||
|
'890',
|
||||||
|
[active('stopped', colors.red)],
|
||||||
|
'18',
|
||||||
|
0x502d34,
|
||||||
|
),
|
||||||
|
// Verified against MPC-HC 2.8.5's /commands.json: 918 is an after-playback setting.
|
||||||
|
transport_previous: button('Previous playlist item', '◀◀\nPREV', '919', [], '18', 0x243b50),
|
||||||
|
transport_next: button('Next playlist item', '▶▶\nNEXT', '920', [], '18', 0x243b50),
|
||||||
|
transport_mute: button(
|
||||||
|
'Toggle mute — red while muted',
|
||||||
|
'MUTE',
|
||||||
|
'909',
|
||||||
|
[active('muted', colors.red, 'MUTED')],
|
||||||
|
'18',
|
||||||
|
),
|
||||||
|
transport_pause: button('Pause — amber while paused', 'Ⅱ\nPAUSE', '888', [active('paused', colors.amber)], '18'),
|
||||||
|
transport_remaining: button(
|
||||||
|
'Remaining time and progress',
|
||||||
|
`LEFT\n$(${label}:remaining)`,
|
||||||
|
null,
|
||||||
|
[{ feedbackId: 'progress_bar', options: {} }],
|
||||||
|
'18',
|
||||||
|
),
|
||||||
|
transport_elapsed: button(
|
||||||
|
'Elapsed time and progress',
|
||||||
|
`ELAPSED\n$(${label}:elapsed)`,
|
||||||
|
null,
|
||||||
|
[{ feedbackId: 'progress_bar', options: {} }],
|
||||||
|
12,
|
||||||
|
),
|
||||||
|
transport_state: button(
|
||||||
|
'Playback state',
|
||||||
|
`$(${label}:state_label)`,
|
||||||
|
null,
|
||||||
|
[active('playing', colors.green), active('paused', colors.amber), active('stopped', colors.red)],
|
||||||
|
'14',
|
||||||
|
),
|
||||||
|
}
|
||||||
|
const playlist = Object.fromEntries(
|
||||||
|
Array.from({ length: 10 }, (_, index) => {
|
||||||
|
const item = index + 1
|
||||||
|
return [
|
||||||
|
`transport_load_item_${item}`,
|
||||||
|
{
|
||||||
|
type: 'layered',
|
||||||
|
name: `Load playlist item ${item}`,
|
||||||
|
canvas: { decoration: 'topbar' },
|
||||||
|
elements: [
|
||||||
|
{ id: 'background', type: 'box', x: 0, y: 0, width: 100, height: 100, color: 0x243b50 },
|
||||||
|
{
|
||||||
|
id: 'title',
|
||||||
|
type: 'text',
|
||||||
|
text: '↓ LOAD',
|
||||||
|
x: 5,
|
||||||
|
y: 3,
|
||||||
|
width: 90,
|
||||||
|
height: 26,
|
||||||
|
fontsize: 90,
|
||||||
|
fontsizeAllowShrink: true,
|
||||||
|
color: colors.white,
|
||||||
|
halign: 'center',
|
||||||
|
valign: 'center',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'number',
|
||||||
|
type: 'text',
|
||||||
|
text: String(item),
|
||||||
|
x: 5,
|
||||||
|
y: 24,
|
||||||
|
width: 90,
|
||||||
|
height: 74,
|
||||||
|
fontsize: 100,
|
||||||
|
fontsizeAllowShrink: true,
|
||||||
|
color: colors.white,
|
||||||
|
halign: 'center',
|
||||||
|
valign: 'center',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
steps: [{ down: [{ actionId: 'load_playlist_item', options: { item, target: 'both' } }], up: [] }],
|
||||||
|
feedbacks: [
|
||||||
|
...['loading', 'ready', 'failed'].map((state) => ({
|
||||||
|
feedbackId: 'load_playlist_item_state',
|
||||||
|
options: { item, state },
|
||||||
|
styleOverrides: [
|
||||||
|
{
|
||||||
|
elementId: 'title',
|
||||||
|
elementProperty: 'text',
|
||||||
|
override: { loading: 'LOADING', ready: 'LOADED', failed: 'FAILED' }[state],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
elementId: 'background',
|
||||||
|
elementProperty: 'color',
|
||||||
|
override: { loading: colors.amber, ready: colors.blue, failed: colors.red }[state],
|
||||||
|
},
|
||||||
|
...['title', 'number'].map((elementId) => ({
|
||||||
|
elementId,
|
||||||
|
elementProperty: 'color',
|
||||||
|
override: state === 'loading' ? colors.dark : colors.white,
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
})),
|
||||||
|
{
|
||||||
|
feedbackId: 'offline',
|
||||||
|
options: {},
|
||||||
|
styleOverrides: [
|
||||||
|
{ elementId: 'title', elementProperty: 'text', override: 'OFFLINE' },
|
||||||
|
{ elementId: 'background', elementProperty: 'color', override: colors.dark },
|
||||||
|
...['title', 'number'].map((elementId) => ({
|
||||||
|
elementId,
|
||||||
|
elementProperty: 'color',
|
||||||
|
override: 0x889099,
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const playPlaylist = Object.fromEntries(
|
||||||
|
Array.from({ length: 10 }, (_, index) => {
|
||||||
|
const item = index + 1
|
||||||
|
return [
|
||||||
|
`playlist_play_item_${item}`,
|
||||||
|
{
|
||||||
|
type: 'simple',
|
||||||
|
name: `Play item ${item}`,
|
||||||
|
style: { text: `▶\nPLAY\n${item}`, size: 12, color: colors.white, bgcolor: 0x243b50, show_topbar: true },
|
||||||
|
steps: [{ down: [{ actionId: 'play_playlist_item', options: { item, target: 'both' } }], up: [] }],
|
||||||
|
feedbacks: [offline],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const timers = Object.fromEntries(
|
||||||
|
['remaining', 'elapsed'].flatMap((mode) =>
|
||||||
|
['hh', 'mm', 'ss'].map((part, index) => [
|
||||||
|
`timer_${mode}_${part}`,
|
||||||
|
{
|
||||||
|
type: 'simple',
|
||||||
|
name: `${mode === 'remaining' ? 'Remaining' : 'Elapsed'} ${part.toUpperCase()} (${index + 1}/3)`,
|
||||||
|
style: {
|
||||||
|
text: `$(${label}:${mode}_${part})`,
|
||||||
|
size: 'auto',
|
||||||
|
color: colors.white,
|
||||||
|
bgcolor: colors.dark,
|
||||||
|
show_topbar: true,
|
||||||
|
alignment: 'center:center',
|
||||||
|
},
|
||||||
|
steps: [{ down: [], up: [] }],
|
||||||
|
feedbacks: [{ feedbackId: 'split_timer_color', options: { mode } }],
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return { ...transport, ...playlist, ...playPlaylist, ...timers, ...catalog }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function presetSections(buttons) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: 'transport',
|
||||||
|
name: 'Transport & timing',
|
||||||
|
definitions: Object.keys(buttons).filter(
|
||||||
|
(id) => id.startsWith('transport_') && !id.startsWith('transport_load_'),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'experimental',
|
||||||
|
name: 'Experimental',
|
||||||
|
definitions: [
|
||||||
|
'transport_load_previous',
|
||||||
|
'transport_load_next',
|
||||||
|
'transport_load_result',
|
||||||
|
...Object.keys(buttons).filter((id) => id.startsWith('transport_load_item_')),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'playlist',
|
||||||
|
name: 'Playlist',
|
||||||
|
definitions: Object.keys(buttons).filter((id) => id.startsWith('playlist_play_item_')),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'timers',
|
||||||
|
name: 'Timers — large HH / MM / SS',
|
||||||
|
definitions: Object.keys(buttons).filter((id) => id.startsWith('timer_')),
|
||||||
|
},
|
||||||
|
{ id: 'commands', name: 'All commands', definitions: Object.keys(commands) },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,296 @@
|
||||||
|
export const colors = {
|
||||||
|
dark: 0x17212b,
|
||||||
|
green: 0x159447,
|
||||||
|
red: 0xba2936,
|
||||||
|
amber: 0xe09b20,
|
||||||
|
blue: 0x286ba8,
|
||||||
|
white: 0xffffff,
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shortFilename(file) {
|
||||||
|
const name = String(file ?? '')
|
||||||
|
.split(/[\\/]/)
|
||||||
|
.at(-1)
|
||||||
|
.replace(/\.[^.]+$/, '')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim()
|
||||||
|
const characters = [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(name)].map(
|
||||||
|
(part) => part.segment,
|
||||||
|
)
|
||||||
|
const visible = characters.length > 16 ? [...characters.slice(0, 15), '…'] : characters
|
||||||
|
return visible.length > 8 ? `${visible.slice(0, 8).join('')}\n${visible.slice(8).join('')}` : visible.join('')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function progressBar(state, image) {
|
||||||
|
if (!image) return {}
|
||||||
|
const width = Math.max(1, Math.min(2048, Math.floor(image.width)))
|
||||||
|
const height = Math.max(1, Math.min(2048, Math.floor(image.height)))
|
||||||
|
if (!Number.isFinite(width) || !Number.isFinite(height)) return {}
|
||||||
|
const pixels = Buffer.alloc(width * height * 4)
|
||||||
|
if (state?.progress != null) {
|
||||||
|
const filled = Math.round((width * state.progress) / 100)
|
||||||
|
const color = state.remaining <= 10000 ? colors.red : state.remaining <= 30000 ? colors.amber : colors.green
|
||||||
|
const barHeight = Math.min(height, Math.max(2, Math.round(height / 9)))
|
||||||
|
for (let y = height - barHeight; y < height; y++) {
|
||||||
|
for (let x = 0; x < width; x++) {
|
||||||
|
const offset = (y * width + x) * 4
|
||||||
|
const shade = x < filled ? color : 0x46505a
|
||||||
|
pixels[offset] = (shade >> 16) & 255
|
||||||
|
pixels[offset + 1] = (shade >> 8) & 255
|
||||||
|
pixels[offset + 2] = shade & 255
|
||||||
|
pixels[offset + 3] = 255
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
imageBuffer: pixels.toString('base64'),
|
||||||
|
imageBufferEncoding: { pixelFormat: 'RGBA' },
|
||||||
|
imageBufferPosition: { x: 0, y: 0, width, height },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transparent center preserves Companion's own text rendering and dark background.
|
||||||
|
export function transportBorder(state, image, control) {
|
||||||
|
if (!image) return {}
|
||||||
|
const width = Math.max(1, Math.min(2048, Math.floor(image.width)))
|
||||||
|
const height = Math.max(1, Math.min(2048, Math.floor(image.height)))
|
||||||
|
if (!Number.isFinite(width) || !Number.isFinite(height)) return {}
|
||||||
|
const palette = { play: colors.green, stop: colors.red, pause: colors.amber, navigation: colors.blue, mute: 0x8965ad }
|
||||||
|
const active =
|
||||||
|
state &&
|
||||||
|
((control === 'play' && ['playing', 'paused'].includes(state.state)) ||
|
||||||
|
(control === 'stop' && state.state === 'stopped') ||
|
||||||
|
(control === 'pause' && state.state === 'paused') ||
|
||||||
|
(control === 'mute' && state.muted) ||
|
||||||
|
(control === 'state' && ['playing', 'paused', 'stopped'].includes(state.state)))
|
||||||
|
let color = palette[control] ?? 0x59636d
|
||||||
|
if (control === 'play' && state?.state === 'paused') color = colors.amber
|
||||||
|
if (control === 'mute' && state?.muted) color = colors.red
|
||||||
|
if (control === 'state')
|
||||||
|
color = { playing: colors.green, paused: colors.amber, stopped: colors.red }[state?.state] ?? 0x59636d
|
||||||
|
if (!state) color = 0x59636d
|
||||||
|
const thickness = Math.max(1, Math.round((Math.min(width, height) * (active ? 3 : 1)) / 72))
|
||||||
|
const pixels = Buffer.alloc(width * height * 4)
|
||||||
|
for (let y = 0; y < height; y++) {
|
||||||
|
for (let x = 0; x < width; x++) {
|
||||||
|
if (x >= thickness && x < width - thickness && y >= thickness && y < height - thickness) continue
|
||||||
|
const offset = (y * width + x) * 4
|
||||||
|
pixels[offset] = (color >> 16) & 255
|
||||||
|
pixels[offset + 1] = (color >> 8) & 255
|
||||||
|
pixels[offset + 2] = color & 255
|
||||||
|
pixels[offset + 3] = 255
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
imageBuffer: pixels.toString('base64'),
|
||||||
|
imageBufferEncoding: { pixelFormat: 'RGBA' },
|
||||||
|
imageBufferPosition: { x: 0, y: 0, width, height },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function feedbacks(getState, getSync = () => null, getLoadStatus = () => 'idle', getLoadResult = () => null) {
|
||||||
|
const boolean = (name, callback, color) => ({
|
||||||
|
type: 'boolean',
|
||||||
|
name,
|
||||||
|
options: [],
|
||||||
|
defaultStyle: { color: colors.white, bgcolor: color },
|
||||||
|
callback,
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
...Object.fromEntries(
|
||||||
|
['next', 'previous'].map((direction) => [
|
||||||
|
`load_${direction}_status`,
|
||||||
|
{
|
||||||
|
type: 'advanced',
|
||||||
|
name: `Load ${direction} status`,
|
||||||
|
options: [],
|
||||||
|
affectedProperties: ['text', 'bgcolor', 'color'],
|
||||||
|
callback: () => {
|
||||||
|
const status = getLoadStatus(direction)
|
||||||
|
const label = direction === 'next' ? 'NEXT' : 'PREV'
|
||||||
|
const icon = direction === 'next' ? '↦' : '↤'
|
||||||
|
return {
|
||||||
|
text:
|
||||||
|
`${icon}\n` +
|
||||||
|
({ loading: `LOADING\n${label}`, ready: `LOADED\n${label}`, failed: `FAILED\n${label}` }[status] ??
|
||||||
|
`LOAD\n${label}`),
|
||||||
|
bgcolor: { loading: colors.amber, ready: colors.blue, failed: colors.red }[status] ?? 0x243b50,
|
||||||
|
color: status === 'loading' ? colors.dark : colors.white,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
load_direction_state: {
|
||||||
|
type: 'boolean',
|
||||||
|
name: 'Load next / previous state',
|
||||||
|
options: [
|
||||||
|
{
|
||||||
|
type: 'dropdown',
|
||||||
|
id: 'direction',
|
||||||
|
label: 'Direction',
|
||||||
|
default: 'next',
|
||||||
|
choices: ['next', 'previous'].map((id) => ({ id, label: id })),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'dropdown',
|
||||||
|
id: 'state',
|
||||||
|
label: 'State',
|
||||||
|
default: 'loading',
|
||||||
|
choices: ['loading', 'ready', 'failed'].map((id) => ({ id, label: id })),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
defaultStyle: { bgcolor: colors.blue },
|
||||||
|
callback: (feedback) => getLoadStatus(feedback.options.direction) === feedback.options.state,
|
||||||
|
},
|
||||||
|
load_playlist_item_state: {
|
||||||
|
type: 'boolean',
|
||||||
|
name: 'Load playlist item state',
|
||||||
|
options: [
|
||||||
|
{ type: 'number', id: 'item', label: 'Playlist item number', default: 1, min: 1, max: 10000, step: 1 },
|
||||||
|
{
|
||||||
|
type: 'dropdown',
|
||||||
|
id: 'state',
|
||||||
|
label: 'State',
|
||||||
|
default: 'loading',
|
||||||
|
choices: ['loading', 'ready', 'failed'].map((id) => ({ id, label: id })),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
defaultStyle: { bgcolor: colors.blue },
|
||||||
|
callback: (feedback) => getLoadStatus(`item_${feedback.options.item}`) === feedback.options.state,
|
||||||
|
},
|
||||||
|
load_playlist_item_status: {
|
||||||
|
type: 'advanced',
|
||||||
|
name: 'Load playlist item status',
|
||||||
|
options: [{ type: 'number', id: 'item', label: 'Playlist item number', default: 1, min: 1, max: 10000, step: 1 }],
|
||||||
|
affectedProperties: ['text', 'bgcolor', 'color'],
|
||||||
|
callback: (feedback) => {
|
||||||
|
const item = feedback.options.item
|
||||||
|
const status = getLoadStatus(`item_${item}`)
|
||||||
|
return {
|
||||||
|
text: `↓\n${{ loading: 'LOADING', ready: 'LOADED', failed: 'FAILED' }[status] ?? 'LOAD'}\n${item}`,
|
||||||
|
bgcolor: { loading: colors.amber, ready: colors.blue, failed: colors.red }[status] ?? 0x243b50,
|
||||||
|
color: status === 'loading' ? colors.dark : colors.white,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
load_result: {
|
||||||
|
type: 'advanced',
|
||||||
|
name: 'Last load result (retained)',
|
||||||
|
options: [],
|
||||||
|
affectedProperties: ['text', 'bgcolor', 'color'],
|
||||||
|
callback: () => {
|
||||||
|
const result = getLoadResult()
|
||||||
|
const direction = result?.direction?.startsWith('item_')
|
||||||
|
? `#${result.direction.slice(5)}`
|
||||||
|
: result?.direction === 'previous'
|
||||||
|
? 'PREV'
|
||||||
|
: 'NEXT'
|
||||||
|
return {
|
||||||
|
text:
|
||||||
|
{
|
||||||
|
loading: `LOADING\n${direction}`,
|
||||||
|
ready: `LOADED\n${shortFilename(result.file) || direction}`,
|
||||||
|
failed: `LAST\nFAILED\n${direction}`,
|
||||||
|
}[result?.status] ?? 'NO LOAD\nYET',
|
||||||
|
bgcolor: { loading: colors.amber, ready: colors.blue, failed: colors.red }[result?.status] ?? colors.dark,
|
||||||
|
color: result?.status === 'loading' ? colors.dark : colors.white,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
in_sync: boolean('Backup in sync with main', () => getSync()?.status === 'in_sync', colors.green),
|
||||||
|
out_of_sync: boolean('Backup out of sync with main', () => getSync()?.status === 'out_of_sync', colors.red),
|
||||||
|
redundancy: {
|
||||||
|
type: 'advanced',
|
||||||
|
name: 'Backup sync status',
|
||||||
|
options: [],
|
||||||
|
affectedProperties: ['text', 'color', 'bgcolor'],
|
||||||
|
callback: () => redundancyStyle(getSync()),
|
||||||
|
},
|
||||||
|
playing: boolean('Playing', () => getState()?.state === 'playing', colors.green),
|
||||||
|
stopped: boolean('Stopped', () => getState()?.state === 'stopped', colors.red),
|
||||||
|
paused: boolean('Paused', () => getState()?.state === 'paused', colors.amber),
|
||||||
|
idle: boolean('No active media (idle)', () => getState()?.state === 'idle', colors.dark),
|
||||||
|
muted: boolean('Audio muted', () => getState()?.muted === true, colors.red),
|
||||||
|
offline: boolean('Status unavailable', () => !getState(), colors.dark),
|
||||||
|
transport_border: {
|
||||||
|
type: 'advanced',
|
||||||
|
name: 'Transport outline — thicker when active',
|
||||||
|
options: [
|
||||||
|
{
|
||||||
|
type: 'dropdown',
|
||||||
|
id: 'control',
|
||||||
|
label: 'Control',
|
||||||
|
default: 'play',
|
||||||
|
choices: ['play', 'stop', 'pause', 'navigation', 'mute', 'state'].map((id) => ({ id, label: id })),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
affectedProperties: ['imageBuffer'],
|
||||||
|
callback: (feedback) => transportBorder(getState(), feedback.image, feedback.options.control),
|
||||||
|
},
|
||||||
|
split_timer_color: {
|
||||||
|
type: 'advanced',
|
||||||
|
name: 'Split timer digit color',
|
||||||
|
options: [
|
||||||
|
{
|
||||||
|
type: 'dropdown',
|
||||||
|
id: 'mode',
|
||||||
|
label: 'Timer',
|
||||||
|
default: 'remaining',
|
||||||
|
choices: [
|
||||||
|
{ id: 'remaining', label: 'Remaining' },
|
||||||
|
{ id: 'elapsed', label: 'Elapsed' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
affectedProperties: ['color'],
|
||||||
|
callback: (feedback) => {
|
||||||
|
const state = getState()
|
||||||
|
if (!state || state.state === 'idle' || (feedback.options.mode === 'remaining' && state.remaining == null))
|
||||||
|
return { color: 0x889099 }
|
||||||
|
return {
|
||||||
|
color:
|
||||||
|
feedback.options.mode === 'remaining' && state.remaining <= 10000
|
||||||
|
? colors.red
|
||||||
|
: feedback.options.mode === 'remaining' && state.remaining <= 30000
|
||||||
|
? colors.amber
|
||||||
|
: colors.white,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
progress_bar: {
|
||||||
|
type: 'advanced',
|
||||||
|
name: 'Playback progress bar',
|
||||||
|
options: [],
|
||||||
|
affectedProperties: ['imageBuffer'],
|
||||||
|
callback: (feedback) => progressBar(getState(), feedback.image),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function redundancyStyle(sync) {
|
||||||
|
const status = sync?.status ?? 'no_backup'
|
||||||
|
const text =
|
||||||
|
{
|
||||||
|
no_backup: 'No\nbackup',
|
||||||
|
backup_config: 'Backup\nconfig',
|
||||||
|
backup_offline: 'Backup\noffline',
|
||||||
|
backup_empty: 'Backup\nempty',
|
||||||
|
main_offline: 'Main\noffline',
|
||||||
|
main_empty: 'Main\nempty',
|
||||||
|
checking: 'Checking\nsync',
|
||||||
|
in_sync: 'In sync',
|
||||||
|
out_of_sync: 'Out of\nsync',
|
||||||
|
}[status] ?? 'Checking\nsync'
|
||||||
|
const bgcolor =
|
||||||
|
status === 'in_sync'
|
||||||
|
? colors.green
|
||||||
|
: status === 'out_of_sync'
|
||||||
|
? colors.red
|
||||||
|
: status === 'no_backup'
|
||||||
|
? colors.dark
|
||||||
|
: status.startsWith('main_')
|
||||||
|
? colors.amber
|
||||||
|
: colors.blue
|
||||||
|
return { text, bgcolor, color: status === 'no_backup' ? 0x99a4af : colors.white }
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,117 @@
|
||||||
|
import { setTimeout as delay } from 'node:timers/promises'
|
||||||
|
|
||||||
|
// Experimental web-API workaround: Navigation still autoplays. Never retry navigation or
|
||||||
|
// mute toggles: an HTTP response is not an acknowledgement of player state.
|
||||||
|
export async function loadItem(player, direction, timing = {}) {
|
||||||
|
const itemMatch = /^item_([1-9]\d*)$/.exec(direction)
|
||||||
|
const itemNumber = itemMatch ? Number(itemMatch[1]) : null
|
||||||
|
if (itemNumber !== null && (!Number.isSafeInteger(itemNumber) || itemNumber > 10000))
|
||||||
|
throw new Error('Invalid playlist item number')
|
||||||
|
if (!['next', 'previous'].includes(direction) && itemNumber === null) throw new Error('Invalid load direction')
|
||||||
|
const navigationId = direction === 'next' ? '920' : '919'
|
||||||
|
const poll = timing.poll ?? 50
|
||||||
|
const settle = timing.settle ?? 500
|
||||||
|
const timeout = timing.timeout ?? 5000
|
||||||
|
const signal = player.client.abort.signal
|
||||||
|
const wait = () => delay(poll, undefined, { signal })
|
||||||
|
const fresh = async () => {
|
||||||
|
await player.pending
|
||||||
|
signal.throwIfAborted()
|
||||||
|
await player.refresh()
|
||||||
|
signal.throwIfAborted()
|
||||||
|
if (!player.state) throw new Error('Player status unavailable; check mute and playback state')
|
||||||
|
return player.state
|
||||||
|
}
|
||||||
|
const command = async (id) => {
|
||||||
|
signal.throwIfAborted()
|
||||||
|
await player.client.command(id)
|
||||||
|
}
|
||||||
|
const filename = (state) => state.file.replaceAll('\\', '/').toLowerCase()
|
||||||
|
let advanced = false
|
||||||
|
try {
|
||||||
|
const original = await fresh()
|
||||||
|
if (itemNumber === null && (!original.file || original.state === 'idle'))
|
||||||
|
throw new Error(`Load a playlist item before using Load ${direction}`)
|
||||||
|
let playlistSignature
|
||||||
|
let alreadySelected = false
|
||||||
|
const verifyPlaylist = async () => {
|
||||||
|
const list = await player.client.playlist()
|
||||||
|
if (JSON.stringify(list.items) !== playlistSignature)
|
||||||
|
throw new Error('Playlist changed during loading; audio was not restored')
|
||||||
|
return list.active === itemNumber - 1
|
||||||
|
}
|
||||||
|
if (itemNumber !== null) {
|
||||||
|
const list = await player.client.playlist()
|
||||||
|
if (itemNumber > list.items.length)
|
||||||
|
throw new Error(`Playlist item ${itemNumber} does not exist (${list.items.length} items)`)
|
||||||
|
playlistSignature = JSON.stringify(list.items)
|
||||||
|
alreadySelected = list.active === itemNumber - 1 && original.state !== 'idle' && !!original.file
|
||||||
|
}
|
||||||
|
const wasMuted = original.muted
|
||||||
|
if (!wasMuted) await command('909')
|
||||||
|
let deadline = performance.now() + timeout
|
||||||
|
while (!(await fresh()).muted) {
|
||||||
|
if (performance.now() >= deadline) throw new Error(`Mute was not confirmed; ${direction} was not sent`)
|
||||||
|
await wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (itemNumber !== null) await verifyPlaylist()
|
||||||
|
advanced = true
|
||||||
|
if (itemNumber === null) await command(navigationId)
|
||||||
|
else if (!alreadySelected) await player.client.selectPlaylistItem(itemNumber - 1)
|
||||||
|
// No status request or artificial delay between navigation and the first Stop.
|
||||||
|
await command('890')
|
||||||
|
deadline = performance.now() + timeout
|
||||||
|
let candidate = ''
|
||||||
|
let stableSince = 0
|
||||||
|
while (performance.now() < deadline) {
|
||||||
|
await wait()
|
||||||
|
const state = await fresh()
|
||||||
|
if (!state.muted) throw new Error('Mute changed during loading; audio was not restored')
|
||||||
|
const file = filename(state)
|
||||||
|
const selected = itemNumber === null || (await verifyPlaylist())
|
||||||
|
if (selected && file && (alreadySelected || file !== filename(original)) && state.state === 'stopped') {
|
||||||
|
if (candidate !== file) {
|
||||||
|
candidate = file
|
||||||
|
stableSince = performance.now()
|
||||||
|
}
|
||||||
|
if (performance.now() - stableSince >= settle) {
|
||||||
|
if (!wasMuted) {
|
||||||
|
await command('909')
|
||||||
|
const restoreDeadline = performance.now() + timeout
|
||||||
|
while (true) {
|
||||||
|
const restored = await fresh()
|
||||||
|
if (
|
||||||
|
filename(restored) !== candidate ||
|
||||||
|
restored.state !== 'stopped' ||
|
||||||
|
(itemNumber !== null && !(await verifyPlaylist()))
|
||||||
|
) {
|
||||||
|
throw new Error('Player changed while restoring audio; check the player')
|
||||||
|
}
|
||||||
|
if (!restored.muted) return restored.file
|
||||||
|
if (performance.now() >= restoreDeadline) throw new Error('Audio restoration was not confirmed')
|
||||||
|
await wait()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return state.file
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
candidate = ''
|
||||||
|
if (state.state !== 'stopped') await command('890')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error('The requested file stopped for 500 ms was not confirmed; audio was not restored')
|
||||||
|
} catch (error) {
|
||||||
|
// A lost navigation response may still mean it executed. Best-effort Stop is
|
||||||
|
// idempotent; blind mute toggles or another navigation command would not be.
|
||||||
|
if (advanced && !signal.aborted) {
|
||||||
|
try {
|
||||||
|
await command('890')
|
||||||
|
await fresh()
|
||||||
|
} catch {
|
||||||
|
/* Keep the original failure. */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,283 @@
|
||||||
|
import { InstanceBase, InstanceStatus } from '@companion-module/base'
|
||||||
|
import { endpoint } from './client.js'
|
||||||
|
import { Player } from './player.js'
|
||||||
|
import { comparePlayers, redundancyDefinitions, redundancyVariables } from './redundancy.js'
|
||||||
|
import { actions, presets, presetSections } from './definitions.js'
|
||||||
|
import { feedbacks } from './feedbacks.js'
|
||||||
|
import { variableDefinitions, variables } from './state.js'
|
||||||
|
|
||||||
|
export const UpgradeScripts = []
|
||||||
|
|
||||||
|
export default class MpcInstance extends InstanceBase {
|
||||||
|
async init(config) {
|
||||||
|
this.setActionDefinitions(
|
||||||
|
actions(
|
||||||
|
(id, target) => this.send(id, target),
|
||||||
|
(target) => this.loadItem('next', target),
|
||||||
|
(target) => this.loadItem('previous', target),
|
||||||
|
(item, target) => this.loadItem(`item_${item}`, target),
|
||||||
|
(item, target) => this.playPlaylistItem(item, target),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
this.setFeedbackDefinitions(
|
||||||
|
feedbacks(
|
||||||
|
() => this.state,
|
||||||
|
() => this.sync,
|
||||||
|
(direction = 'next') => (this.main?.loadDirection === direction ? this.main.loadDisplayStatus : 'idle'),
|
||||||
|
() => this.main?.loadResult,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
this.setVariableDefinitions({
|
||||||
|
...variableDefinitions,
|
||||||
|
...redundancyDefinitions,
|
||||||
|
...Object.fromEntries(
|
||||||
|
['', 'backup_'].flatMap((prefix) =>
|
||||||
|
['status', 'direction', 'file', 'detail'].map((field) => [
|
||||||
|
`${prefix}load_result_${field}`,
|
||||||
|
{ name: `${prefix ? 'Backup' : 'Main'} last load result: ${field} (retained until next attempt)` },
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
load_previous_status: { name: 'Main experimental Load previous: idle, loading, ready, failed' },
|
||||||
|
load_previous_detail: { name: 'Main experimental Load previous result' },
|
||||||
|
backup_load_previous_status: { name: 'Backup experimental Load previous status' },
|
||||||
|
backup_load_previous_detail: { name: 'Backup experimental Load previous result' },
|
||||||
|
load_next_status: { name: 'Main experimental Load next: idle, loading, ready, failed' },
|
||||||
|
load_next_detail: { name: 'Main experimental Load next result' },
|
||||||
|
backup_load_next_status: { name: 'Backup experimental Load next status (or not_configured)' },
|
||||||
|
backup_load_next_detail: { name: 'Backup experimental Load next result' },
|
||||||
|
})
|
||||||
|
await this.configUpdated(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
publish() {
|
||||||
|
this.state = this.main?.state ?? null
|
||||||
|
this.sync = comparePlayers(this.main, this.backup, this.syncOptions)
|
||||||
|
this.setVariableValues({
|
||||||
|
...variables(this.state),
|
||||||
|
...Object.fromEntries(
|
||||||
|
[
|
||||||
|
[this.main, ''],
|
||||||
|
[this.backup, 'backup_'],
|
||||||
|
].flatMap(([player, prefix]) =>
|
||||||
|
['status', 'direction', 'file', 'detail'].map((field) => [
|
||||||
|
`${prefix}load_result_${field}`,
|
||||||
|
player?.loadResult?.[field] ?? (field === 'status' ? 'idle' : ''),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
...Object.fromEntries(
|
||||||
|
['next', 'previous'].flatMap((direction) => {
|
||||||
|
const values = (player, prefix, absent) => [
|
||||||
|
[
|
||||||
|
`${prefix}load_${direction}_status`,
|
||||||
|
player ? (player.loadDirection === direction ? player.loadStatus : 'idle') : absent,
|
||||||
|
],
|
||||||
|
[`${prefix}load_${direction}_detail`, player?.loadDirection === direction ? player.loadDetail : ''],
|
||||||
|
]
|
||||||
|
return [
|
||||||
|
...values(this.main, '', 'idle'),
|
||||||
|
...values(this.backup, 'backup_', this.syncOptions?.configured ? 'unavailable' : 'not_configured'),
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
...redundancyVariables(this.backup, this.syncOptions, this.sync),
|
||||||
|
})
|
||||||
|
this.checkAllFeedbacks()
|
||||||
|
}
|
||||||
|
|
||||||
|
async configUpdated(config) {
|
||||||
|
this.main?.close()
|
||||||
|
this.backup?.close()
|
||||||
|
this.main = undefined
|
||||||
|
this.backup = undefined
|
||||||
|
this.lastError = undefined
|
||||||
|
this.syncOptions = {
|
||||||
|
configured: !!String(config.backup_host ?? '').trim(),
|
||||||
|
interval: Number(config.poll_interval ?? 500),
|
||||||
|
tolerance: Number(config.sync_tolerance ?? 1000),
|
||||||
|
compareAudio: config.compare_audio === true,
|
||||||
|
}
|
||||||
|
this.publish()
|
||||||
|
try {
|
||||||
|
if (
|
||||||
|
!Number.isInteger(this.syncOptions.interval) ||
|
||||||
|
this.syncOptions.interval < 250 ||
|
||||||
|
this.syncOptions.interval > 5000
|
||||||
|
) {
|
||||||
|
throw new Error('Status polling must be between 250 and 5000 milliseconds.')
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!Number.isInteger(this.syncOptions.tolerance) ||
|
||||||
|
this.syncOptions.tolerance < 100 ||
|
||||||
|
this.syncOptions.tolerance > 10000
|
||||||
|
) {
|
||||||
|
throw new Error('Sync tolerance must be between 100 and 10000 milliseconds.')
|
||||||
|
}
|
||||||
|
this.main = new Player(config, this.syncOptions.interval, (player) => {
|
||||||
|
if (player !== this.main) return
|
||||||
|
this.publish()
|
||||||
|
if (player.error) {
|
||||||
|
this.updateStatus(InstanceStatus.ConnectionFailure, player.error)
|
||||||
|
if (player.error !== this.lastError)
|
||||||
|
this.log('error', `Main MPC-HC: ${player.error}. Check the Web Interface setting, host, and port.`)
|
||||||
|
} else this.updateStatus(InstanceStatus.Ok)
|
||||||
|
this.lastError = player.error
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
this.updateStatus(InstanceStatus.BadConfig, error.message)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (this.syncOptions.configured) {
|
||||||
|
try {
|
||||||
|
const backupConfig = { host: config.backup_host, port: config.backup_port ?? 13579 }
|
||||||
|
if (endpoint(config).origin === endpoint(backupConfig).origin)
|
||||||
|
throw new Error('Backup must be a different player address; duplicate commands are disabled.')
|
||||||
|
this.backup = new Player(backupConfig, this.syncOptions.interval, (player) => {
|
||||||
|
if (player === this.backup) this.publish()
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
// The optional backup never changes the main connection's health.
|
||||||
|
this.syncOptions.configError = error.message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.publish()
|
||||||
|
const buttons = presets(this.label)
|
||||||
|
this.setPresetDefinitions(presetSections(buttons), buttons)
|
||||||
|
this.updateStatus(InstanceStatus.Connecting)
|
||||||
|
void this.main.refresh()
|
||||||
|
void this.backup?.refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
async refresh() {
|
||||||
|
await Promise.allSettled([this.main?.refresh(), this.backup?.refresh()])
|
||||||
|
}
|
||||||
|
|
||||||
|
async loadItem(direction, target = 'both') {
|
||||||
|
if (this.loadingItem) return this.loadingItem
|
||||||
|
if (!['both', 'main', 'backup'].includes(target)) return
|
||||||
|
const players = (
|
||||||
|
target === 'main' ? [this.main] : target === 'backup' ? [this.backup] : [this.main, this.backup]
|
||||||
|
).filter(Boolean)
|
||||||
|
this.loadingItem = Promise.allSettled(
|
||||||
|
players.map(async (player) => {
|
||||||
|
await player.loadItem(direction)
|
||||||
|
if (player.active && player.loadStatus === 'failed')
|
||||||
|
this.log('warn', `Load ${direction} (${player === this.main ? 'main' : 'backup'}): ${player.loadDetail}`)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
try {
|
||||||
|
await this.loadingItem
|
||||||
|
} finally {
|
||||||
|
this.loadingItem = undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async playPlaylistItem(item, target = 'both') {
|
||||||
|
if (this.loadingItem) {
|
||||||
|
this.log('warn', 'Command ignored while experimental loading is running')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!['both', 'main', 'backup'].includes(target)) return
|
||||||
|
const players = target === 'main' ? [this.main] : target === 'backup' ? [this.backup] : [this.main, this.backup]
|
||||||
|
await Promise.allSettled(players.filter(Boolean).map((player) => player.playPlaylistItem(item)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async send(id, target = 'both') {
|
||||||
|
if (this.loadingItem) {
|
||||||
|
this.log('warn', 'Command ignored while experimental loading is running')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!['both', 'main', 'backup'].includes(target)) {
|
||||||
|
this.log('warn', `Unknown player target: ${target}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const players = target === 'main' ? [this.main] : target === 'backup' ? [this.backup] : [this.main, this.backup]
|
||||||
|
await Promise.allSettled(
|
||||||
|
players.filter(Boolean).map(async (player) => {
|
||||||
|
if ((await player.send(id)) === false) this.log('warn', 'Command ignored while experimental loading is running')
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async destroy() {
|
||||||
|
this.main?.close()
|
||||||
|
this.backup?.close()
|
||||||
|
this.main = undefined
|
||||||
|
this.backup = undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
getConfigFields() {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
type: 'number',
|
||||||
|
id: 'poll_interval',
|
||||||
|
label: 'Status polling interval (milliseconds)',
|
||||||
|
width: 12,
|
||||||
|
default: 500,
|
||||||
|
min: 250,
|
||||||
|
max: 5000,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'static-text',
|
||||||
|
id: 'info',
|
||||||
|
label: 'MPC-HC setup',
|
||||||
|
width: 12,
|
||||||
|
value:
|
||||||
|
'Enable View → Options → Player → Web Interface → Listen on port. Allow this Companion computer to connect.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'textinput',
|
||||||
|
id: 'host',
|
||||||
|
label: 'Main player IP address or hostname',
|
||||||
|
width: 8,
|
||||||
|
default: '127.0.0.1',
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'number',
|
||||||
|
id: 'port',
|
||||||
|
label: 'Main web interface port',
|
||||||
|
width: 4,
|
||||||
|
default: 13579,
|
||||||
|
min: 1,
|
||||||
|
max: 65535,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'textinput',
|
||||||
|
id: 'backup_host',
|
||||||
|
label: 'Backup IP address or hostname (optional)',
|
||||||
|
width: 8,
|
||||||
|
default: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'number',
|
||||||
|
id: 'backup_port',
|
||||||
|
label: 'Backup web interface port',
|
||||||
|
width: 4,
|
||||||
|
default: 13579,
|
||||||
|
min: 1,
|
||||||
|
max: 65535,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'number',
|
||||||
|
id: 'sync_tolerance',
|
||||||
|
label: 'Playback sync tolerance (milliseconds)',
|
||||||
|
width: 8,
|
||||||
|
default: 1000,
|
||||||
|
min: 100,
|
||||||
|
max: 10000,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'checkbox',
|
||||||
|
id: 'compare_audio',
|
||||||
|
label: 'Include mute and volume in sync comparison',
|
||||||
|
width: 12,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,150 @@
|
||||||
|
import { MpcClient } from './client.js'
|
||||||
|
import { loadItem } from './load-item.js'
|
||||||
|
|
||||||
|
// Each player owns its polling loop so an unavailable backup never delays the main.
|
||||||
|
export class Player {
|
||||||
|
constructor(config, interval, changed) {
|
||||||
|
this.client = new MpcClient(config, 2500)
|
||||||
|
this.interval = interval
|
||||||
|
this.changed = changed
|
||||||
|
this.state = null
|
||||||
|
this.active = true
|
||||||
|
this.commands = new Set()
|
||||||
|
this.loadDirection = 'next'
|
||||||
|
this.loadStatus = 'idle'
|
||||||
|
this.loadDetail = ''
|
||||||
|
this.loadDisplayStatus = 'idle'
|
||||||
|
this.loadResult = { status: 'idle', direction: '', file: '', detail: '' }
|
||||||
|
}
|
||||||
|
|
||||||
|
refresh() {
|
||||||
|
if (!this.active) return Promise.resolve()
|
||||||
|
if (this.pending) return this.pending
|
||||||
|
clearTimeout(this.timer)
|
||||||
|
this.pending = (async () => {
|
||||||
|
const started = performance.now()
|
||||||
|
try {
|
||||||
|
const state = await this.client.status()
|
||||||
|
if (!this.active) return
|
||||||
|
this.state = state
|
||||||
|
if (this.loadStatus === 'ready' && (state.file !== this.loadedFile || state.state !== 'stopped')) {
|
||||||
|
this.loadStatus = 'idle'
|
||||||
|
this.loadDetail = ''
|
||||||
|
}
|
||||||
|
// Approximate when the remote snapshot was taken, not when it arrived.
|
||||||
|
this.sampledAt = (started + performance.now()) / 2
|
||||||
|
this.error = null
|
||||||
|
this.changed(this)
|
||||||
|
} catch (error) {
|
||||||
|
if (this.active) this.failed(error)
|
||||||
|
} finally {
|
||||||
|
if (this.active) {
|
||||||
|
this.pending = undefined
|
||||||
|
this.timer = setTimeout(() => void this.refresh(), this.interval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
return this.pending
|
||||||
|
}
|
||||||
|
|
||||||
|
failed(error) {
|
||||||
|
if (this.loadStatus === 'ready') {
|
||||||
|
this.loadStatus = 'idle'
|
||||||
|
this.loadDetail = ''
|
||||||
|
}
|
||||||
|
this.state = null
|
||||||
|
this.error = String(error.cause?.code ?? error.message)
|
||||||
|
this.changed(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
loadNext() {
|
||||||
|
return this.loadItem('next')
|
||||||
|
}
|
||||||
|
|
||||||
|
loadPrevious() {
|
||||||
|
return this.loadItem('previous')
|
||||||
|
}
|
||||||
|
|
||||||
|
loadItem(direction) {
|
||||||
|
if (!this.active) return Promise.resolve()
|
||||||
|
if (this.loading) return this.loading
|
||||||
|
this.loading = (async () => {
|
||||||
|
clearTimeout(this.loadDisplayTimer)
|
||||||
|
this.loadDisplayStatus = 'loading'
|
||||||
|
this.loadResult = { status: 'loading', direction, file: '', detail: '' }
|
||||||
|
this.loadDirection = direction
|
||||||
|
this.loadStatus = 'loading'
|
||||||
|
this.loadDetail = `Muting, selecting ${direction} once, and confirming stopped`
|
||||||
|
this.changed(this)
|
||||||
|
try {
|
||||||
|
await Promise.allSettled([...this.commands])
|
||||||
|
this.loadedFile = await loadItem(this, direction)
|
||||||
|
if (!this.active) return
|
||||||
|
this.loadStatus = 'ready'
|
||||||
|
this.loadDetail = 'Different file loaded and stopped; original mute state restored'
|
||||||
|
} catch (error) {
|
||||||
|
if (!this.active) return
|
||||||
|
this.loadStatus = 'failed'
|
||||||
|
this.loadDetail = error.message
|
||||||
|
} finally {
|
||||||
|
this.loading = undefined
|
||||||
|
if (this.active) {
|
||||||
|
this.loadDisplayStatus = this.loadStatus
|
||||||
|
this.loadResult = {
|
||||||
|
status: this.loadStatus,
|
||||||
|
direction,
|
||||||
|
file: this.loadStatus === 'ready' ? this.loadedFile : '',
|
||||||
|
detail: this.loadDetail,
|
||||||
|
}
|
||||||
|
this.loadDisplayTimer = setTimeout(() => {
|
||||||
|
this.loadDisplayStatus = 'idle'
|
||||||
|
if (this.active) this.changed(this)
|
||||||
|
}, 2000)
|
||||||
|
this.changed(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
return this.loading
|
||||||
|
}
|
||||||
|
|
||||||
|
playPlaylistItem(item) {
|
||||||
|
return this.runCommand(async () => {
|
||||||
|
const number = Number(item)
|
||||||
|
if (!Number.isInteger(number) || number < 1 || number > 10000) throw new Error('Invalid playlist item number')
|
||||||
|
const playlist = await this.client.playlist()
|
||||||
|
if (number > playlist.items.length)
|
||||||
|
throw new Error(`Playlist item ${number} does not exist (${playlist.items.length} items)`)
|
||||||
|
await this.client.selectPlaylistItem(number - 1)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
send(id) {
|
||||||
|
return this.runCommand(() => this.client.command(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
runCommand(command) {
|
||||||
|
if (this.loading) return Promise.resolve(false)
|
||||||
|
const pending = this.sendCommand(command)
|
||||||
|
this.commands.add(pending)
|
||||||
|
return pending.finally(() => this.commands.delete(pending))
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendCommand(command) {
|
||||||
|
if (!this.active) return
|
||||||
|
try {
|
||||||
|
await command()
|
||||||
|
await this.pending
|
||||||
|
if (this.active) await this.refresh()
|
||||||
|
} catch (error) {
|
||||||
|
if (this.active) this.failed(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
close() {
|
||||||
|
this.active = false
|
||||||
|
clearTimeout(this.timer)
|
||||||
|
clearTimeout(this.loadDisplayTimer)
|
||||||
|
this.client.close()
|
||||||
|
this.state = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,75 @@
|
||||||
|
import { variableDefinitions, variables } from './state.js'
|
||||||
|
|
||||||
|
const result = (status, label, reason, offset = null) => ({ status, label, reason, offset })
|
||||||
|
|
||||||
|
function positionAt(player, now) {
|
||||||
|
const state = player.state
|
||||||
|
const advance = state.state === 'playing' ? Math.max(0, now - player.sampledAt) * (state.rate ?? 1) : 0
|
||||||
|
const position = state.position + advance
|
||||||
|
return state.duration > 0 ? Math.min(position, state.duration) : position
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compare filenames rather than absolute paths: backup media can be on another drive.
|
||||||
|
const fileKey = (name) => name.split(/[\\/]/).at(-1).normalize('NFC').toLowerCase()
|
||||||
|
|
||||||
|
export function comparePlayers(main, backup, options = {}, now = performance.now()) {
|
||||||
|
if (!options.configured) return result('no_backup', 'No backup', 'No backup address configured')
|
||||||
|
if (options.configError) return result('backup_config', 'Backup config', options.configError)
|
||||||
|
if (!backup?.state) return result('backup_offline', 'Backup offline', backup?.error ?? 'Waiting for backup status')
|
||||||
|
if (backup.state.state === 'idle' || !backup.state.file)
|
||||||
|
return result('backup_empty', 'Backup empty', 'No active media on backup')
|
||||||
|
if (!main?.state) return result('main_offline', 'Main offline', 'Main player status unavailable; cannot compare')
|
||||||
|
if (main.state.state === 'idle' || !main.state.file)
|
||||||
|
return result('main_empty', 'Main empty', 'No active media on main')
|
||||||
|
const staleAfter = (options.interval ?? 500) + 3000
|
||||||
|
if ([main, backup].some((player) => !Number.isFinite(player.sampledAt) || now - player.sampledAt > staleAfter)) {
|
||||||
|
return result('checking', 'Checking', 'Waiting for fresh status from both players')
|
||||||
|
}
|
||||||
|
const tolerance = options.tolerance ?? 1000
|
||||||
|
const offset = Math.round(positionAt(backup, now) - positionAt(main, now))
|
||||||
|
const mismatch = []
|
||||||
|
if (fileKey(main.state.file) !== fileKey(backup.state.file)) mismatch.push('Different files')
|
||||||
|
if (main.state.state !== backup.state.state) mismatch.push('Different playback states')
|
||||||
|
if (Math.abs(main.state.duration - backup.state.duration) > tolerance) mismatch.push('Different durations')
|
||||||
|
if (Math.abs((main.state.rate ?? 1) - (backup.state.rate ?? 1)) > 0.001) mismatch.push('Different playback speeds')
|
||||||
|
if (Math.abs(offset) > tolerance) mismatch.push(`Backup ${offset > 0 ? 'ahead' : 'behind'} by ${Math.abs(offset)} ms`)
|
||||||
|
if (options.compareAudio) {
|
||||||
|
if (main.state.muted !== backup.state.muted) mismatch.push('Different mute states')
|
||||||
|
if (main.state.volume !== backup.state.volume) mismatch.push('Different volumes')
|
||||||
|
}
|
||||||
|
return mismatch.length
|
||||||
|
? result('out_of_sync', 'Out of sync', mismatch.join('; '), offset)
|
||||||
|
: result('in_sync', 'In sync', `Within ${tolerance} ms of main`, offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const redundancyDefinitions = {
|
||||||
|
...Object.fromEntries(
|
||||||
|
Object.entries(variableDefinitions).map(([id, value]) => [`backup_${id}`, { name: `Backup: ${value.name}` }]),
|
||||||
|
),
|
||||||
|
backup_configured: { name: 'Backup address is configured' },
|
||||||
|
backup_status: { name: 'Backup availability: not_configured, config_error, offline, empty, or connected' },
|
||||||
|
sync_status: { name: 'Redundancy comparison status (machine-readable)' },
|
||||||
|
sync_label: { name: 'Redundancy comparison status for display' },
|
||||||
|
sync_detail: { name: 'Redundancy comparison explanation' },
|
||||||
|
backup_offset_ms: { name: 'Estimated backup position minus main position (milliseconds)' },
|
||||||
|
}
|
||||||
|
|
||||||
|
export function redundancyVariables(backup, options, sync) {
|
||||||
|
return {
|
||||||
|
...Object.fromEntries(Object.entries(variables(backup?.state)).map(([id, value]) => [`backup_${id}`, value])),
|
||||||
|
backup_configured: !!options.configured,
|
||||||
|
backup_status: !options.configured
|
||||||
|
? 'not_configured'
|
||||||
|
: options.configError
|
||||||
|
? 'config_error'
|
||||||
|
: !backup?.state
|
||||||
|
? 'offline'
|
||||||
|
: backup.state.state === 'idle' || !backup.state.file
|
||||||
|
? 'empty'
|
||||||
|
: 'connected',
|
||||||
|
sync_status: sync.status,
|
||||||
|
sync_label: sync.label,
|
||||||
|
sync_detail: sync.reason,
|
||||||
|
backup_offset_ms: sync.offset,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,135 @@
|
||||||
|
const names = { '-1': 'idle', 0: 'stopped', 1: 'paused', 2: 'playing' }
|
||||||
|
|
||||||
|
function number(value, name) {
|
||||||
|
if (value === '' || value === null || value === undefined || !Number.isFinite(Number(value))) {
|
||||||
|
throw new Error(`Invalid MPC-HC status field: ${name}`)
|
||||||
|
}
|
||||||
|
return Number(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeStatus(data) {
|
||||||
|
if (!data || typeof data !== 'object') throw new Error('Invalid MPC-HC status response')
|
||||||
|
const code = number(data.state, 'state')
|
||||||
|
if (!(code in names)) throw new Error(`Unknown MPC-HC playback state: ${code}`)
|
||||||
|
const position = Math.max(0, number(data.position, 'position'))
|
||||||
|
const duration = Math.max(0, number(data.duration, 'duration'))
|
||||||
|
const volume = number(data.volume, 'volume')
|
||||||
|
if (typeof data.muted !== 'boolean' || volume < 0 || volume > 100) throw new Error('Invalid MPC-HC audio status')
|
||||||
|
return {
|
||||||
|
state: names[code],
|
||||||
|
file: typeof data.file === 'string' ? data.file : '',
|
||||||
|
position,
|
||||||
|
duration,
|
||||||
|
remaining: duration > 0 ? Math.max(0, duration - position) : null,
|
||||||
|
progress: duration > 0 ? Math.min(100, (position / duration) * 100) : null,
|
||||||
|
volume,
|
||||||
|
muted: data.muted,
|
||||||
|
rate: data.rate === undefined ? null : number(data.rate, 'rate'),
|
||||||
|
version: typeof data.version === 'string' ? data.version : '',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function decode(text) {
|
||||||
|
const named = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' }
|
||||||
|
return text.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi, (match, key) => {
|
||||||
|
if (!key.startsWith('#')) return named[key.toLowerCase()]
|
||||||
|
const code = key[1].toLowerCase() === 'x' ? parseInt(key.slice(2), 16) : Number(key.slice(1))
|
||||||
|
return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseVariables(html) {
|
||||||
|
const fields = {}
|
||||||
|
for (const match of html.matchAll(/<p\b[^>]*\bid\s*=\s*["']([^"']+)["'][^>]*>([\s\S]*?)<\/p\s*>/gi)) {
|
||||||
|
fields[match[1]] = decode(match[2].trim())
|
||||||
|
}
|
||||||
|
if (!['0', '1'].includes(fields.muted)) throw new Error('Invalid MPC-HC status field: muted')
|
||||||
|
return normalizeStatus({
|
||||||
|
...fields,
|
||||||
|
volume: fields.volumelevel,
|
||||||
|
muted: fields.muted === '1',
|
||||||
|
rate: fields.playbackrate,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clock(milliseconds, roundUp = false) {
|
||||||
|
if (milliseconds === null || milliseconds === undefined) return '--:--'
|
||||||
|
const seconds = Math.max(0, (roundUp ? Math.ceil : Math.floor)(milliseconds / 1000))
|
||||||
|
const hours = Math.floor(seconds / 3600)
|
||||||
|
const minutes = String(Math.floor(seconds / 60) % 60).padStart(2, '0')
|
||||||
|
const remainder = String(seconds % 60).padStart(2, '0')
|
||||||
|
return hours ? `${hours}:${minutes}:${remainder}` : `${minutes}:${remainder}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clockParts(milliseconds, roundUp = false) {
|
||||||
|
if (milliseconds === null || milliseconds === undefined) return { hh: '--', mm: '--', ss: '--' }
|
||||||
|
// Round once before splitting so all three buttons agree at minute/hour boundaries.
|
||||||
|
const seconds = Math.max(0, (roundUp ? Math.ceil : Math.floor)(milliseconds / 1000))
|
||||||
|
return {
|
||||||
|
hh: String(Math.floor(seconds / 3600)).padStart(2, '0'),
|
||||||
|
mm: String(Math.floor(seconds / 60) % 60).padStart(2, '0'),
|
||||||
|
ss: String(seconds % 60).padStart(2, '0'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const variableDefinitions = Object.fromEntries(
|
||||||
|
Object.entries({
|
||||||
|
connected: 'Status data is available',
|
||||||
|
state: 'Playback state: playing, paused, stopped, idle, or offline',
|
||||||
|
state_label: 'Playback state for display: Playing, Paused, Stopped, Idle, or Offline',
|
||||||
|
playing: 'Player reports playing',
|
||||||
|
stopped: 'Player reports stopped (idle is separate)',
|
||||||
|
paused: 'Player reports paused',
|
||||||
|
muted: 'Player mute switch (independent of volume)',
|
||||||
|
volume: 'Volume percent',
|
||||||
|
file: 'Current filename',
|
||||||
|
elapsed: 'Elapsed media time',
|
||||||
|
duration: 'Media duration',
|
||||||
|
remaining: 'Remaining media time',
|
||||||
|
remaining_hh: 'Remaining hours, padded (split timer)',
|
||||||
|
remaining_mm: 'Remaining minutes within hour, padded (split timer)',
|
||||||
|
remaining_ss: 'Remaining seconds within minute, padded (split timer)',
|
||||||
|
elapsed_hh: 'Elapsed hours, padded (split timer)',
|
||||||
|
elapsed_mm: 'Elapsed minutes within hour, padded (split timer)',
|
||||||
|
elapsed_ss: 'Elapsed seconds within minute, padded (split timer)',
|
||||||
|
elapsed_seconds: 'Elapsed media time in seconds',
|
||||||
|
duration_seconds: 'Media duration in seconds',
|
||||||
|
remaining_seconds: 'Remaining media time in seconds',
|
||||||
|
progress: 'Media progress percent (0–100)',
|
||||||
|
rate: 'Playback rate',
|
||||||
|
version: 'MPC-HC version',
|
||||||
|
}).map(([id, name]) => [id, { name }]),
|
||||||
|
)
|
||||||
|
|
||||||
|
export function variables(state) {
|
||||||
|
const available = state && state.state !== 'idle'
|
||||||
|
return {
|
||||||
|
...Object.fromEntries(
|
||||||
|
Object.entries(clockParts(available ? state.remaining : null, true)).map(([part, value]) => [
|
||||||
|
`remaining_${part}`,
|
||||||
|
value,
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
...Object.fromEntries(
|
||||||
|
Object.entries(clockParts(available ? state.position : null)).map(([part, value]) => [`elapsed_${part}`, value]),
|
||||||
|
),
|
||||||
|
connected: !!state,
|
||||||
|
state: state?.state ?? 'offline',
|
||||||
|
state_label: state ? state.state[0].toUpperCase() + state.state.slice(1) : 'Offline',
|
||||||
|
playing: state ? state.state === 'playing' : null,
|
||||||
|
stopped: state ? state.state === 'stopped' : null,
|
||||||
|
paused: state ? state.state === 'paused' : null,
|
||||||
|
muted: state?.muted ?? null,
|
||||||
|
volume: state?.volume ?? null,
|
||||||
|
file: state?.file ?? '',
|
||||||
|
elapsed: clock(state?.position),
|
||||||
|
duration: clock(state && state.duration > 0 ? state.duration : null, true),
|
||||||
|
remaining: clock(state?.remaining, true),
|
||||||
|
elapsed_seconds: state ? state.position / 1000 : null,
|
||||||
|
duration_seconds: state && state.duration > 0 ? state.duration / 1000 : null,
|
||||||
|
remaining_seconds: state?.remaining == null ? null : state.remaining / 1000,
|
||||||
|
progress: state?.progress == null ? null : Math.round(state.progress * 10) / 10,
|
||||||
|
rate: state?.rate ?? null,
|
||||||
|
version: state?.version ?? '',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,116 @@
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { createServer } from 'node:http'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import { MpcClient, endpoint } from '../src/client.js'
|
||||||
|
import { actions, presets } from '../src/definitions.js'
|
||||||
|
import { status, htmlStatus } from './fixture.js'
|
||||||
|
|
||||||
|
async function server(t, handler) {
|
||||||
|
const server = createServer(handler)
|
||||||
|
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||||
|
t.after(() => {
|
||||||
|
server.closeAllConnections()
|
||||||
|
server.close()
|
||||||
|
})
|
||||||
|
return { host: '127.0.0.1', port: server.address().port }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('all original actions and presets dispatch their numeric command IDs', async (t) => {
|
||||||
|
const paths = []
|
||||||
|
const client = new MpcClient(
|
||||||
|
await server(t, (req, res) => {
|
||||||
|
paths.push(req.url)
|
||||||
|
res.end(JSON.stringify(status))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
t.after(() => client.close())
|
||||||
|
const definitions = actions((id) => client.command(id))
|
||||||
|
assert.equal(Object.keys(definitions).length, 138)
|
||||||
|
for (const [id, action] of Object.entries(definitions)) {
|
||||||
|
await action.callback()
|
||||||
|
assert.equal(paths.at(-1), `/command.html?wm_command=${id}`)
|
||||||
|
assert.equal(presets()[id].steps[0].down[0].actionId, id)
|
||||||
|
}
|
||||||
|
await client.probe()
|
||||||
|
assert.equal(paths.at(-1), '/status.json')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('HTTP failures and redirects fail rather than reporting success', async (t) => {
|
||||||
|
for (const status of [404, 500, 302]) {
|
||||||
|
const client = new MpcClient(
|
||||||
|
await server(t, (_, res) => {
|
||||||
|
res.writeHead(status, { Location: '/other' })
|
||||||
|
res.end()
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
t.after(() => client.close())
|
||||||
|
await assert.rejects(client.probe())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('timeouts and module destruction cancel pending requests', async (t) => {
|
||||||
|
const config = await server(t, () => {})
|
||||||
|
const timeout = new MpcClient(config, 30)
|
||||||
|
await assert.rejects(timeout.probe(), { name: 'TimeoutError' })
|
||||||
|
timeout.close()
|
||||||
|
const client = new MpcClient(config)
|
||||||
|
const pending = client.probe()
|
||||||
|
client.close()
|
||||||
|
await assert.rejects(pending, { name: 'AbortError' })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('reject invalid configuration and command injection', async () => {
|
||||||
|
for (const config of [
|
||||||
|
{ host: '' },
|
||||||
|
{ host: 'localhost/path' },
|
||||||
|
{ host: 'localhost', port: 0 },
|
||||||
|
{ host: 'localhost', port: 65536 },
|
||||||
|
]) {
|
||||||
|
assert.throws(() => endpoint(config))
|
||||||
|
}
|
||||||
|
assert.equal(endpoint({ host: '::1' }).hostname, '[::1]')
|
||||||
|
const client = new MpcClient({ host: 'localhost' })
|
||||||
|
await assert.rejects(client.command('887&extra=1'))
|
||||||
|
client.close()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('prefer JSON, fall back once for unavailable endpoints, and decode HTML entities', async (t) => {
|
||||||
|
for (const unavailable of [404, 200]) {
|
||||||
|
const paths = []
|
||||||
|
const client = new MpcClient(
|
||||||
|
await server(t, (req, res) => {
|
||||||
|
paths.push(req.url)
|
||||||
|
if (req.url === '/status.json') {
|
||||||
|
res.writeHead(unavailable)
|
||||||
|
res.end('<html>Home</html>')
|
||||||
|
} else res.end(htmlStatus({ ...status, file: 'A & B 🎬', muted: true }))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
t.after(() => client.close())
|
||||||
|
const first = await client.status()
|
||||||
|
assert.equal(first.file, 'A & B 🎬')
|
||||||
|
assert.equal(first.muted, true)
|
||||||
|
assert.equal(first.state, 'playing')
|
||||||
|
await client.status()
|
||||||
|
assert.deepEqual(paths, ['/status.json', '/variables.html', '/variables.html'])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('malformed status and server failures are not hidden by HTML fallback', async (t) => {
|
||||||
|
for (const body of ['garbage', '{}', JSON.stringify({ ...status, muted: 'false' })]) {
|
||||||
|
const client = new MpcClient(await server(t, (_, res) => res.end(body)))
|
||||||
|
t.after(() => client.close())
|
||||||
|
await assert.rejects(client.status())
|
||||||
|
}
|
||||||
|
let count = 0
|
||||||
|
const client = new MpcClient(
|
||||||
|
await server(t, (_, res) => {
|
||||||
|
count++
|
||||||
|
res.writeHead(503)
|
||||||
|
res.end()
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
t.after(() => client.close())
|
||||||
|
await assert.rejects(client.status())
|
||||||
|
assert.equal(count, 1)
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
export const status = {
|
||||||
|
file: 'Test clip.mp4',
|
||||||
|
state: 2,
|
||||||
|
position: 12500,
|
||||||
|
duration: 60000,
|
||||||
|
volume: 75,
|
||||||
|
muted: false,
|
||||||
|
rate: 1,
|
||||||
|
version: '2.8.5.0',
|
||||||
|
}
|
||||||
|
|
||||||
|
export function htmlStatus(data = status) {
|
||||||
|
return Object.entries({ ...data, volumelevel: data.volume, muted: data.muted ? 1 : 0, playbackrate: data.rate })
|
||||||
|
.map(([key, value]) => `<p id="${key}">${value}</p>`)
|
||||||
|
.join('\n')
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,213 @@
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { createServer } from 'node:http'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import { InstanceStatus } from '@companion-module/base'
|
||||||
|
import MpcInstance from '../src/main.js'
|
||||||
|
import { status as sample } from './fixture.js'
|
||||||
|
|
||||||
|
function instance() {
|
||||||
|
const state = { statuses: [] }
|
||||||
|
const module = new MpcInstance({
|
||||||
|
_isInstanceContext: true,
|
||||||
|
id: 'test-mpc',
|
||||||
|
label: 'MPC_TEST',
|
||||||
|
setActionDefinitions: (actions) => {
|
||||||
|
state.actions = actions
|
||||||
|
},
|
||||||
|
setPresetDefinitions: (sections, presets) => {
|
||||||
|
state.sections = sections
|
||||||
|
state.presets = presets
|
||||||
|
},
|
||||||
|
setFeedbackDefinitions: (feedbacks) => {
|
||||||
|
state.feedbacks = feedbacks
|
||||||
|
},
|
||||||
|
setVariableDefinitions: () => {},
|
||||||
|
setVariableValues: (variables) => {
|
||||||
|
state.variables = variables
|
||||||
|
},
|
||||||
|
checkAllFeedbacks: () => {},
|
||||||
|
updateStatus: (status) => state.statuses.push(status),
|
||||||
|
})
|
||||||
|
return { module, state }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('initialization registers API 2 presets; successful actions recover failed requests', async (t) => {
|
||||||
|
let status = 200
|
||||||
|
const server = createServer((_, response) => {
|
||||||
|
response.writeHead(status)
|
||||||
|
response.end(JSON.stringify(sample))
|
||||||
|
})
|
||||||
|
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||||
|
const { module, state } = instance()
|
||||||
|
t.after(async () => {
|
||||||
|
await module.destroy()
|
||||||
|
server.closeAllConnections()
|
||||||
|
server.close()
|
||||||
|
})
|
||||||
|
await module.init({ host: '127.0.0.1', port: server.address().port })
|
||||||
|
await module.send('887')
|
||||||
|
assert.equal(state.statuses.at(-1), InstanceStatus.Ok)
|
||||||
|
assert.equal(Object.keys(state.actions).length, 142)
|
||||||
|
assert.deepEqual(state.sections.flatMap((section) => section.definitions).sort(), Object.keys(state.presets).sort())
|
||||||
|
assert.equal(state.variables.remaining, '00:48')
|
||||||
|
assert.equal(state.feedbacks.playing.callback(), true)
|
||||||
|
assert.ok(Object.values(state.presets).every((preset) => ['simple', 'layered'].includes(preset.type)))
|
||||||
|
status = 503
|
||||||
|
await module.send('887')
|
||||||
|
assert.equal(state.statuses.at(-1), InstanceStatus.ConnectionFailure)
|
||||||
|
assert.equal(state.variables.state, 'offline')
|
||||||
|
assert.equal(state.variables.muted, null)
|
||||||
|
assert.equal(state.feedbacks.playing.callback(), false)
|
||||||
|
status = 200
|
||||||
|
await module.send('888')
|
||||||
|
assert.equal(state.statuses.at(-1), InstanceStatus.Ok)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('configuration changes and destroy cancel stale operations without overwriting status', async (t) => {
|
||||||
|
const server = createServer(() => {})
|
||||||
|
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||||
|
t.after(() => {
|
||||||
|
server.closeAllConnections()
|
||||||
|
server.close()
|
||||||
|
})
|
||||||
|
const { module, state } = instance()
|
||||||
|
await module.init({ host: '127.0.0.1', port: server.address().port })
|
||||||
|
const oldRequest = module.send('887')
|
||||||
|
await module.configUpdated({ host: '' })
|
||||||
|
await oldRequest
|
||||||
|
assert.equal(state.statuses.at(-1), InstanceStatus.BadConfig)
|
||||||
|
await module.configUpdated({ host: '127.0.0.1', port: server.address().port })
|
||||||
|
const pending = module.send('888')
|
||||||
|
await module.destroy()
|
||||||
|
const count = state.statuses.length
|
||||||
|
await pending
|
||||||
|
assert.equal(state.statuses.length, count)
|
||||||
|
assert.equal(module.main, undefined)
|
||||||
|
assert.equal(module.backup, undefined)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('polling discovers external changes, retries failures, and stops on destroy', async (t) => {
|
||||||
|
let data = { ...sample }
|
||||||
|
let code = 200
|
||||||
|
let requests = 0
|
||||||
|
let active = 0
|
||||||
|
let maximum = 0
|
||||||
|
const server = createServer((_, response) => {
|
||||||
|
requests++
|
||||||
|
active++
|
||||||
|
maximum = Math.max(maximum, active)
|
||||||
|
setTimeout(() => {
|
||||||
|
active--
|
||||||
|
response.writeHead(code)
|
||||||
|
response.end(JSON.stringify(data))
|
||||||
|
}, 15)
|
||||||
|
})
|
||||||
|
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||||
|
const { module, state } = instance()
|
||||||
|
t.after(async () => {
|
||||||
|
await module.destroy()
|
||||||
|
server.closeAllConnections()
|
||||||
|
server.close()
|
||||||
|
})
|
||||||
|
const until = async (condition) => {
|
||||||
|
const deadline = Date.now() + 3000
|
||||||
|
while (!condition()) {
|
||||||
|
assert.ok(Date.now() < deadline, 'polling did not reach expected state')
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await module.init({ host: '127.0.0.1', port: server.address().port, poll_interval: 250 })
|
||||||
|
await Promise.all(Array.from({ length: 10 }, () => module.refresh()))
|
||||||
|
assert.equal(maximum, 1)
|
||||||
|
assert.equal(requests, 1)
|
||||||
|
data = { ...sample, state: 1, muted: true, position: 20000 }
|
||||||
|
await until(() => state.variables.paused && state.variables.muted)
|
||||||
|
assert.equal(state.variables.remaining, '00:40')
|
||||||
|
code = 503
|
||||||
|
await until(() => state.variables.state === 'offline')
|
||||||
|
assert.equal(state.variables.remaining, '--:--')
|
||||||
|
code = 200
|
||||||
|
data = { ...sample, state: 0, position: 0 }
|
||||||
|
await until(() => state.variables.stopped)
|
||||||
|
assert.equal(state.feedbacks.stopped.callback(), true)
|
||||||
|
await module.destroy()
|
||||||
|
const lastCount = requests
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 350))
|
||||||
|
assert.equal(requests, lastCount)
|
||||||
|
})
|
||||||
|
|
||||||
|
for (const direction of ['next', 'previous']) {
|
||||||
|
const navigationId = direction === 'next' ? '920' : '919'
|
||||||
|
test(`Load ${direction} preset runs on main with unavailable backup and exposes independent results`, async (t) => {
|
||||||
|
const data = { ...sample, state: 0 }
|
||||||
|
const commands = []
|
||||||
|
const mainServer = createServer((req, res) => {
|
||||||
|
const id = new URL(req.url, 'http://localhost').searchParams.get('wm_command')
|
||||||
|
if (id) {
|
||||||
|
commands.push(id)
|
||||||
|
if (id === '909') data.muted = !data.muted
|
||||||
|
if (id === navigationId) {
|
||||||
|
data.file = 'Next.mp4'
|
||||||
|
data.state = 2
|
||||||
|
}
|
||||||
|
if (id === '890') data.state = 0
|
||||||
|
}
|
||||||
|
res.end(JSON.stringify(data))
|
||||||
|
})
|
||||||
|
const backupServer = createServer((_, res) => {
|
||||||
|
res.writeHead(503)
|
||||||
|
res.end()
|
||||||
|
})
|
||||||
|
await Promise.all(
|
||||||
|
[mainServer, backupServer].map((server) => new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))),
|
||||||
|
)
|
||||||
|
const { module, state } = instance()
|
||||||
|
t.after(async () => {
|
||||||
|
await module.destroy()
|
||||||
|
for (const server of [mainServer, backupServer]) {
|
||||||
|
server.closeAllConnections()
|
||||||
|
server.close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
await module.init({
|
||||||
|
host: '127.0.0.1',
|
||||||
|
port: mainServer.address().port,
|
||||||
|
backup_host: '127.0.0.1',
|
||||||
|
backup_port: backupServer.address().port,
|
||||||
|
})
|
||||||
|
assert.equal(state.presets[`transport_load_${direction}`].steps[0].down[0].actionId, `load_${direction}`)
|
||||||
|
const pending = state.actions[`load_${direction}`].callback({ options: { target: 'both' } })
|
||||||
|
await module.send('887')
|
||||||
|
await Promise.all([pending, state.actions[`load_${direction}`].callback({ options: { target: 'both' } })])
|
||||||
|
assert.deepEqual(commands, ['909', navigationId, '890', '909'])
|
||||||
|
assert.equal(state.variables[`load_${direction}_status`], 'ready')
|
||||||
|
assert.equal(state.variables[`backup_load_${direction}_status`], 'failed')
|
||||||
|
assert.equal(state.variables[`load_${direction === 'next' ? 'previous' : 'next'}_status`], 'idle')
|
||||||
|
assert.equal(state.statuses.at(-1), InstanceStatus.Ok)
|
||||||
|
assert.equal(
|
||||||
|
state.feedbacks[`load_${direction}_status`].callback().text,
|
||||||
|
direction === 'next' ? '↦\nLOADED\nNEXT' : '↤\nLOADED\nPREV',
|
||||||
|
)
|
||||||
|
assert.deepEqual(state.presets.transport_load_result.steps[0].down, [])
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2100))
|
||||||
|
assert.equal(
|
||||||
|
state.feedbacks[`load_${direction}_status`].callback().text,
|
||||||
|
direction === 'next' ? '↦\nLOAD\nNEXT' : '↤\nLOAD\nPREV',
|
||||||
|
)
|
||||||
|
assert.equal(module.backup.loadDisplayStatus, 'idle')
|
||||||
|
assert.equal(state.variables.backup_load_result_status, 'failed')
|
||||||
|
assert.equal(state.variables.load_result_status, 'ready')
|
||||||
|
assert.equal(state.variables.load_result_direction, direction)
|
||||||
|
assert.equal(state.variables.load_result_file, 'Next.mp4')
|
||||||
|
const resultText = 'LOADED\nNext'
|
||||||
|
assert.equal(state.feedbacks.load_result.callback().text, resultText)
|
||||||
|
data.state = 2
|
||||||
|
await module.refresh()
|
||||||
|
assert.equal(state.variables[`load_${direction}_status`], 'idle')
|
||||||
|
assert.equal(state.feedbacks.load_result.callback().text, resultText)
|
||||||
|
data.volume = null
|
||||||
|
await module.refresh()
|
||||||
|
assert.equal(state.variables.state, 'offline')
|
||||||
|
assert.equal(state.feedbacks.load_result.callback().text, resultText)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,177 @@
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { createServer } from 'node:http'
|
||||||
|
import { setTimeout as delay } from 'node:timers/promises'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import { Player } from '../src/player.js'
|
||||||
|
import { loadItem } from '../src/load-item.js'
|
||||||
|
import { status } from './fixture.js'
|
||||||
|
|
||||||
|
async function mock(t, handle, initial = {}) {
|
||||||
|
const data = { ...status, state: 0, ...initial }
|
||||||
|
const commands = []
|
||||||
|
const events = []
|
||||||
|
const server = createServer((req, res) => {
|
||||||
|
const id = new URL(req.url, 'http://localhost').searchParams.get('wm_command')
|
||||||
|
if (id) {
|
||||||
|
commands.push(id)
|
||||||
|
events.push(id)
|
||||||
|
if (handle?.(id, data, res) === false) return
|
||||||
|
if (id === '909') data.muted = !data.muted
|
||||||
|
res.end()
|
||||||
|
} else {
|
||||||
|
events.push(data.muted ? 'muted-status' : 'unmuted-status')
|
||||||
|
res.end(JSON.stringify(data))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||||
|
const player = new Player({ host: '127.0.0.1', port: server.address().port }, 5000, () => {})
|
||||||
|
t.after(() => {
|
||||||
|
player.close()
|
||||||
|
server.closeAllConnections()
|
||||||
|
server.close()
|
||||||
|
})
|
||||||
|
return { player, data, commands, events }
|
||||||
|
}
|
||||||
|
const fast = { poll: 10, settle: 40, timeout: 250 }
|
||||||
|
|
||||||
|
for (const direction of ['next', 'previous']) {
|
||||||
|
const navigationId = direction === 'next' ? '920' : '919'
|
||||||
|
const loadNext = (player, timing) => loadItem(player, direction, timing)
|
||||||
|
test(`Load ${direction}: waits for confirmed mute, immediately stops, retries delayed autoplay, then restores audio`, async (t) => {
|
||||||
|
let stops = 0
|
||||||
|
const { player, commands, events } = await mock(t, (id, data) => {
|
||||||
|
if (id === navigationId)
|
||||||
|
setTimeout(() => {
|
||||||
|
data.file = 'Next.mp4'
|
||||||
|
data.state = 2
|
||||||
|
}, 35)
|
||||||
|
if (id === '890' && ++stops >= 3) data.state = 0
|
||||||
|
})
|
||||||
|
assert.equal(await loadNext(player, fast), 'Next.mp4')
|
||||||
|
assert.equal(commands.filter((id) => id === navigationId).length, 1)
|
||||||
|
assert.equal(commands.filter((id) => id === '909').length, 2)
|
||||||
|
const next = events.indexOf(navigationId)
|
||||||
|
assert.ok(events.slice(0, next).includes('muted-status'))
|
||||||
|
assert.equal(events[next + 1], '890', 'no status request delays the first Stop')
|
||||||
|
assert.ok(stops >= 3)
|
||||||
|
assert.equal(player.state.state, 'stopped')
|
||||||
|
assert.equal(player.state.muted, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test(`Load ${direction}: preserves existing mute and waits through a false stopped snapshot`, async (t) => {
|
||||||
|
const { player, commands } = await mock(
|
||||||
|
t,
|
||||||
|
(id, data) => {
|
||||||
|
if (id === navigationId) {
|
||||||
|
data.file = 'Next.mp4'
|
||||||
|
setTimeout(() => {
|
||||||
|
data.state = 2
|
||||||
|
}, 25)
|
||||||
|
}
|
||||||
|
if (id === '890') data.state = 0
|
||||||
|
},
|
||||||
|
{ muted: true },
|
||||||
|
)
|
||||||
|
await loadNext(player, fast)
|
||||||
|
assert.ok(commands.filter((id) => id === '890').length >= 2)
|
||||||
|
assert.ok(!commands.includes('909'))
|
||||||
|
assert.equal(player.state.muted, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test(`Load ${direction}: unconfirmed mute never advances and toggle is not retried`, async (t) => {
|
||||||
|
const { player, commands } = await mock(t, (id, _, res) => {
|
||||||
|
if (id === '909') {
|
||||||
|
res.end()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
await assert.rejects(loadNext(player, fast), /Mute was not confirmed/)
|
||||||
|
assert.deepEqual(commands, ['909'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test(`Load ${direction}: unchanged filename or failure to stop leaves mute enabled and never skips twice`, async (t) => {
|
||||||
|
for (const changeFile of [false, true]) {
|
||||||
|
const { player, commands, data } = await mock(t, (id, data) => {
|
||||||
|
if (id === navigationId && changeFile) {
|
||||||
|
data.file = 'Next.mp4'
|
||||||
|
data.state = 2
|
||||||
|
}
|
||||||
|
})
|
||||||
|
await assert.rejects(loadNext(player, fast), /not confirmed/)
|
||||||
|
assert.equal(data.muted, true)
|
||||||
|
assert.equal(commands.filter((id) => id === navigationId).length, 1)
|
||||||
|
assert.equal(commands.filter((id) => id === '909').length, 1)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test(`Load ${direction}: lost navigation response triggers best-effort Stop without retrying navigation or unmuting`, async (t) => {
|
||||||
|
const { player, commands, data } = await mock(t, (id, data, res) => {
|
||||||
|
if (id === navigationId) {
|
||||||
|
data.file = 'Next.mp4'
|
||||||
|
data.state = 2
|
||||||
|
res.writeHead(500)
|
||||||
|
res.end()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (id === '890') data.state = 0
|
||||||
|
})
|
||||||
|
await assert.rejects(loadNext(player, fast), /HTTP 500/)
|
||||||
|
assert.deepEqual(commands, ['909', navigationId, '890'])
|
||||||
|
assert.equal(data.muted, true)
|
||||||
|
assert.equal(data.state, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test(`Load ${direction}: Player coalesces repeated loading, excludes normal commands and publishes verified success`, async (t) => {
|
||||||
|
const { player, commands } = await mock(t, (id, data) => {
|
||||||
|
if (id === navigationId) {
|
||||||
|
data.file = 'Next.mp4'
|
||||||
|
data.state = 2
|
||||||
|
}
|
||||||
|
if (id === '890') data.state = 0
|
||||||
|
})
|
||||||
|
const pending = player.loadItem(direction)
|
||||||
|
assert.equal(player.loadItem(direction), pending)
|
||||||
|
assert.equal(player.loadItem(direction === 'next' ? 'previous' : 'next'), pending)
|
||||||
|
assert.equal(await player.send('887'), false)
|
||||||
|
await pending
|
||||||
|
assert.equal(player.loadStatus, 'ready')
|
||||||
|
assert.deepEqual(commands, ['909', navigationId, '890', '909'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test(`Load ${direction}: closing a player cancels a load sequence without sending navigation or restoring audio`, async (t) => {
|
||||||
|
const { player, commands } = await mock(t, (id, _, res) => {
|
||||||
|
if (id === '909') {
|
||||||
|
res.end()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const pending = player.loadItem(direction)
|
||||||
|
while (!commands.length) await delay(5)
|
||||||
|
player.close()
|
||||||
|
await pending
|
||||||
|
await delay(80)
|
||||||
|
assert.deepEqual(commands, ['909'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test(`Load ${direction}: uncertain final unmute is not toggled again and cannot report ready`, async (t) => {
|
||||||
|
let toggles = 0
|
||||||
|
const { player, commands } = await mock(t, (id, data, res) => {
|
||||||
|
if (id === navigationId) {
|
||||||
|
data.file = 'Next.mp4'
|
||||||
|
data.state = 2
|
||||||
|
}
|
||||||
|
if (id === '890') data.state = 0
|
||||||
|
if (id === '909' && ++toggles === 2) {
|
||||||
|
data.muted = false
|
||||||
|
res.writeHead(500)
|
||||||
|
res.end()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
await player.loadItem(direction)
|
||||||
|
assert.equal(player.loadStatus, 'failed')
|
||||||
|
assert.equal(commands.filter((id) => id === '909').length, 2)
|
||||||
|
assert.equal(commands.filter((id) => id === navigationId).length, 1)
|
||||||
|
assert.equal(commands.at(-1), '890')
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,195 @@
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { createServer } from 'node:http'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import { Player } from '../src/player.js'
|
||||||
|
import { loadItem } from '../src/load-item.js'
|
||||||
|
import { actions, presets } from '../src/definitions.js'
|
||||||
|
import { feedbacks } from '../src/feedbacks.js'
|
||||||
|
import { status } from './fixture.js'
|
||||||
|
|
||||||
|
const fast = { poll: 10, settle: 40, timeout: 220 }
|
||||||
|
async function mock(t, onSelect) {
|
||||||
|
const data = { ...status, file: 'Clip 1.mp4', state: 0 }
|
||||||
|
const playlist = {
|
||||||
|
active: 0,
|
||||||
|
items: Array.from({ length: 12 }, (_, index) => ({ index, label: `Clip ${index + 1}.mp4`, duration: 60000 })),
|
||||||
|
}
|
||||||
|
const commands = []
|
||||||
|
const server = createServer((req, res) => {
|
||||||
|
const url = new URL(req.url, 'http://localhost')
|
||||||
|
if (url.pathname === '/playlist.json') return res.end(JSON.stringify(playlist))
|
||||||
|
const command = url.searchParams.get('wm_command')
|
||||||
|
if (command) {
|
||||||
|
commands.push(req.url)
|
||||||
|
if (command === '909') data.muted = !data.muted
|
||||||
|
if (command === '890') data.state = 0
|
||||||
|
if (command === '-3') {
|
||||||
|
const index = Number(url.searchParams.get('index'))
|
||||||
|
if (onSelect) onSelect({ index, data, playlist, res })
|
||||||
|
else {
|
||||||
|
playlist.active = index
|
||||||
|
data.file = playlist.items[index].label
|
||||||
|
data.state = 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!res.writableEnded) res.end()
|
||||||
|
} else res.end(JSON.stringify(data))
|
||||||
|
})
|
||||||
|
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||||
|
const player = new Player({ host: '127.0.0.1', port: server.address().port }, 5000, () => {})
|
||||||
|
t.after(() => {
|
||||||
|
player.close()
|
||||||
|
server.closeAllConnections()
|
||||||
|
server.close()
|
||||||
|
})
|
||||||
|
return { player, data, playlist, commands }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('numbered loading converts 1-based numbers, supports items beyond the presets, and restores mute', async (t) => {
|
||||||
|
const { player, commands, data, playlist } = await mock(t)
|
||||||
|
assert.equal(await loadItem(player, 'item_12', fast), 'Clip 12.mp4')
|
||||||
|
assert.deepEqual(commands, [
|
||||||
|
'/command.html?wm_command=909',
|
||||||
|
'/command.html?wm_command=-3&index=11',
|
||||||
|
'/command.html?wm_command=890',
|
||||||
|
'/command.html?wm_command=909',
|
||||||
|
])
|
||||||
|
assert.equal(playlist.active, 11)
|
||||||
|
assert.equal(data.state, 0)
|
||||||
|
assert.equal(data.muted, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('invalid or missing playlist items fail before muting or navigation', async (t) => {
|
||||||
|
const { player, commands, playlist } = await mock(t)
|
||||||
|
for (const direction of ['item_0', 'item_-1', 'item_1.5', 'item_13', 'item_10001', 'item_1&index=2']) {
|
||||||
|
await assert.rejects(loadItem(player, direction, fast))
|
||||||
|
}
|
||||||
|
playlist.items = []
|
||||||
|
playlist.active = -1
|
||||||
|
await assert.rejects(loadItem(player, 'item_1', fast), /does not exist/)
|
||||||
|
assert.deepEqual(commands, [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('loading the already selected item stops without reopening and preserves existing mute', async (t) => {
|
||||||
|
const { player, commands, data } = await mock(t)
|
||||||
|
data.state = 2
|
||||||
|
data.muted = true
|
||||||
|
assert.equal(await loadItem(player, 'item_1', fast), 'Clip 1.mp4')
|
||||||
|
assert.deepEqual(commands, ['/command.html?wm_command=890'])
|
||||||
|
assert.equal(data.muted, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('indexed selection does not mistake an early active-index update for completed loading', async (t) => {
|
||||||
|
const { player, data, commands } = await mock(t, ({ index, data, playlist }) => {
|
||||||
|
playlist.active = index
|
||||||
|
setTimeout(() => {
|
||||||
|
data.file = playlist.items[index].label
|
||||||
|
data.state = 2
|
||||||
|
}, 70)
|
||||||
|
})
|
||||||
|
assert.equal(await loadItem(player, 'item_3', { ...fast, timeout: 500 }), 'Clip 3.mp4')
|
||||||
|
assert.equal(data.state, 0)
|
||||||
|
assert.equal(data.muted, false)
|
||||||
|
assert.ok(commands.filter((path) => path.includes('wm_command=890')).length >= 2)
|
||||||
|
assert.equal(commands.filter((path) => path.includes('wm_command=-3')).length, 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('wrong active index, unchanged filename, or playlist changes cannot restore audio', async (t) => {
|
||||||
|
for (const problem of ['index', 'filename', 'reorder']) {
|
||||||
|
const { player, commands, data } = await mock(t, ({ index, data, playlist }) => {
|
||||||
|
if (problem !== 'index') playlist.active = index
|
||||||
|
if (problem !== 'filename') data.file = 'Clip 2.mp4'
|
||||||
|
if (problem === 'reorder') playlist.items[1].label = 'Replacement.mp4'
|
||||||
|
})
|
||||||
|
await assert.rejects(loadItem(player, 'item_2', fast))
|
||||||
|
assert.equal(data.muted, true)
|
||||||
|
assert.equal(commands.filter((path) => path.includes('wm_command=909')).length, 1)
|
||||||
|
assert.equal(commands.filter((path) => path.includes('wm_command=-3')).length, 1)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('uncertain indexed-selection response stops without selecting again or restoring audio', async (t) => {
|
||||||
|
const { player, commands, data } = await mock(t, ({ index, data, playlist, res }) => {
|
||||||
|
playlist.active = index
|
||||||
|
data.file = 'Clip 2.mp4'
|
||||||
|
data.state = 2
|
||||||
|
res.writeHead(500)
|
||||||
|
res.end()
|
||||||
|
})
|
||||||
|
await assert.rejects(loadItem(player, 'item_2', fast), /HTTP 500/)
|
||||||
|
assert.equal(commands.filter((path) => path.includes('wm_command=-3')).length, 1)
|
||||||
|
assert.equal(commands.filter((path) => path.includes('wm_command=909')).length, 1)
|
||||||
|
assert.equal(data.state, 0)
|
||||||
|
assert.equal(data.muted, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('modular action, first ten presets and load-result feedback agree on item numbers', async () => {
|
||||||
|
let sent
|
||||||
|
const definitions = actions(
|
||||||
|
() => {},
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
(item, target) => {
|
||||||
|
sent = { item, target }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
await definitions.load_playlist_item.callback({ options: { item: 12, target: 'backup' } })
|
||||||
|
assert.deepEqual(sent, { item: 12, target: 'backup' })
|
||||||
|
for (let item = 1; item <= 10; item++) {
|
||||||
|
const preset = presets()[`transport_load_item_${item}`]
|
||||||
|
assert.equal(preset.steps[0].down[0].options.item, item)
|
||||||
|
assert.equal(preset.feedbacks[0].options.item, item)
|
||||||
|
}
|
||||||
|
const fb = feedbacks(
|
||||||
|
() => null,
|
||||||
|
() => null,
|
||||||
|
(key) => (key === 'item_12' ? 'ready' : 'idle'),
|
||||||
|
() => ({ status: 'ready', direction: 'item_12' }),
|
||||||
|
)
|
||||||
|
assert.equal(fb.load_playlist_item_status.callback({ options: { item: 12 } }).text, '↓\nLOADED\n12')
|
||||||
|
assert.equal(fb.load_playlist_item_status.callback({ options: { item: 1 } }).text, '↓\nLOAD\n1')
|
||||||
|
assert.equal(fb.load_result.callback().text, 'LOADED\n#12')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('direct playlist play sends only selection, leaves mute alone, and does not record an experimental load', async (t) => {
|
||||||
|
for (const muted of [true, false]) {
|
||||||
|
const { player, data, commands } = await mock(t)
|
||||||
|
data.muted = muted
|
||||||
|
await player.playPlaylistItem(3)
|
||||||
|
assert.deepEqual(commands, ['/command.html?wm_command=-3&index=2'])
|
||||||
|
assert.equal(data.state, 2)
|
||||||
|
assert.equal(data.muted, muted)
|
||||||
|
assert.equal(player.loadResult.status, 'idle')
|
||||||
|
assert.equal(player.state.file, 'Clip 3.mp4')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('direct playlist play rejects missing items without a playback command', async (t) => {
|
||||||
|
const { player, commands } = await mock(t)
|
||||||
|
await player.playPlaylistItem(13)
|
||||||
|
assert.deepEqual(commands, [])
|
||||||
|
assert.match(player.error, /does not exist/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('direct playlist action and presets expose selection independently of experimental loads', async () => {
|
||||||
|
let sent
|
||||||
|
const definitions = actions(
|
||||||
|
() => {},
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
(item, target) => {
|
||||||
|
sent = { item, target }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
await definitions.play_playlist_item.callback({ options: { item: 7, target: 'main' } })
|
||||||
|
assert.deepEqual(sent, { item: 7, target: 'main' })
|
||||||
|
for (let item = 1; item <= 10; item++) {
|
||||||
|
const button = presets()[`playlist_play_item_${item}`]
|
||||||
|
assert.deepEqual(button.steps[0].down, [{ actionId: 'play_playlist_item', options: { item, target: 'both' } }])
|
||||||
|
assert.deepEqual(
|
||||||
|
button.feedbacks.map((f) => f.feedbackId),
|
||||||
|
['offline'],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,222 @@
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { createServer } from 'node:http'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import { InstanceStatus } from '@companion-module/base'
|
||||||
|
import MpcInstance from '../src/main.js'
|
||||||
|
import { normalizeStatus } from '../src/state.js'
|
||||||
|
import { comparePlayers } from '../src/redundancy.js'
|
||||||
|
import { colors, redundancyStyle } from '../src/feedbacks.js'
|
||||||
|
import { status as sample } from './fixture.js'
|
||||||
|
|
||||||
|
async function player(t) {
|
||||||
|
const mock = { data: { ...sample }, commands: [], statusCode: 200, commandCode: 200 }
|
||||||
|
const server = createServer((request, response) => {
|
||||||
|
if (request.url.startsWith('/command.html')) {
|
||||||
|
mock.commands.push(new URL(request.url, 'http://localhost').searchParams.get('wm_command'))
|
||||||
|
if (mock.holdCommands) {
|
||||||
|
mock.held = response
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response.writeHead(mock.commandCode)
|
||||||
|
} else response.writeHead(mock.statusCode)
|
||||||
|
response.end(JSON.stringify(mock.data))
|
||||||
|
})
|
||||||
|
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||||
|
t.after(() => {
|
||||||
|
server.closeAllConnections()
|
||||||
|
server.close()
|
||||||
|
})
|
||||||
|
mock.config = { host: '127.0.0.1', port: server.address().port }
|
||||||
|
return mock
|
||||||
|
}
|
||||||
|
|
||||||
|
async function moduleFor(t, main, backup, extra = {}) {
|
||||||
|
const seen = { statuses: [] }
|
||||||
|
const module = new MpcInstance({
|
||||||
|
_isInstanceContext: true,
|
||||||
|
id: 'test',
|
||||||
|
label: 'MPC_TEST',
|
||||||
|
setActionDefinitions: (value) => {
|
||||||
|
seen.actions = value
|
||||||
|
},
|
||||||
|
setFeedbackDefinitions: () => {},
|
||||||
|
setVariableDefinitions: () => {},
|
||||||
|
setPresetDefinitions: () => {},
|
||||||
|
setVariableValues: (value) => {
|
||||||
|
seen.variables = value
|
||||||
|
},
|
||||||
|
checkAllFeedbacks: () => {},
|
||||||
|
updateStatus: (status) => seen.statuses.push(status),
|
||||||
|
})
|
||||||
|
t.after(() => module.destroy())
|
||||||
|
const config = {
|
||||||
|
...main.config,
|
||||||
|
...(backup ? { backup_host: backup.config.host, backup_port: backup.config.port } : {}),
|
||||||
|
...extra,
|
||||||
|
}
|
||||||
|
await module.init(config)
|
||||||
|
await module.refresh()
|
||||||
|
return { module, seen, config }
|
||||||
|
}
|
||||||
|
|
||||||
|
const until = async (condition) => {
|
||||||
|
const end = Date.now() + 3000
|
||||||
|
while (!condition()) {
|
||||||
|
assert.ok(Date.now() < end, 'Expected player update did not arrive')
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test('optional unconfigured backup stays neutral and existing actions default to both', async (t) => {
|
||||||
|
const main = await player(t)
|
||||||
|
const { module, seen } = await moduleFor(t, main, null, { backup_host: ' ', backup_port: 0 })
|
||||||
|
await seen.actions['887'].callback({ options: {} })
|
||||||
|
assert.deepEqual(main.commands, ['887'])
|
||||||
|
assert.equal(module.backup, undefined)
|
||||||
|
assert.equal(seen.variables.sync_status, 'no_backup')
|
||||||
|
assert.equal(seen.variables.backup_status, 'not_configured')
|
||||||
|
assert.equal(seen.statuses.at(-1), InstanceStatus.Ok)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('main is authoritative and actions can target both, main, or backup', async (t) => {
|
||||||
|
const main = await player(t)
|
||||||
|
const backup = await player(t)
|
||||||
|
backup.data = { ...sample, state: 1, muted: true, position: 5000 }
|
||||||
|
const { module, seen } = await moduleFor(t, main, backup)
|
||||||
|
assert.equal(seen.variables.state, 'playing')
|
||||||
|
assert.equal(seen.variables.muted, false)
|
||||||
|
assert.equal(seen.variables.backup_state, 'paused')
|
||||||
|
assert.equal(seen.variables.backup_muted, true)
|
||||||
|
assert.equal(seen.variables.sync_status, 'out_of_sync')
|
||||||
|
await module.send('887')
|
||||||
|
await seen.actions['888'].callback({ options: { target: 'main' } })
|
||||||
|
await seen.actions['890'].callback({ options: { target: 'backup' } })
|
||||||
|
assert.deepEqual(main.commands, ['887', '888'])
|
||||||
|
assert.deepEqual(backup.commands, ['887', '890'])
|
||||||
|
assert.equal(seen.statuses.at(-1), InstanceStatus.Ok)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('main command failure does not suppress backup delivery or replace authoritative feedback', async (t) => {
|
||||||
|
const main = await player(t)
|
||||||
|
const backup = await player(t)
|
||||||
|
const { module, seen } = await moduleFor(t, main, backup)
|
||||||
|
main.commandCode = 503
|
||||||
|
await module.send('887')
|
||||||
|
assert.deepEqual(backup.commands, ['887'])
|
||||||
|
assert.equal(seen.variables.state, 'offline')
|
||||||
|
assert.equal(seen.variables.backup_state, 'playing')
|
||||||
|
assert.equal(seen.statuses.at(-1), InstanceStatus.ConnectionFailure)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('backup failure and empty media do not mark the connection as failed, and recovery resumes comparison', async (t) => {
|
||||||
|
const main = await player(t)
|
||||||
|
const backup = await player(t)
|
||||||
|
backup.statusCode = 503
|
||||||
|
const { module, seen } = await moduleFor(t, main, backup, { poll_interval: 250 })
|
||||||
|
assert.equal(seen.variables.sync_status, 'backup_offline')
|
||||||
|
assert.equal(seen.variables.backup_muted, null)
|
||||||
|
assert.equal(seen.statuses.at(-1), InstanceStatus.Ok)
|
||||||
|
backup.commandCode = 503
|
||||||
|
await module.send('909', 'backup')
|
||||||
|
assert.equal(seen.statuses.at(-1), InstanceStatus.Ok)
|
||||||
|
backup.statusCode = 200
|
||||||
|
backup.data = { ...sample, state: -1 }
|
||||||
|
await until(() => seen.variables.sync_status === 'backup_empty')
|
||||||
|
backup.data = { ...sample }
|
||||||
|
await until(() => seen.variables.sync_status === 'in_sync')
|
||||||
|
assert.equal(seen.statuses.at(-1), InstanceStatus.Ok)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('slow backup requests do not block main commands or status polling', async (t) => {
|
||||||
|
const main = await player(t)
|
||||||
|
const backup = await player(t)
|
||||||
|
const { module, seen } = await moduleFor(t, main, backup, { poll_interval: 250 })
|
||||||
|
backup.holdCommands = true
|
||||||
|
main.data = { ...sample, state: 1 }
|
||||||
|
const sending = module.send('888')
|
||||||
|
await until(() => backup.held && seen.variables.state === 'paused')
|
||||||
|
assert.deepEqual(main.commands, ['888'])
|
||||||
|
main.data = { ...sample, state: 0 }
|
||||||
|
await until(() => seen.variables.state === 'stopped')
|
||||||
|
backup.held.end('ok')
|
||||||
|
await sending
|
||||||
|
assert.equal(seen.statuses.at(-1), InstanceStatus.Ok)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('invalid or duplicate backup configuration leaves the main operational', async (t) => {
|
||||||
|
const main = await player(t)
|
||||||
|
for (const config of [
|
||||||
|
{ backup_host: 'localhost', backup_port: 0 },
|
||||||
|
{ backup_host: main.config.host, backup_port: main.config.port },
|
||||||
|
]) {
|
||||||
|
const { module, seen } = await moduleFor(t, main, null, config)
|
||||||
|
assert.equal(seen.variables.sync_status, 'backup_config')
|
||||||
|
assert.equal(seen.statuses.at(-1), InstanceStatus.Ok)
|
||||||
|
await module.send('887')
|
||||||
|
assert.equal(module.backup, undefined)
|
||||||
|
await module.destroy()
|
||||||
|
}
|
||||||
|
assert.deepEqual(main.commands, ['887', '887'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('reconfiguration cancels both old players and removes stale backup state', async (t) => {
|
||||||
|
const main = await player(t)
|
||||||
|
const backup = await player(t)
|
||||||
|
const { module, seen, config } = await moduleFor(t, main, backup)
|
||||||
|
const oldMain = module.main
|
||||||
|
const oldBackup = module.backup
|
||||||
|
backup.holdCommands = true
|
||||||
|
const pending = module.send('887', 'backup')
|
||||||
|
await until(() => backup.held)
|
||||||
|
await module.configUpdated({ ...config, backup_host: '' })
|
||||||
|
await pending
|
||||||
|
await module.refresh()
|
||||||
|
assert.equal(oldMain.active, false)
|
||||||
|
assert.equal(oldBackup.active, false)
|
||||||
|
assert.equal(seen.variables.sync_status, 'no_backup')
|
||||||
|
assert.equal(seen.variables.backup_file, '')
|
||||||
|
assert.equal(seen.variables.backup_remaining_seconds, null)
|
||||||
|
await module.destroy()
|
||||||
|
assert.equal(module.main, undefined)
|
||||||
|
assert.equal(module.backup, undefined)
|
||||||
|
})
|
||||||
|
|
||||||
|
const snapshot = (patch = {}, sampledAt = 10000) => ({ state: normalizeStatus({ ...sample, ...patch }), sampledAt })
|
||||||
|
const compare = (main, backup, options = {}) => comparePlayers(main, backup, { configured: true, ...options }, 10000)
|
||||||
|
|
||||||
|
test('comparison handles optional, offline, idle, and stale players without claiming synchronization', () => {
|
||||||
|
assert.equal(comparePlayers(null, null).status, 'no_backup')
|
||||||
|
assert.equal(compare(snapshot(), null).status, 'backup_offline')
|
||||||
|
assert.equal(compare(null, snapshot()).status, 'main_offline')
|
||||||
|
assert.equal(compare(snapshot(), snapshot({ state: -1 })).status, 'backup_empty')
|
||||||
|
assert.equal(compare(snapshot({ state: -1 }), snapshot()).status, 'main_empty')
|
||||||
|
assert.equal(compare(snapshot(), snapshot({ file: '' })).status, 'backup_empty')
|
||||||
|
assert.equal(compare(snapshot({}, 1000), snapshot()).status, 'checking')
|
||||||
|
for (const status of ['no_backup', 'backup_offline', 'backup_empty'])
|
||||||
|
assert.notEqual(redundancyStyle({ status }).bgcolor, colors.red)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('comparison accounts for sample time and rate, with configurable position tolerance', () => {
|
||||||
|
assert.equal(compare(snapshot({ position: 1000 }, 9000), snapshot({ position: 2000 })).status, 'in_sync')
|
||||||
|
assert.equal(compare(snapshot({ position: 1000, rate: 2 }, 9000), snapshot({ position: 3000, rate: 2 })).offset, 0)
|
||||||
|
assert.equal(compare(snapshot(), snapshot({ position: sample.position + 1001 })).status, 'out_of_sync')
|
||||||
|
assert.equal(
|
||||||
|
compare(snapshot(), snapshot({ position: sample.position + 1001 }), { tolerance: 1500 }).status,
|
||||||
|
'in_sync',
|
||||||
|
)
|
||||||
|
assert.equal(compare(snapshot(), snapshot({ position: sample.position - 2000 })).offset, -2000)
|
||||||
|
assert.equal(compare(snapshot({ state: 1 }, 9000), snapshot({ state: 1 })).offset, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('comparison checks media/state/rate; audio is optional and paths can differ', () => {
|
||||||
|
assert.equal(
|
||||||
|
compare(snapshot({ file: 'C:\\media\\Clip.mp4' }), snapshot({ file: 'D:\\backup\\clip.mp4' })).status,
|
||||||
|
'in_sync',
|
||||||
|
)
|
||||||
|
for (const patch of [{ file: 'other.mp4' }, { state: 1 }, { rate: 2 }, { duration: sample.duration + 2000 }]) {
|
||||||
|
assert.equal(compare(snapshot(), snapshot(patch)).status, 'out_of_sync')
|
||||||
|
}
|
||||||
|
assert.equal(compare(snapshot(), snapshot({ muted: true, volume: 0 })).status, 'in_sync')
|
||||||
|
assert.equal(compare(snapshot(), snapshot({ muted: true }), { compareAudio: true }).status, 'out_of_sync')
|
||||||
|
assert.equal(compare(snapshot(), snapshot({ volume: 0 }), { compareAudio: true }).status, 'out_of_sync')
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,186 @@
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import { normalizeStatus, parseVariables, variables, clock } from '../src/state.js'
|
||||||
|
import { feedbacks, progressBar, transportBorder, shortFilename } from '../src/feedbacks.js'
|
||||||
|
import { presets } from '../src/definitions.js'
|
||||||
|
import { status, htmlStatus } from './fixture.js'
|
||||||
|
|
||||||
|
test('playback feedback follows numeric player state, not localized strings or button presses', () => {
|
||||||
|
for (const [code, name] of [
|
||||||
|
[-1, 'idle'],
|
||||||
|
[0, 'stopped'],
|
||||||
|
[1, 'paused'],
|
||||||
|
[2, 'playing'],
|
||||||
|
]) {
|
||||||
|
const state = normalizeStatus({ ...status, state: code, stateString: 'Localized text' })
|
||||||
|
const definitions = feedbacks(() => state)
|
||||||
|
for (const id of ['playing', 'stopped', 'paused', 'idle']) assert.equal(definitions[id].callback(), id === name)
|
||||||
|
assert.equal(definitions.muted.callback(), false)
|
||||||
|
}
|
||||||
|
assert.equal(feedbacks(() => normalizeStatus({ ...status, volume: 0 })).muted.callback(), false)
|
||||||
|
assert.equal(feedbacks(() => normalizeStatus({ ...status, muted: true })).muted.callback(), true)
|
||||||
|
assert.equal(feedbacks(() => null).offline.callback(), true)
|
||||||
|
assert.equal(feedbacks(() => null).stopped.callback(), false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('timing uses milliseconds, clamps end/seek overshoot, and handles unknown duration', () => {
|
||||||
|
const state = normalizeStatus(status)
|
||||||
|
assert.equal(state.remaining, 47500)
|
||||||
|
assert.equal(variables(state).remaining, '00:48')
|
||||||
|
assert.equal(variables(state).elapsed, '00:12')
|
||||||
|
assert.equal(variables(state).progress, 20.8)
|
||||||
|
assert.equal(clock(3661000), '1:01:01')
|
||||||
|
assert.equal(clock(0), '00:00')
|
||||||
|
const ended = normalizeStatus({ ...status, position: 61000 })
|
||||||
|
assert.equal(ended.remaining, 0)
|
||||||
|
assert.equal(ended.progress, 100)
|
||||||
|
const unknown = normalizeStatus({ ...status, duration: 0 })
|
||||||
|
assert.equal(variables(unknown).remaining, '--:--')
|
||||||
|
assert.equal(unknown.progress, null)
|
||||||
|
assert.equal(variables(null).remaining_seconds, null)
|
||||||
|
assert.equal(variables(null).connected, false)
|
||||||
|
assert.equal(variables(null).muted, null)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('HTML parsing rejects incomplete/error pages and does not evaluate scripts', () => {
|
||||||
|
assert.deepEqual(parseVariables(htmlStatus()), normalizeStatus(status))
|
||||||
|
assert.throws(() => parseVariables('<html>Authentication required</html>'))
|
||||||
|
assert.throws(() => parseVariables(htmlStatus().replace('<p id="state">2</p>', '')))
|
||||||
|
assert.throws(() => normalizeStatus({ ...status, state: 42 }))
|
||||||
|
assert.throws(() => normalizeStatus({ ...status, duration: 'NaN' }))
|
||||||
|
})
|
||||||
|
|
||||||
|
test('transport presets use playlist commands and state feedback; time displays are passive', () => {
|
||||||
|
const buttons = presets('MY_PLAYER')
|
||||||
|
for (const [preset, command] of [
|
||||||
|
['play', '887'],
|
||||||
|
['stop', '890'],
|
||||||
|
['previous', '919'],
|
||||||
|
['next', '920'],
|
||||||
|
['mute', '909'],
|
||||||
|
]) {
|
||||||
|
assert.equal(buttons[`transport_${preset}`].steps[0].down[0].actionId, command)
|
||||||
|
assert.equal(buttons[`transport_${preset}`].feedbacks.at(-1).feedbackId, 'offline')
|
||||||
|
}
|
||||||
|
assert.equal(buttons.transport_play.feedbacks[0].feedbackId, 'playing')
|
||||||
|
assert.equal(buttons.transport_stop.feedbacks[0].feedbackId, 'stopped')
|
||||||
|
assert.equal(buttons.transport_mute.feedbacks[0].feedbackId, 'muted')
|
||||||
|
assert.equal(buttons.transport_remaining.style.text, 'LEFT\n$(MY_PLAYER:remaining)')
|
||||||
|
assert.deepEqual(buttons.transport_remaining.steps[0].down, [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('progress graphic fills the bottom proportionally and clears when state is unavailable', () => {
|
||||||
|
const bar = progressBar(normalizeStatus({ ...status, position: 30000 }), { width: 72, height: 72 })
|
||||||
|
const pixels = Buffer.from(bar.imageBuffer, 'base64')
|
||||||
|
assert.equal(pixels.length, 72 * 72 * 4)
|
||||||
|
assert.equal(pixels[3], 0)
|
||||||
|
assert.equal(pixels[71 * 72 * 4 + 3], 255)
|
||||||
|
assert.notDeepEqual(
|
||||||
|
pixels.subarray((71 * 72 + 35) * 4, (71 * 72 + 36) * 4),
|
||||||
|
pixels.subarray((71 * 72 + 36) * 4, (71 * 72 + 37) * 4),
|
||||||
|
)
|
||||||
|
assert.ok(
|
||||||
|
Buffer.from(progressBar(null, { width: 72, height: 72 }).imageBuffer, 'base64').every((value) => value === 0),
|
||||||
|
)
|
||||||
|
assert.deepEqual(progressBar(null, undefined), {})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('transport outlines leave the center clear, thicken when active, and turn grey offline', () => {
|
||||||
|
const image = { width: 72, height: 72 }
|
||||||
|
const render = (state, control) => Buffer.from(transportBorder(state, image, control).imageBuffer, 'base64')
|
||||||
|
const waiting = render({ state: 'stopped' }, 'play')
|
||||||
|
const playing = render({ state: 'playing' }, 'play')
|
||||||
|
const pixel = (buffer, x, y) => [...buffer.subarray((y * 72 + x) * 4, (y * 72 + x + 1) * 4)]
|
||||||
|
assert.equal(pixel(waiting, 0, 36)[3], 255)
|
||||||
|
assert.equal(pixel(waiting, 1, 36)[3], 0)
|
||||||
|
assert.equal(pixel(playing, 2, 36)[3], 255)
|
||||||
|
assert.equal(pixel(playing, 3, 36)[3], 0)
|
||||||
|
assert.equal(pixel(playing, 36, 36)[3], 0)
|
||||||
|
assert.deepEqual(pixel(render(null, 'play'), 0, 0), [89, 99, 109, 255])
|
||||||
|
assert.deepEqual(pixel(render({ muted: true }, 'mute'), 0, 0), [186, 41, 54, 255])
|
||||||
|
assert.deepEqual(transportBorder(null, undefined, 'play'), {})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('split timers share rounded time across boundaries, preserve long hours, and clear unavailable values', () => {
|
||||||
|
const parts = (values, mode) => ['hh', 'mm', 'ss'].map((part) => values[`${mode}_${part}`])
|
||||||
|
for (const [milliseconds, expected] of [
|
||||||
|
[0, ['00', '00', '00']],
|
||||||
|
[1, ['00', '00', '01']],
|
||||||
|
[59999, ['00', '01', '00']],
|
||||||
|
[3599999, ['01', '00', '00']],
|
||||||
|
[3600001, ['01', '00', '01']],
|
||||||
|
[90061000, ['25', '01', '01']],
|
||||||
|
]) {
|
||||||
|
const data = normalizeStatus({ ...status, duration: milliseconds || 1, position: milliseconds ? 0 : 1 })
|
||||||
|
assert.deepEqual(parts(variables(data), 'remaining'), expected)
|
||||||
|
}
|
||||||
|
assert.deepEqual(parts(variables(normalizeStatus({ ...status, position: 3599999, duration: 4000000 })), 'elapsed'), [
|
||||||
|
'00',
|
||||||
|
'59',
|
||||||
|
'59',
|
||||||
|
])
|
||||||
|
assert.deepEqual(parts(variables(null), 'remaining'), ['--', '--', '--'])
|
||||||
|
assert.deepEqual(parts(variables(normalizeStatus({ ...status, state: -1 })), 'elapsed'), ['--', '--', '--'])
|
||||||
|
const unknown = variables(normalizeStatus({ ...status, duration: 0 }))
|
||||||
|
assert.deepEqual(parts(unknown, 'remaining'), ['--', '--', '--'])
|
||||||
|
assert.deepEqual(parts(unknown, 'elapsed'), ['00', '00', '12'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('split timer presets are passive and countdown urgency follows remaining time', () => {
|
||||||
|
const buttons = presets('CLOCK')
|
||||||
|
for (const mode of ['remaining', 'elapsed'])
|
||||||
|
for (const part of ['hh', 'mm', 'ss']) {
|
||||||
|
const button = buttons[`timer_${mode}_${part}`]
|
||||||
|
assert.equal(button.style.text, `$(CLOCK:${mode}_${part})`)
|
||||||
|
assert.deepEqual(button.steps[0].down, [])
|
||||||
|
}
|
||||||
|
for (const [remaining, color] of [
|
||||||
|
[30001, 0xffffff],
|
||||||
|
[30000, 0xe09b20],
|
||||||
|
[10001, 0xe09b20],
|
||||||
|
[10000, 0xba2936],
|
||||||
|
[0, 0xba2936],
|
||||||
|
]) {
|
||||||
|
const defs = feedbacks(() => ({ state: 'playing', remaining }))
|
||||||
|
assert.equal(defs.split_timer_color.callback({ options: { mode: 'remaining' } }).color, color)
|
||||||
|
assert.equal(defs.split_timer_color.callback({ options: { mode: 'elapsed' } }).color, 0xffffff)
|
||||||
|
}
|
||||||
|
assert.equal(feedbacks(() => null).split_timer_color.callback({ options: { mode: 'remaining' } }).color, 0x889099)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('loaded filename preview uses the basename, wraps and truncates without splitting Unicode characters', () => {
|
||||||
|
assert.equal(shortFilename('C:\\Videos\\Opening film.mp4'), 'Opening \nfilm')
|
||||||
|
assert.equal(shortFilename('/media/12345678901234567890.mp4'), '12345678\n9012345…')
|
||||||
|
assert.equal(shortFilename('é👨👩👧👦.mp4'), 'é👨👩👧👦')
|
||||||
|
assert.equal(shortFilename(''), '')
|
||||||
|
const fb = feedbacks(
|
||||||
|
() => null,
|
||||||
|
() => null,
|
||||||
|
() => 'idle',
|
||||||
|
() => ({ status: 'ready', file: '/media/Intro.mp4', direction: 'item_1' }),
|
||||||
|
)
|
||||||
|
assert.equal(fb.load_result.callback().text, 'LOADED\nIntro')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('layered directional load feedback follows each direction and clears after its result expires', () => {
|
||||||
|
let current = 'loading'
|
||||||
|
const definitions = feedbacks(
|
||||||
|
() => null,
|
||||||
|
() => null,
|
||||||
|
(direction) => (direction === 'next' ? current : 'idle'),
|
||||||
|
)
|
||||||
|
const catalog = presets()
|
||||||
|
for (const state of ['loading', 'ready', 'failed', 'idle']) {
|
||||||
|
current = state
|
||||||
|
for (const direction of ['next', 'previous']) {
|
||||||
|
const preset = catalog[`transport_load_${direction}`]
|
||||||
|
assert.equal(preset.type, 'layered')
|
||||||
|
for (const feedback of preset.feedbacks.filter((item) => item.feedbackId === 'load_direction_state')) {
|
||||||
|
assert.equal(
|
||||||
|
definitions.load_direction_state.callback(feedback),
|
||||||
|
direction === 'next' && feedback.options.state === state,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,33 @@
|
||||||
|
[package]
|
||||||
|
name = "ascii-names"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
description = "Sequential ASCII filename cleanup for removable drives"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["desktop"]
|
||||||
|
desktop = ["dep:eframe", "dep:rfd"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
clap = { version = "4", features = ["derive"] }
|
||||||
|
unicode-normalization = "0.1"
|
||||||
|
eframe = { version = "0.31", optional = true, default-features = false, features = ["default_fonts", "glow", "x11", "wayland"] }
|
||||||
|
rfd = { version = "0.15", optional = true }
|
||||||
|
|
||||||
|
[target.'cfg(any(target_os = "linux", target_vendor = "apple"))'.dependencies]
|
||||||
|
rustix = { version = "1", features = ["fs"] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
libc = "0.2.191"
|
||||||
|
tempfile = "3"
|
||||||
|
|
||||||
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] }
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "freebsd")'.dependencies]
|
||||||
|
libc = "0.2.191"
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
winresource = "0.1.17"
|
||||||
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 364 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
|
@ -0,0 +1,9 @@
|
||||||
|
fn main() {
|
||||||
|
println!("cargo:rerun-if-changed=assets/app-icon.ico");
|
||||||
|
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
||||||
|
winresource::WindowsResource::new()
|
||||||
|
.set_icon("assets/app-icon.ico")
|
||||||
|
.compile()
|
||||||
|
.expect("Could not embed the Windows application icon");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,113 @@
|
||||||
|
//! Resolve the newer FreeBSD API at runtime so older jails can still start/preview.
|
||||||
|
use std::{ffi::CString, io, os::unix::ffi::OsStrExt, path::Path, sync::OnceLock};
|
||||||
|
|
||||||
|
type RenameAt2 = unsafe extern "C" fn(
|
||||||
|
libc::c_int,
|
||||||
|
*const libc::c_char,
|
||||||
|
libc::c_int,
|
||||||
|
*const libc::c_char,
|
||||||
|
libc::c_uint,
|
||||||
|
) -> libc::c_int;
|
||||||
|
|
||||||
|
fn unsupported(detail: impl std::fmt::Display) -> io::Error {
|
||||||
|
io::Error::new(
|
||||||
|
io::ErrorKind::Unsupported,
|
||||||
|
format!(
|
||||||
|
"FreeBSD no-overwrite rename unavailable ({detail}); use a host, jail userland and filesystem supporting renameat2 with AT_RENAME_NOREPLACE, or run cleanup on Linux/macOS/Windows"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> {
|
||||||
|
static RENAME: OnceLock<Option<RenameAt2>> = OnceLock::new();
|
||||||
|
let rename = RENAME.get_or_init(|| {
|
||||||
|
// SAFETY: static NUL-terminated symbol name; RTLD_DEFAULT searches loaded libraries.
|
||||||
|
let symbol = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"renameat2".as_ptr()) };
|
||||||
|
if symbol.is_null() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
// SAFETY: the FreeBSD renameat2 ABI has precisely the signature above.
|
||||||
|
Some(unsafe { std::mem::transmute::<*mut libc::c_void, RenameAt2>(symbol) })
|
||||||
|
}
|
||||||
|
});
|
||||||
|
rename_with(*rename, from, to)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rename_with(rename: Option<RenameAt2>, from: &Path, to: &Path) -> io::Result<()> {
|
||||||
|
let rename = rename.ok_or_else(|| unsupported("renameat2 is missing from the jail's libc"))?;
|
||||||
|
let from = CString::new(from.as_os_str().as_bytes())?;
|
||||||
|
let to = CString::new(to.as_os_str().as_bytes())?;
|
||||||
|
// SAFETY: both paths remain valid NUL-terminated strings throughout the call.
|
||||||
|
let status = unsafe {
|
||||||
|
rename(
|
||||||
|
libc::AT_FDCWD,
|
||||||
|
from.as_ptr(),
|
||||||
|
libc::AT_FDCWD,
|
||||||
|
to.as_ptr(),
|
||||||
|
libc::RENAME_NOREPLACE,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if status == 0 {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let error = io::Error::last_os_error();
|
||||||
|
if matches!(error.raw_os_error(), Some(libc::ENOSYS | libc::EOPNOTSUPP)) {
|
||||||
|
Err(unsupported(error))
|
||||||
|
} else {
|
||||||
|
Err(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_api_preserves_files_and_directories() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let from = tmp.path().join("source");
|
||||||
|
let to = tmp.path().join("target");
|
||||||
|
fs::write(&from, "source bytes").unwrap();
|
||||||
|
fs::write(&to, "existing bytes").unwrap();
|
||||||
|
let error = rename_with(None, &from, &to).unwrap_err();
|
||||||
|
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
|
||||||
|
assert!(error.to_string().contains("renameat2 is missing"));
|
||||||
|
assert_eq!(fs::read_to_string(&from).unwrap(), "source bytes");
|
||||||
|
assert_eq!(fs::read_to_string(&to).unwrap(), "existing bytes");
|
||||||
|
fs::remove_file(&to).unwrap();
|
||||||
|
assert!(rename_with(None, &from, &to).is_err());
|
||||||
|
assert!(!to.exists());
|
||||||
|
fs::remove_file(&from).unwrap();
|
||||||
|
fs::create_dir(&from).unwrap();
|
||||||
|
assert!(rename_with(None, &from, &to).is_err());
|
||||||
|
assert!(from.is_dir());
|
||||||
|
assert!(!to.exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Linux exposes the same function signature and no-replace flag, allowing
|
||||||
|
// this dynamic-lookup adapter to be exercised without a FreeBSD runtime.
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
#[test]
|
||||||
|
fn dynamic_api_moves_and_refuses_collisions() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let from = tmp.path().join("source");
|
||||||
|
let to = tmp.path().join("target");
|
||||||
|
fs::write(&from, "source bytes").unwrap();
|
||||||
|
fs::write(&to, "existing bytes").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
rename_no_replace(&from, &to).unwrap_err().kind(),
|
||||||
|
io::ErrorKind::AlreadyExists
|
||||||
|
);
|
||||||
|
assert_eq!(fs::read_to_string(&to).unwrap(), "existing bytes");
|
||||||
|
fs::remove_file(&to).unwrap();
|
||||||
|
rename_no_replace(&from, &to).unwrap();
|
||||||
|
assert_eq!(fs::read_to_string(&to).unwrap(), "source bytes");
|
||||||
|
assert!(!from.exists());
|
||||||
|
fs::remove_file(&to).unwrap();
|
||||||
|
fs::create_dir(&from).unwrap();
|
||||||
|
rename_no_replace(&from, &to).unwrap();
|
||||||
|
assert!(to.is_dir());
|
||||||
|
assert!(!from.exists());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,152 @@
|
||||||
|
//! Small drag-and-drop interface, with one background worker and bounded progress storage.
|
||||||
|
use crate::{Options, Summary, clean};
|
||||||
|
use eframe::egui;
|
||||||
|
use std::{
|
||||||
|
collections::VecDeque,
|
||||||
|
path::PathBuf,
|
||||||
|
sync::{
|
||||||
|
Arc, Mutex,
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
|
},
|
||||||
|
thread::{self, JoinHandle},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Progress {
|
||||||
|
summary: Summary,
|
||||||
|
messages: VecDeque<String>,
|
||||||
|
}
|
||||||
|
impl Progress {
|
||||||
|
fn push(&mut self, message: String) {
|
||||||
|
if self.messages.len() == 200 {
|
||||||
|
self.messages.pop_front();
|
||||||
|
}
|
||||||
|
self.messages.push_back(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Default)]
|
||||||
|
struct App {
|
||||||
|
folder: Option<PathBuf>,
|
||||||
|
progress: Arc<Mutex<Progress>>,
|
||||||
|
cancel: Arc<AtomicBool>,
|
||||||
|
worker: Option<JoinHandle<()>>,
|
||||||
|
}
|
||||||
|
impl App {
|
||||||
|
fn start(&mut self, dry_run: bool) {
|
||||||
|
let Some(folder) = self.folder.clone() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
self.cancel.store(false, Ordering::Relaxed);
|
||||||
|
*self.progress.lock().unwrap() = Progress::default();
|
||||||
|
let progress = self.progress.clone();
|
||||||
|
let cancel = self.cancel.clone();
|
||||||
|
self.worker = Some(thread::spawn(move || {
|
||||||
|
let result = clean(
|
||||||
|
&folder,
|
||||||
|
Options {
|
||||||
|
dry_run,
|
||||||
|
..Options::default()
|
||||||
|
},
|
||||||
|
&cancel,
|
||||||
|
|summary, message| {
|
||||||
|
let mut p = progress.lock().unwrap();
|
||||||
|
p.summary = summary.clone();
|
||||||
|
p.push(message);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let mut p = progress.lock().unwrap();
|
||||||
|
match result {
|
||||||
|
Ok(summary) => {
|
||||||
|
p.push(format!(
|
||||||
|
"{}: {summary}",
|
||||||
|
if dry_run {
|
||||||
|
"Preview complete"
|
||||||
|
} else {
|
||||||
|
"Cleanup complete"
|
||||||
|
}
|
||||||
|
));
|
||||||
|
p.summary = summary;
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
p.summary.errors += 1;
|
||||||
|
p.push(format!("Cannot clean {}: {error}", folder.display()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for App {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.cancel.store(true, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl eframe::App for App {
|
||||||
|
fn update(&mut self, ctx: &egui::Context, _: &mut eframe::Frame) {
|
||||||
|
if self.worker.as_ref().is_some_and(|w| w.is_finished())
|
||||||
|
&& self.worker.take().unwrap().join().is_err()
|
||||||
|
{
|
||||||
|
let mut p = self.progress.lock().unwrap();
|
||||||
|
p.summary.errors += 1;
|
||||||
|
p.push("Worker stopped unexpectedly; completed renames remain in place.".into());
|
||||||
|
}
|
||||||
|
let busy = self.worker.is_some();
|
||||||
|
if !busy {
|
||||||
|
let dropped = ctx.input(|i| i.raw.dropped_files.clone());
|
||||||
|
if let Some(file) = dropped.first() {
|
||||||
|
self.folder = file.path.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
egui::CentralPanel::default().show(ctx, |ui| {
|
||||||
|
ui.heading("ASCII names");
|
||||||
|
ui.label("Drop a folder here, then clean its file and subfolder names.");
|
||||||
|
ui.label("Accents become letters; unknown characters become underscores.");
|
||||||
|
ui.small("Contents stay intact. The selected folder keeps its name. Links are skipped.");
|
||||||
|
ui.small("Renaming can break playlists, shortcuts and project references. Keep the folder idle.");
|
||||||
|
ui.add_space(12.0);
|
||||||
|
ui.add_enabled_ui(!busy, |ui| {
|
||||||
|
if ui.button("Choose folder…").clicked()
|
||||||
|
&& let Some(folder) = rfd::FileDialog::new().pick_folder() { self.folder = Some(folder); }
|
||||||
|
ui.label(self.folder.as_ref().map_or_else(|| "No folder selected".into(), |p| p.display().to_string()));
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.add_enabled_ui(self.folder.is_some(), |ui| {
|
||||||
|
if ui.button("Preview").clicked() { self.start(true); }
|
||||||
|
if ui.button("Clean names").clicked() { self.start(false); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if busy {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.spinner(); ui.label("Working sequentially · 25 ms between renames");
|
||||||
|
if ui.button("Stop").clicked() { self.cancel.store(true, Ordering::Relaxed); }
|
||||||
|
});
|
||||||
|
ctx.request_repaint_after(Duration::from_millis(100));
|
||||||
|
}
|
||||||
|
ui.separator();
|
||||||
|
let p = self.progress.lock().unwrap();
|
||||||
|
ui.label(p.summary.to_string());
|
||||||
|
ui.small("Most recent 200 messages");
|
||||||
|
egui::ScrollArea::vertical().stick_to_bottom(true).show(ui, |ui| {
|
||||||
|
for message in &p.messages { ui.label(message); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn launch() -> eframe::Result {
|
||||||
|
eframe::run_native(
|
||||||
|
"ASCII names",
|
||||||
|
eframe::NativeOptions {
|
||||||
|
viewport: egui::ViewportBuilder::default()
|
||||||
|
.with_app_id("ascii-names")
|
||||||
|
.with_icon(
|
||||||
|
eframe::icon_data::from_png_bytes(include_bytes!("../assets/app-icon.png"))
|
||||||
|
.expect("embedded application icon must be a valid PNG"),
|
||||||
|
)
|
||||||
|
.with_inner_size([760.0, 480.0])
|
||||||
|
.with_drag_and_drop(true),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
Box::new(|_| Ok(Box::<App>::default())),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,401 @@
|
||||||
|
//! Sequential, paced filename cleanup. File contents are never opened.
|
||||||
|
use std::{
|
||||||
|
collections::{HashMap, HashSet},
|
||||||
|
fs, io,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
sync::atomic::{AtomicBool, Ordering},
|
||||||
|
thread,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
use unicode_normalization::{UnicodeNormalization, char::is_combining_mark};
|
||||||
|
|
||||||
|
#[cfg(feature = "desktop")]
|
||||||
|
pub mod gui;
|
||||||
|
|
||||||
|
#[cfg(any(target_os = "freebsd", all(test, target_os = "linux")))]
|
||||||
|
mod freebsd;
|
||||||
|
|
||||||
|
/// ASCII equivalents for accented Latin text and common punctuation; unknowns become `_`.
|
||||||
|
/// Also removes names that are unsafe on common removable-drive filesystems.
|
||||||
|
pub fn ascii_name(name: &str) -> String {
|
||||||
|
let mut result = String::new();
|
||||||
|
for c in name.nfkd().filter(|c| !is_combining_mark(*c)) {
|
||||||
|
let replacement = match c {
|
||||||
|
'ß' | 'ẞ' => "ss",
|
||||||
|
'æ' => "ae",
|
||||||
|
'Æ' => "AE",
|
||||||
|
'œ' => "oe",
|
||||||
|
'Œ' => "OE",
|
||||||
|
'ø' => "o",
|
||||||
|
'Ø' => "O",
|
||||||
|
'ł' => "l",
|
||||||
|
'Ł' => "L",
|
||||||
|
'đ' | 'ð' => "d",
|
||||||
|
'Đ' | 'Ð' => "D",
|
||||||
|
'þ' => "th",
|
||||||
|
'Þ' => "Th",
|
||||||
|
'‘' | '’' | '‚' | '‛' => "'",
|
||||||
|
'“' | '”' | '„' | '‟' => "'",
|
||||||
|
'–' | '—' | '−' => "-",
|
||||||
|
'…' => "...",
|
||||||
|
c if c.is_ascii() && !c.is_ascii_control() && !"<>:\"/\\|?*".contains(c) => {
|
||||||
|
result.push(c);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
_ => "_",
|
||||||
|
};
|
||||||
|
result.push_str(replacement);
|
||||||
|
}
|
||||||
|
result = result.trim_end_matches([' ', '.']).to_owned();
|
||||||
|
if result.is_empty() {
|
||||||
|
result.push('_');
|
||||||
|
}
|
||||||
|
let base = result
|
||||||
|
.split('.')
|
||||||
|
.next()
|
||||||
|
.unwrap_or("")
|
||||||
|
.trim_end()
|
||||||
|
.to_ascii_uppercase();
|
||||||
|
if matches!(base.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|
||||||
|
|| (base.len() == 4
|
||||||
|
&& (base.starts_with("COM") || base.starts_with("LPT"))
|
||||||
|
&& matches!(base.as_bytes()[3], b'1'..=b'9'))
|
||||||
|
{
|
||||||
|
result.insert(0, '_');
|
||||||
|
}
|
||||||
|
// Leave room for collision suffixes and stay below common 255-byte limits.
|
||||||
|
shorten(&result, 220)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shorten(name: &str, limit: usize) -> String {
|
||||||
|
if name.len() <= limit {
|
||||||
|
return name.to_owned();
|
||||||
|
}
|
||||||
|
if let Some((stem, ext)) = name.rsplit_once('.')
|
||||||
|
&& !stem.is_empty()
|
||||||
|
&& ext.len() < 32
|
||||||
|
{
|
||||||
|
return format!("{}.{}", &stem[..limit - ext.len() - 1], ext);
|
||||||
|
}
|
||||||
|
name[..limit].to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct Options {
|
||||||
|
pub dry_run: bool,
|
||||||
|
pub delay: Duration,
|
||||||
|
}
|
||||||
|
impl Default for Options {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
dry_run: false,
|
||||||
|
delay: Duration::from_millis(25),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default)]
|
||||||
|
pub struct Summary {
|
||||||
|
pub visited: usize,
|
||||||
|
pub renamed: usize,
|
||||||
|
pub skipped: usize,
|
||||||
|
pub errors: usize,
|
||||||
|
pub cancelled: bool,
|
||||||
|
}
|
||||||
|
impl std::fmt::Display for Summary {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"{} visited; {} renames; {} skipped; {} errors{}",
|
||||||
|
self.visited,
|
||||||
|
self.renamed,
|
||||||
|
self.skipped,
|
||||||
|
self.errors,
|
||||||
|
if self.cancelled { "; stopped" } else { "" }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clean the contents of a folder, keeping the selected root itself unchanged.
|
||||||
|
/// Symlinks and special files are skipped. No parallel I/O; stop between entries.
|
||||||
|
/// Keep the tree idle during cleanup (renaming can break links and application references).
|
||||||
|
pub fn clean(
|
||||||
|
root: &Path,
|
||||||
|
options: Options,
|
||||||
|
cancel: &AtomicBool,
|
||||||
|
mut report: impl FnMut(&Summary, String),
|
||||||
|
) -> io::Result<Summary> {
|
||||||
|
if !fs::symlink_metadata(root)?.file_type().is_dir() {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
"Drop a real folder, not a file or symlink",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut summary = Summary::default();
|
||||||
|
let mut targets = Targets::default();
|
||||||
|
// Explicit stack avoids call-stack overflow in deeply nested trees.
|
||||||
|
enum Work {
|
||||||
|
Visit(PathBuf),
|
||||||
|
Rename(PathBuf, bool),
|
||||||
|
}
|
||||||
|
let mut stack = vec![Work::Visit(root.to_owned())];
|
||||||
|
while let Some(work) = stack.pop() {
|
||||||
|
if cancel.load(Ordering::Relaxed) {
|
||||||
|
summary.cancelled = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
match work {
|
||||||
|
Work::Visit(dir) => {
|
||||||
|
let entries = match fs::read_dir(&dir)
|
||||||
|
.and_then(|entries| entries.collect::<io::Result<Vec<_>>>())
|
||||||
|
{
|
||||||
|
Ok(mut entries) => {
|
||||||
|
entries.sort_by_key(|e| e.file_name());
|
||||||
|
entries
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
summary.errors += 1;
|
||||||
|
report(&summary, format!("Cannot read {}: {e}", dir.display()));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for entry in entries.into_iter().rev() {
|
||||||
|
let path = entry.path();
|
||||||
|
match entry.file_type() {
|
||||||
|
Ok(kind) if kind.is_dir() => {
|
||||||
|
stack.push(Work::Rename(path.clone(), true));
|
||||||
|
stack.push(Work::Visit(path));
|
||||||
|
}
|
||||||
|
Ok(kind) if kind.is_file() => stack.push(Work::Rename(path, false)),
|
||||||
|
Ok(_) => {
|
||||||
|
summary.skipped += 1;
|
||||||
|
report(
|
||||||
|
&summary,
|
||||||
|
format!("Skipped link/special file: {}", path.display()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
summary.errors += 1;
|
||||||
|
report(&summary, format!("Cannot inspect {}: {e}", path.display()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Work::Rename(path, is_dir) => {
|
||||||
|
summary.visited += 1;
|
||||||
|
if let Err(e) = rename_one(
|
||||||
|
&path,
|
||||||
|
is_dir,
|
||||||
|
options,
|
||||||
|
&mut targets,
|
||||||
|
&mut summary,
|
||||||
|
&mut report,
|
||||||
|
) {
|
||||||
|
summary.errors += 1;
|
||||||
|
report(&summary, format!("Cannot rename {}: {e}", path.display()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(summary)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Targets {
|
||||||
|
reserved: HashSet<PathBuf>,
|
||||||
|
next_suffix: HashMap<PathBuf, u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rename_one(
|
||||||
|
path: &Path,
|
||||||
|
is_dir: bool,
|
||||||
|
options: Options,
|
||||||
|
targets: &mut Targets,
|
||||||
|
summary: &mut Summary,
|
||||||
|
report: &mut impl FnMut(&Summary, String),
|
||||||
|
) -> io::Result<()> {
|
||||||
|
let original = path.file_name().unwrap();
|
||||||
|
let name = ascii_name(&original.to_string_lossy());
|
||||||
|
if original == name.as_str() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let parent = path.parent().unwrap();
|
||||||
|
let base_key = parent.join(name.to_ascii_lowercase());
|
||||||
|
let mut number = targets.next_suffix.get(&base_key).copied().unwrap_or(0);
|
||||||
|
loop {
|
||||||
|
let candidate = if number == 0 {
|
||||||
|
name.clone()
|
||||||
|
} else {
|
||||||
|
let p = Path::new(&name);
|
||||||
|
match (p.file_stem(), p.extension()) {
|
||||||
|
(Some(stem), Some(ext)) if !is_dir => format!(
|
||||||
|
"{}_{number}.{}",
|
||||||
|
stem.to_string_lossy(),
|
||||||
|
ext.to_string_lossy()
|
||||||
|
),
|
||||||
|
_ => format!("{name}_{number}"),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let target = parent.join(candidate);
|
||||||
|
// Case-fold reservations also protect previews on case-insensitive media.
|
||||||
|
let key = parent.join(
|
||||||
|
target
|
||||||
|
.file_name()
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.to_ascii_lowercase(),
|
||||||
|
);
|
||||||
|
// Avoid repeated metadata probes when many names normalize to the same base.
|
||||||
|
if targets.reserved.contains(&key) {
|
||||||
|
number += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let occupied = match fs::symlink_metadata(&target) {
|
||||||
|
Ok(_) => true,
|
||||||
|
Err(e) if e.kind() == io::ErrorKind::NotFound => false,
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
};
|
||||||
|
if occupied {
|
||||||
|
number += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !options.dry_run {
|
||||||
|
// Pace attempts as well as successful renames.
|
||||||
|
thread::sleep(options.delay);
|
||||||
|
match rename_no_replace(path, &target) {
|
||||||
|
Ok(()) => (),
|
||||||
|
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
|
||||||
|
number += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
targets.reserved.insert(key);
|
||||||
|
targets.next_suffix.insert(base_key, number + 1);
|
||||||
|
summary.renamed += 1;
|
||||||
|
report(
|
||||||
|
summary,
|
||||||
|
format!(
|
||||||
|
"{}{} -> {}",
|
||||||
|
if options.dry_run { "Preview: " } else { "" },
|
||||||
|
path.display(),
|
||||||
|
target.display()
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> {
|
||||||
|
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
|
||||||
|
{
|
||||||
|
rustix::fs::renameat_with(
|
||||||
|
rustix::fs::CWD,
|
||||||
|
from,
|
||||||
|
rustix::fs::CWD,
|
||||||
|
to,
|
||||||
|
rustix::fs::RenameFlags::NOREPLACE,
|
||||||
|
)
|
||||||
|
.map_err(Into::into)
|
||||||
|
}
|
||||||
|
#[cfg(target_os = "freebsd")]
|
||||||
|
{
|
||||||
|
freebsd::rename_no_replace(from, to)
|
||||||
|
}
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
use std::os::windows::ffi::OsStrExt;
|
||||||
|
let from: Vec<u16> = from.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||||
|
let to: Vec<u16> = to.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||||
|
// No MOVEFILE_REPLACE_EXISTING: an existing destination must survive.
|
||||||
|
let ok = unsafe {
|
||||||
|
windows_sys::Win32::Storage::FileSystem::MoveFileExW(from.as_ptr(), to.as_ptr(), 0)
|
||||||
|
};
|
||||||
|
if ok == 0 {
|
||||||
|
Err(io::Error::last_os_error())
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(not(any(
|
||||||
|
target_os = "linux",
|
||||||
|
target_vendor = "apple",
|
||||||
|
target_os = "windows",
|
||||||
|
target_os = "freebsd"
|
||||||
|
)))]
|
||||||
|
{
|
||||||
|
let _ = (from, to);
|
||||||
|
Err(io::Error::new(
|
||||||
|
io::ErrorKind::Unsupported,
|
||||||
|
"Safe no-overwrite rename is unavailable on this platform",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn atomic_rename_refuses_existing_files_and_directories() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let source = tmp.path().join("source");
|
||||||
|
let dest = tmp.path().join("dest");
|
||||||
|
fs::write(&source, "new").unwrap();
|
||||||
|
fs::write(&dest, "original").unwrap();
|
||||||
|
#[cfg(target_os = "freebsd")]
|
||||||
|
{
|
||||||
|
// SAFETY: static C symbol name and the default loaded-library handle.
|
||||||
|
let symbol = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"renameat2".as_ptr()) };
|
||||||
|
if symbol.is_null() {
|
||||||
|
let error = rename_no_replace(&source, &dest).unwrap_err();
|
||||||
|
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
|
||||||
|
assert_eq!(fs::read_to_string(&source).unwrap(), "new");
|
||||||
|
assert_eq!(fs::read_to_string(&dest).unwrap(), "original");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let error = rename_no_replace(&source, &dest).unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
error.kind(),
|
||||||
|
io::ErrorKind::AlreadyExists,
|
||||||
|
"Expected a destination collision in {}, got: {error}",
|
||||||
|
tmp.path().display()
|
||||||
|
);
|
||||||
|
assert_eq!(fs::read_to_string(&dest).unwrap(), "original");
|
||||||
|
assert_eq!(fs::read_to_string(&source).unwrap(), "new");
|
||||||
|
fs::remove_file(&source).unwrap();
|
||||||
|
fs::remove_file(&dest).unwrap();
|
||||||
|
fs::create_dir(&source).unwrap();
|
||||||
|
fs::create_dir(&dest).unwrap();
|
||||||
|
let error = rename_no_replace(&source, &dest).unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
error.kind(),
|
||||||
|
io::ErrorKind::AlreadyExists,
|
||||||
|
"Expected a destination collision in {}, got: {error}",
|
||||||
|
tmp.path().display()
|
||||||
|
);
|
||||||
|
assert!(source.is_dir());
|
||||||
|
assert!(dest.is_dir());
|
||||||
|
let fresh = tmp.path().join("fresh");
|
||||||
|
rename_no_replace(&source, &fresh).unwrap_or_else(|error| {
|
||||||
|
panic!(
|
||||||
|
"No-replace directory rename failed in {}: {error}",
|
||||||
|
tmp.path().display()
|
||||||
|
)
|
||||||
|
});
|
||||||
|
assert!(fresh.is_dir());
|
||||||
|
assert!(!source.exists());
|
||||||
|
fs::write(&source, "new").unwrap();
|
||||||
|
let fresh_file = tmp.path().join("fresh-file");
|
||||||
|
rename_no_replace(&source, &fresh_file).unwrap_or_else(|error| {
|
||||||
|
panic!(
|
||||||
|
"No-replace file rename failed in {}: {error}",
|
||||||
|
tmp.path().display()
|
||||||
|
)
|
||||||
|
});
|
||||||
|
assert_eq!(fs::read_to_string(fresh_file).unwrap(), "new");
|
||||||
|
assert!(!source.exists());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,52 @@
|
||||||
|
use clap::Parser;
|
||||||
|
use std::{path::PathBuf, sync::atomic::AtomicBool, time::Duration};
|
||||||
|
|
||||||
|
#[derive(Parser)]
|
||||||
|
#[command(
|
||||||
|
version,
|
||||||
|
about = "Clean filenames recursively for ASCII-only computers. Run without arguments for drag and drop."
|
||||||
|
)]
|
||||||
|
struct Args {
|
||||||
|
/// Folder whose contents will be renamed in place (root itself stays unchanged).
|
||||||
|
folder: Option<PathBuf>,
|
||||||
|
/// Show proposed renames without changing anything.
|
||||||
|
#[arg(long, requires = "folder")]
|
||||||
|
dry_run: bool,
|
||||||
|
/// Pause between renames, in milliseconds (one worker only).
|
||||||
|
#[arg(long, default_value_t = 25, requires = "folder", value_parser = clap::value_parser!(u64).range(0..=1000))]
|
||||||
|
delay_ms: u64,
|
||||||
|
}
|
||||||
|
fn main() {
|
||||||
|
let args = Args::parse();
|
||||||
|
if let Some(folder) = args.folder {
|
||||||
|
let options = ascii_names::Options {
|
||||||
|
dry_run: args.dry_run,
|
||||||
|
delay: Duration::from_millis(args.delay_ms),
|
||||||
|
};
|
||||||
|
match ascii_names::clean(&folder, options, &AtomicBool::new(false), |_, message| {
|
||||||
|
println!("{message}")
|
||||||
|
}) {
|
||||||
|
Ok(summary) => {
|
||||||
|
println!("{summary}");
|
||||||
|
if summary.errors > 0 {
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
eprintln!("{}: {error}", folder.display());
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
#[cfg(feature = "desktop")]
|
||||||
|
if let Err(error) = ascii_names::gui::launch() {
|
||||||
|
eprintln!("Cannot open window: {error}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "desktop"))]
|
||||||
|
{
|
||||||
|
eprintln!("Supply a folder, or build with the default desktop feature.");
|
||||||
|
std::process::exit(2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,370 @@
|
||||||
|
use ascii_names::{Options, ascii_name, clean};
|
||||||
|
use std::{
|
||||||
|
fs,
|
||||||
|
sync::atomic::AtomicBool,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
|
fn options() -> Options {
|
||||||
|
Options {
|
||||||
|
delay: Duration::ZERO,
|
||||||
|
dry_run: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Older FreeBSD jails have no atomic no-replace API. Exercise their documented
|
||||||
|
// refusal rather than expecting successful renames or accepting other OS errors.
|
||||||
|
fn rename_test_dir() -> Option<tempfile::TempDir> {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
#[cfg(target_os = "freebsd")]
|
||||||
|
{
|
||||||
|
// SAFETY: a static C string and the default loaded-library search handle.
|
||||||
|
let symbol = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"renameat2".as_ptr()) };
|
||||||
|
if symbol.is_null() {
|
||||||
|
let file = tmp.path().join("été.txt");
|
||||||
|
let directory = tmp.path().join("été");
|
||||||
|
fs::write(&file, "unchanged").unwrap();
|
||||||
|
fs::create_dir(&directory).unwrap();
|
||||||
|
let mut messages = Vec::new();
|
||||||
|
let summary = clean(
|
||||||
|
tmp.path(),
|
||||||
|
options(),
|
||||||
|
&AtomicBool::new(false),
|
||||||
|
|_, message| messages.push(message),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(summary.errors, 2, "{messages:?}");
|
||||||
|
assert_eq!(summary.renamed, 0);
|
||||||
|
assert_eq!(fs::read_to_string(file).unwrap(), "unchanged");
|
||||||
|
assert!(directory.is_dir());
|
||||||
|
assert!(!tmp.path().join("ete.txt").exists());
|
||||||
|
assert!(!tmp.path().join("ete").exists());
|
||||||
|
assert!(
|
||||||
|
messages
|
||||||
|
.iter()
|
||||||
|
.all(|m| m.contains("renameat2 is missing from the jail's libc")),
|
||||||
|
"{messages:?}"
|
||||||
|
);
|
||||||
|
let output = std::process::Command::new(env!("CARGO_BIN_EXE_ascii-names"))
|
||||||
|
.arg(tmp.path())
|
||||||
|
.args(["--delay-ms", "0"])
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(!output.status.success());
|
||||||
|
assert!(
|
||||||
|
String::from_utf8_lossy(&output.stdout)
|
||||||
|
.contains("renameat2 is missing from the jail's libc")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_to_string(tmp.path().join("été.txt")).unwrap(),
|
||||||
|
"unchanged"
|
||||||
|
);
|
||||||
|
assert!(tmp.path().join("été").is_dir());
|
||||||
|
// Direct stderr keeps this platform limitation visible in successful CI output.
|
||||||
|
use std::io::Write;
|
||||||
|
let _ = writeln!(
|
||||||
|
std::io::stderr(),
|
||||||
|
"FreeBSD libc lacks renameat2: verified safe refusal; successful-rename assertions require a supported host."
|
||||||
|
);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(tmp)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn accents_punctuation_unknowns_and_portable_names() {
|
||||||
|
for (input, expected) in [
|
||||||
|
("Été à Noël.mov", "Ete a Noel.mov"),
|
||||||
|
("Cafe\u{301}.txt", "Cafe.txt"),
|
||||||
|
(
|
||||||
|
"œuf Straße Łódź Æsir Øresund",
|
||||||
|
"oeuf Strasse Lodz AEsir Oresund",
|
||||||
|
),
|
||||||
|
("‘Hello’—world…", "'Hello'-world"),
|
||||||
|
("日本🎬.txt", "___.txt"),
|
||||||
|
("a\nb:<>\"\\|?*c", "a_b________c"),
|
||||||
|
("\u{301}", "_"),
|
||||||
|
("..", "_"),
|
||||||
|
("foo. ", "foo"),
|
||||||
|
("CON.txt", "_CON.txt"),
|
||||||
|
("LPT9", "_LPT9"),
|
||||||
|
("COM0", "COM0"),
|
||||||
|
("ordinary file-01.txt", "ordinary file-01.txt"),
|
||||||
|
] {
|
||||||
|
assert_eq!(ascii_name(input), expected, "{input:?}");
|
||||||
|
}
|
||||||
|
let name = ascii_name(&format!("{}.txt", "ffi".repeat(100)));
|
||||||
|
assert_eq!(name.len(), 220);
|
||||||
|
assert!(name.ends_with(".txt"));
|
||||||
|
assert!(name.is_ascii());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nested_cleanup_preserves_all_contents_and_is_idempotent() {
|
||||||
|
let Some(tmp) = rename_test_dir() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let root = tmp.path().join("Sélection");
|
||||||
|
fs::create_dir_all(root.join("Étage/été")).unwrap();
|
||||||
|
fs::write(root.join("Étage/été/vidéo.mov"), b"video bytes").unwrap();
|
||||||
|
fs::write(root.join("resume.txt"), b"original").unwrap();
|
||||||
|
fs::write(root.join("résumé.txt"), b"accented").unwrap();
|
||||||
|
fs::write(root.join("résume.txt"), b"another").unwrap();
|
||||||
|
let cancel = AtomicBool::new(false);
|
||||||
|
let summary = clean(&root, options(), &cancel, |_, message| {
|
||||||
|
eprintln!("{message}")
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(summary.errors, 0);
|
||||||
|
assert_eq!(summary.renamed, 5);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read(root.join("Etage/ete/video.mov")).unwrap(),
|
||||||
|
b"video bytes"
|
||||||
|
);
|
||||||
|
assert_eq!(fs::read(root.join("resume.txt")).unwrap(), b"original");
|
||||||
|
let mut contents = [
|
||||||
|
fs::read(root.join("resume_1.txt")).unwrap(),
|
||||||
|
fs::read(root.join("resume_2.txt")).unwrap(),
|
||||||
|
];
|
||||||
|
contents.sort();
|
||||||
|
assert_eq!(contents, [b"accented".to_vec(), b"another".to_vec()]);
|
||||||
|
assert_eq!(
|
||||||
|
clean(&root, options(), &cancel, |_, message| eprintln!(
|
||||||
|
"{message}"
|
||||||
|
))
|
||||||
|
.unwrap()
|
||||||
|
.renamed,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn preview_reserves_targets_and_changes_nothing() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
fs::write(tmp.path().join("é.txt"), "a").unwrap();
|
||||||
|
fs::write(tmp.path().join("è.txt"), "b").unwrap();
|
||||||
|
let mut logs = vec![];
|
||||||
|
let summary = clean(
|
||||||
|
tmp.path(),
|
||||||
|
Options {
|
||||||
|
dry_run: true,
|
||||||
|
..options()
|
||||||
|
},
|
||||||
|
&AtomicBool::new(false),
|
||||||
|
|_, msg| logs.push(msg),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(summary.renamed, 2);
|
||||||
|
assert!(logs[0].ends_with("e.txt"));
|
||||||
|
assert!(logs[1].ends_with("e_1.txt"));
|
||||||
|
assert!(tmp.path().join("é.txt").exists());
|
||||||
|
assert!(tmp.path().join("è.txt").exists());
|
||||||
|
assert!(!tmp.path().join("e.txt").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn directory_and_file_collisions_never_merge() {
|
||||||
|
let Some(tmp) = rename_test_dir() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
fs::create_dir(tmp.path().join("Ete")).unwrap();
|
||||||
|
fs::create_dir(tmp.path().join("Été")).unwrap();
|
||||||
|
fs::write(tmp.path().join("Ete/original"), "keep").unwrap();
|
||||||
|
fs::write(tmp.path().join("Été/new"), "new").unwrap();
|
||||||
|
fs::write(tmp.path().join("été"), "file").unwrap();
|
||||||
|
let result = clean(
|
||||||
|
tmp.path(),
|
||||||
|
options(),
|
||||||
|
&AtomicBool::new(false),
|
||||||
|
|_, message| eprintln!("{message}"),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(result.errors, 0);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_to_string(tmp.path().join("Ete/original")).unwrap(),
|
||||||
|
"keep"
|
||||||
|
);
|
||||||
|
assert!(tmp.path().join("Ete_1/new").is_file());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cancellation_stops_between_renames_and_delay_is_applied() {
|
||||||
|
let Some(tmp) = rename_test_dir() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
fs::write(tmp.path().join("é"), "a").unwrap();
|
||||||
|
fs::write(tmp.path().join("à"), "b").unwrap();
|
||||||
|
let cancel = AtomicBool::new(false);
|
||||||
|
let start = Instant::now();
|
||||||
|
let result = clean(
|
||||||
|
tmp.path(),
|
||||||
|
Options {
|
||||||
|
delay: Duration::from_millis(30),
|
||||||
|
dry_run: false,
|
||||||
|
},
|
||||||
|
&cancel,
|
||||||
|
|_, message| {
|
||||||
|
eprintln!("{message}");
|
||||||
|
cancel.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(result.cancelled);
|
||||||
|
assert_eq!(result.renamed, 1);
|
||||||
|
assert!(start.elapsed() >= Duration::from_millis(30));
|
||||||
|
assert!(
|
||||||
|
clean(tmp.path(), options(), &cancel, |_, message| eprintln!(
|
||||||
|
"{message}"
|
||||||
|
))
|
||||||
|
.unwrap()
|
||||||
|
.cancelled
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_root_and_file_root_are_errors() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let file = tmp.path().join("file");
|
||||||
|
let cancel = AtomicBool::new(false);
|
||||||
|
assert!(
|
||||||
|
clean(&file, options(), &cancel, |_, message| eprintln!(
|
||||||
|
"{message}"
|
||||||
|
))
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
fs::write(&file, "x").unwrap();
|
||||||
|
assert!(
|
||||||
|
clean(&file, options(), &cancel, |_, message| eprintln!(
|
||||||
|
"{message}"
|
||||||
|
))
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn links_are_not_followed_and_invalid_utf8_is_cleaned() {
|
||||||
|
use std::{
|
||||||
|
ffi::OsString,
|
||||||
|
os::unix::{ffi::OsStringExt, fs::symlink},
|
||||||
|
};
|
||||||
|
let Some(tmp) = rename_test_dir() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let outside = tempfile::tempdir().unwrap();
|
||||||
|
fs::write(outside.path().join("é.txt"), "outside").unwrap();
|
||||||
|
symlink(outside.path(), tmp.path().join("lïnk")).unwrap();
|
||||||
|
symlink("missing", tmp.path().join("e.txt")).unwrap();
|
||||||
|
fs::write(tmp.path().join("é.txt"), "inside").unwrap();
|
||||||
|
fs::write(
|
||||||
|
tmp.path().join(OsString::from_vec(b"bad\xff.txt".to_vec())),
|
||||||
|
"bytes",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let result = clean(
|
||||||
|
tmp.path(),
|
||||||
|
options(),
|
||||||
|
&AtomicBool::new(false),
|
||||||
|
|_, message| eprintln!("{message}"),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(result.skipped, 2);
|
||||||
|
assert_eq!(result.errors, 0);
|
||||||
|
assert!(outside.path().join("é.txt").exists());
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_to_string(tmp.path().join("bad_.txt")).unwrap(),
|
||||||
|
"bytes"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_to_string(tmp.path().join("e_1.txt")).unwrap(),
|
||||||
|
"inside"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
clean(
|
||||||
|
&tmp.path().join("lïnk"),
|
||||||
|
options(),
|
||||||
|
&AtomicBool::new(false),
|
||||||
|
|_, message| eprintln!("{message}")
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cli_preview_and_apply() {
|
||||||
|
let Some(tmp) = rename_test_dir() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
fs::write(tmp.path().join("été.txt"), "content").unwrap();
|
||||||
|
let bin = env!("CARGO_BIN_EXE_ascii-names");
|
||||||
|
let output = std::process::Command::new(bin)
|
||||||
|
.arg(tmp.path())
|
||||||
|
.arg("--dry-run")
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
output.status.success(),
|
||||||
|
"status: {}; stdout: {}; stderr: {}",
|
||||||
|
output.status,
|
||||||
|
String::from_utf8_lossy(&output.stdout),
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
);
|
||||||
|
assert!(tmp.path().join("été.txt").exists());
|
||||||
|
let output = std::process::Command::new(bin)
|
||||||
|
.arg(tmp.path())
|
||||||
|
.args(["--delay-ms", "0"])
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
output.status.success(),
|
||||||
|
"status: {}; stdout: {}; stderr: {}",
|
||||||
|
output.status,
|
||||||
|
String::from_utf8_lossy(&output.stdout),
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_to_string(tmp.path().join("ete.txt")).unwrap(),
|
||||||
|
"content"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!std::process::Command::new(bin)
|
||||||
|
.arg(tmp.path().join("missing"))
|
||||||
|
.output()
|
||||||
|
.unwrap()
|
||||||
|
.status
|
||||||
|
.success()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn many_names_with_same_fallback_keep_every_file() {
|
||||||
|
let Some(tmp) = rename_test_dir() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for (index, character) in (0x4e00..0x4e80).filter_map(char::from_u32).enumerate() {
|
||||||
|
fs::write(
|
||||||
|
tmp.path().join(format!("{character}.txt")),
|
||||||
|
index.to_string(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let summary = clean(
|
||||||
|
tmp.path(),
|
||||||
|
options(),
|
||||||
|
&AtomicBool::new(false),
|
||||||
|
|_, message| eprintln!("{message}"),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(summary.renamed, 128);
|
||||||
|
assert_eq!(summary.errors, 0);
|
||||||
|
let values: std::collections::HashSet<_> = fs::read_dir(tmp.path())
|
||||||
|
.unwrap()
|
||||||
|
.map(|entry| {
|
||||||
|
let path = entry.unwrap().path();
|
||||||
|
assert!(path.file_name().unwrap().to_str().unwrap().is_ascii());
|
||||||
|
fs::read_to_string(path).unwrap()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert_eq!(values.len(), 128);
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 364 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
|
@ -1,10 +1,8 @@
|
||||||
fn main() {
|
fn main() {
|
||||||
println!("cargo:rerun-if-changed=assets/rust-report.ico");
|
println!("cargo:rerun-if-changed=assets/app-icon.ico");
|
||||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
|
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
||||||
&& std::env::var_os("CARGO_FEATURE_DESKTOP").is_some()
|
|
||||||
{
|
|
||||||
winresource::WindowsResource::new()
|
winresource::WindowsResource::new()
|
||||||
.set_icon("assets/rust-report.ico")
|
.set_icon("assets/app-icon.ico")
|
||||||
.compile()
|
.compile()
|
||||||
.expect("Could not embed the Windows application icon");
|
.expect("Could not embed the Windows application icon");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -639,9 +639,10 @@ fn configure_style(ctx: &egui::Context) {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn launch() -> anyhow::Result<()> {
|
pub fn launch() -> anyhow::Result<()> {
|
||||||
let icon = eframe::icon_data::from_png_bytes(include_bytes!("../assets/rust-report-icon.png"))?;
|
let icon = eframe::icon_data::from_png_bytes(include_bytes!("../assets/app-icon.png"))?;
|
||||||
let options = eframe::NativeOptions {
|
let options = eframe::NativeOptions {
|
||||||
viewport: egui::ViewportBuilder::default()
|
viewport: egui::ViewportBuilder::default()
|
||||||
|
.with_app_id("pptx-reporter")
|
||||||
.with_icon(icon)
|
.with_icon(icon)
|
||||||
.with_inner_size([760.0, 560.0])
|
.with_inner_size([760.0, 560.0])
|
||||||
.with_min_inner_size([560.0, 420.0])
|
.with_min_inner_size([560.0, 420.0])
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,44 @@
|
||||||
|
[package]
|
||||||
|
name = "rundown-converter"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
description = "Local spreadsheet rundown inference, review and Ontime export"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["desktop"]
|
||||||
|
desktop = ["dep:eframe", "dep:rfd", "dep:open"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1"
|
||||||
|
directories = "6"
|
||||||
|
clap = { version = "4", features = ["derive"] }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||||
|
roxmltree = "0.20"
|
||||||
|
csv = "1.4"
|
||||||
|
unicode-normalization = "0.1"
|
||||||
|
tempfile = "3"
|
||||||
|
uuid = { version = "1", features = ["v5"] }
|
||||||
|
eframe = { version = "0.31", optional = true, default-features = false, features = ["default_fonts", "glow", "x11", "wayland"] }
|
||||||
|
rfd = { version = "0.15", optional = true }
|
||||||
|
open = { version = "5", optional = true }
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
winresource = "0.1.17"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "rundown-converter"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "rundown-converter-gui"
|
||||||
|
path = "src/bin/gui.rs"
|
||||||
|
required-features = ["desktop"]
|
||||||
|
|
||||||
|
[package.metadata.binstall]
|
||||||
|
pkg-url = "{ repo }/releases/download/v{ version }/{ name }-{ target }-v{ version }.tgz"
|
||||||
|
pkg-fmt = "tgz"
|
||||||
|
bin-dir = "{ name }-{ target }-v{ version }/{ bin }{ binary-ext }"
|
||||||
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 364 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
|
@ -0,0 +1,187 @@
|
||||||
|
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
|
||||||
|
Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
|
||||||
|
|
||||||
|
|
||||||
|
Bitstream Vera Fonts Copyright
|
||||||
|
------------------------------
|
||||||
|
|
||||||
|
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
|
||||||
|
a trademark of Bitstream, Inc.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of the fonts accompanying this license ("Fonts") and associated
|
||||||
|
documentation files (the "Font Software"), to reproduce and distribute the
|
||||||
|
Font Software, including without limitation the rights to use, copy, merge,
|
||||||
|
publish, distribute, and/or sell copies of the Font Software, and to permit
|
||||||
|
persons to whom the Font Software is furnished to do so, subject to the
|
||||||
|
following conditions:
|
||||||
|
|
||||||
|
The above copyright and trademark notices and this permission notice shall
|
||||||
|
be included in all copies of one or more of the Font Software typefaces.
|
||||||
|
|
||||||
|
The Font Software may be modified, altered, or added to, and in particular
|
||||||
|
the designs of glyphs or characters in the Fonts may be modified and
|
||||||
|
additional glyphs or characters may be added to the Fonts, only if the fonts
|
||||||
|
are renamed to names not containing either the words "Bitstream" or the word
|
||||||
|
"Vera".
|
||||||
|
|
||||||
|
This License becomes null and void to the extent applicable to Fonts or Font
|
||||||
|
Software that has been modified and is distributed under the "Bitstream
|
||||||
|
Vera" names.
|
||||||
|
|
||||||
|
The Font Software may be sold as part of a larger software package but no
|
||||||
|
copy of one or more of the Font Software typefaces may be sold by itself.
|
||||||
|
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||||
|
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
|
||||||
|
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
|
||||||
|
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
|
||||||
|
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
|
||||||
|
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
|
||||||
|
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
|
||||||
|
FONT SOFTWARE.
|
||||||
|
|
||||||
|
Except as contained in this notice, the names of Gnome, the Gnome
|
||||||
|
Foundation, and Bitstream Inc., shall not be used in advertising or
|
||||||
|
otherwise to promote the sale, use or other dealings in this Font Software
|
||||||
|
without prior written authorization from the Gnome Foundation or Bitstream
|
||||||
|
Inc., respectively. For further information, contact: fonts at gnome dot
|
||||||
|
org.
|
||||||
|
|
||||||
|
Arev Fonts Copyright
|
||||||
|
------------------------------
|
||||||
|
|
||||||
|
Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the fonts accompanying this license ("Fonts") and
|
||||||
|
associated documentation files (the "Font Software"), to reproduce
|
||||||
|
and distribute the modifications to the Bitstream Vera Font Software,
|
||||||
|
including without limitation the rights to use, copy, merge, publish,
|
||||||
|
distribute, and/or sell copies of the Font Software, and to permit
|
||||||
|
persons to whom the Font Software is furnished to do so, subject to
|
||||||
|
the following conditions:
|
||||||
|
|
||||||
|
The above copyright and trademark notices and this permission notice
|
||||||
|
shall be included in all copies of one or more of the Font Software
|
||||||
|
typefaces.
|
||||||
|
|
||||||
|
The Font Software may be modified, altered, or added to, and in
|
||||||
|
particular the designs of glyphs or characters in the Fonts may be
|
||||||
|
modified and additional glyphs or characters may be added to the
|
||||||
|
Fonts, only if the fonts are renamed to names not containing either
|
||||||
|
the words "Tavmjong Bah" or the word "Arev".
|
||||||
|
|
||||||
|
This License becomes null and void to the extent applicable to Fonts
|
||||||
|
or Font Software that has been modified and is distributed under the
|
||||||
|
"Tavmjong Bah Arev" names.
|
||||||
|
|
||||||
|
The Font Software may be sold as part of a larger software package but
|
||||||
|
no copy of one or more of the Font Software typefaces may be sold by
|
||||||
|
itself.
|
||||||
|
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
|
||||||
|
TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
|
|
||||||
|
Except as contained in this notice, the name of Tavmjong Bah shall not
|
||||||
|
be used in advertising or otherwise to promote the sale, use or other
|
||||||
|
dealings in this Font Software without prior written authorization
|
||||||
|
from Tavmjong Bah. For further information, contact: tavmjong @ free
|
||||||
|
. fr.
|
||||||
|
|
||||||
|
TeX Gyre DJV Math
|
||||||
|
-----------------
|
||||||
|
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
|
||||||
|
|
||||||
|
Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
|
||||||
|
(on behalf of TeX users groups) are in public domain.
|
||||||
|
|
||||||
|
Letters imported from Euler Fraktur from AMSfonts are (c) American
|
||||||
|
Mathematical Society (see below).
|
||||||
|
Bitstream Vera Fonts Copyright
|
||||||
|
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
|
||||||
|
is a trademark of Bitstream, Inc.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of the fonts accompanying this license (“Fonts”) and associated
|
||||||
|
documentation
|
||||||
|
files (the “Font Software”), to reproduce and distribute the Font Software,
|
||||||
|
including without limitation the rights to use, copy, merge, publish,
|
||||||
|
distribute,
|
||||||
|
and/or sell copies of the Font Software, and to permit persons to whom
|
||||||
|
the Font Software is furnished to do so, subject to the following
|
||||||
|
conditions:
|
||||||
|
|
||||||
|
The above copyright and trademark notices and this permission notice
|
||||||
|
shall be
|
||||||
|
included in all copies of one or more of the Font Software typefaces.
|
||||||
|
|
||||||
|
The Font Software may be modified, altered, or added to, and in particular
|
||||||
|
the designs of glyphs or characters in the Fonts may be modified and
|
||||||
|
additional
|
||||||
|
glyphs or characters may be added to the Fonts, only if the fonts are
|
||||||
|
renamed
|
||||||
|
to names not containing either the words “Bitstream” or the word “Vera”.
|
||||||
|
|
||||||
|
This License becomes null and void to the extent applicable to Fonts or
|
||||||
|
Font Software
|
||||||
|
that has been modified and is distributed under the “Bitstream Vera”
|
||||||
|
names.
|
||||||
|
|
||||||
|
The Font Software may be sold as part of a larger software package but
|
||||||
|
no copy
|
||||||
|
of one or more of the Font Software typefaces may be sold by itself.
|
||||||
|
|
||||||
|
THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||||
|
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
|
||||||
|
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
|
||||||
|
FOUNDATION
|
||||||
|
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL,
|
||||||
|
SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN
|
||||||
|
ACTION
|
||||||
|
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR
|
||||||
|
INABILITY TO USE
|
||||||
|
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
|
Except as contained in this notice, the names of GNOME, the GNOME
|
||||||
|
Foundation,
|
||||||
|
and Bitstream Inc., shall not be used in advertising or otherwise to promote
|
||||||
|
the sale, use or other dealings in this Font Software without prior written
|
||||||
|
authorization from the GNOME Foundation or Bitstream Inc., respectively.
|
||||||
|
For further information, contact: fonts at gnome dot org.
|
||||||
|
|
||||||
|
AMSFonts (v. 2.2) copyright
|
||||||
|
|
||||||
|
The PostScript Type 1 implementation of the AMSFonts produced by and
|
||||||
|
previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
|
||||||
|
available for general use. This has been accomplished through the
|
||||||
|
cooperation
|
||||||
|
of a consortium of scientific publishers with Blue Sky Research and Y&Y.
|
||||||
|
Members of this consortium include:
|
||||||
|
|
||||||
|
Elsevier Science IBM Corporation Society for Industrial and Applied
|
||||||
|
Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
|
||||||
|
|
||||||
|
In order to assure the authenticity of these fonts, copyright will be
|
||||||
|
held by
|
||||||
|
the American Mathematical Society. This is not meant to restrict in any way
|
||||||
|
the legitimate use of the fonts, such as (but not limited to) electronic
|
||||||
|
distribution of documents containing these fonts, inclusion of these fonts
|
||||||
|
into other public domain or commercial font collections or computer
|
||||||
|
applications, use of the outline data to create derivative fonts and/or
|
||||||
|
faces, etc. However, the AMS does require that the AMS copyright notice be
|
||||||
|
removed from any derivative versions of the fonts which have been altered in
|
||||||
|
any way. In addition, to ensure the fidelity of TeX documents using Computer
|
||||||
|
Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
|
||||||
|
has requested that any alterations which yield different font metrics be
|
||||||
|
given a different name.
|
||||||
|
|
||||||
|
$Id$
|
||||||
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 364 KiB |
|
After Width: | Height: | Size: 1.6 MiB |
|
|
@ -0,0 +1,9 @@
|
||||||
|
fn main() {
|
||||||
|
println!("cargo:rerun-if-changed=assets/app-icon.ico");
|
||||||
|
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
||||||
|
winresource::WindowsResource::new()
|
||||||
|
.set_icon("assets/app-icon.ico")
|
||||||
|
.compile()
|
||||||
|
.expect("Could not embed the Windows application icon");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,10 @@
|
||||||
|
#![cfg_attr(target_os = "windows", windows_subsystem = "windows")]
|
||||||
|
fn main() {
|
||||||
|
if let Err(error) = rundown_converter::gui::launch() {
|
||||||
|
rfd::MessageDialog::new()
|
||||||
|
.set_title("Rundown converter")
|
||||||
|
.set_description(error.to_string())
|
||||||
|
.set_level(rfd::MessageLevel::Error)
|
||||||
|
.show();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,819 @@
|
||||||
|
use crate::{
|
||||||
|
model::*,
|
||||||
|
time::{clock, clock_range, duration, normalize, select_duration_parts},
|
||||||
|
};
|
||||||
|
|
||||||
|
fn role(header: &str) -> Option<&'static str> {
|
||||||
|
let h = normalize(header);
|
||||||
|
let h = h.trim();
|
||||||
|
if [
|
||||||
|
"start-end",
|
||||||
|
"start / end",
|
||||||
|
"start to end",
|
||||||
|
"debut-fin",
|
||||||
|
"debut / fin",
|
||||||
|
"debut a fin",
|
||||||
|
"horaire debut-fin",
|
||||||
|
]
|
||||||
|
.contains(&h)
|
||||||
|
{
|
||||||
|
Some("start_end")
|
||||||
|
} else if h.contains("duration") || h.contains("duree") || h == "timer" {
|
||||||
|
Some("duration")
|
||||||
|
} else if ["end", "end time", "fin", "heure fin", "heure de fin"].contains(&h) {
|
||||||
|
Some("end")
|
||||||
|
} else if [
|
||||||
|
"start",
|
||||||
|
"start time",
|
||||||
|
"time",
|
||||||
|
"heure",
|
||||||
|
"debut",
|
||||||
|
"heure debut",
|
||||||
|
"heure de debut",
|
||||||
|
"clock",
|
||||||
|
"horaire",
|
||||||
|
"horaires",
|
||||||
|
]
|
||||||
|
.contains(&h)
|
||||||
|
{
|
||||||
|
Some("start")
|
||||||
|
} else if [
|
||||||
|
"title",
|
||||||
|
"titre",
|
||||||
|
"event",
|
||||||
|
"segment",
|
||||||
|
"segment / cue",
|
||||||
|
"deroulement",
|
||||||
|
"contenu / detail",
|
||||||
|
"action",
|
||||||
|
"activity",
|
||||||
|
"activite",
|
||||||
|
"description",
|
||||||
|
]
|
||||||
|
.contains(&h)
|
||||||
|
{
|
||||||
|
Some("title")
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn role_label(role: &str) -> &str {
|
||||||
|
if role == "secondary_title" {
|
||||||
|
"secondary title"
|
||||||
|
} else if role == "start_end" {
|
||||||
|
"start–end"
|
||||||
|
} else {
|
||||||
|
role
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn loc(table: &Table, row: usize, col: usize) -> String {
|
||||||
|
format!("{}!{}{}", table.name, column_name(col), row + 1)
|
||||||
|
}
|
||||||
|
fn err(code: &str, table: &Table, row: usize, col: usize, msg: impl Into<String>) -> Diagnostic {
|
||||||
|
Diagnostic::new(1, code, loc(table, row, col), msg)
|
||||||
|
}
|
||||||
|
fn placeholder(s: &str) -> bool {
|
||||||
|
matches!(s.trim(), "" | "-" | "—")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn automatic_usage(header: &str) -> &'static str {
|
||||||
|
let normalized = normalize(header);
|
||||||
|
let words: Vec<_> = normalized
|
||||||
|
.split(|c: char| !c.is_alphanumeric())
|
||||||
|
.filter(|word| !word.is_empty())
|
||||||
|
.collect();
|
||||||
|
if words.iter().any(|word| {
|
||||||
|
matches!(
|
||||||
|
*word,
|
||||||
|
"note"
|
||||||
|
| "notes"
|
||||||
|
| "comment"
|
||||||
|
| "comments"
|
||||||
|
| "remark"
|
||||||
|
| "remarks"
|
||||||
|
| "remarque"
|
||||||
|
| "remarques"
|
||||||
|
| "instruction"
|
||||||
|
| "instructions"
|
||||||
|
| "consigne"
|
||||||
|
| "consignes"
|
||||||
|
| "observation"
|
||||||
|
| "observations"
|
||||||
|
)
|
||||||
|
}) {
|
||||||
|
"notes"
|
||||||
|
} else if words.iter().any(|word| {
|
||||||
|
matches!(
|
||||||
|
*word,
|
||||||
|
"video"
|
||||||
|
| "light"
|
||||||
|
| "lights"
|
||||||
|
| "lighting"
|
||||||
|
| "lumiere"
|
||||||
|
| "eclairage"
|
||||||
|
| "son"
|
||||||
|
| "sound"
|
||||||
|
| "audio"
|
||||||
|
| "sonorisation"
|
||||||
|
| "powerpoint"
|
||||||
|
| "ppt"
|
||||||
|
| "slide"
|
||||||
|
| "slides"
|
||||||
|
| "projection"
|
||||||
|
| "media"
|
||||||
|
| "camera"
|
||||||
|
| "cameras"
|
||||||
|
| "microphone"
|
||||||
|
| "microphones"
|
||||||
|
)
|
||||||
|
}) || normalized.contains("power point")
|
||||||
|
{
|
||||||
|
"metadata"
|
||||||
|
} else {
|
||||||
|
"ignore"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Only an isolated, full-width merged text band is automatically structural.
|
||||||
|
pub fn structural_row(table: &Table, row: usize, header: usize) -> bool {
|
||||||
|
let width = table.rows[header]
|
||||||
|
.iter()
|
||||||
|
.rposition(|c| !c.text.is_empty())
|
||||||
|
.map_or(0, |c| c + 1);
|
||||||
|
let populated: Vec<_> = table.rows[row]
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, c)| !placeholder(&c.text))
|
||||||
|
.collect();
|
||||||
|
populated.len() == 1
|
||||||
|
&& clock_range(populated[0].1).is_none()
|
||||||
|
&& table.merges.iter().any(|m| {
|
||||||
|
m.first_row == row
|
||||||
|
&& m.first_col == populated[0].0
|
||||||
|
&& m.first_col == 0
|
||||||
|
&& m.last_col + 1 >= width
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/// Ignored columns cannot make an otherwise empty row require clarification.
|
||||||
|
pub fn has_content(table: &Table, row: usize, profile: &Profile) -> bool {
|
||||||
|
table.rows[row]
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.any(|(col, cell)| profile.usage(col) != Some("ignore") && !placeholder(&cell.text))
|
||||||
|
}
|
||||||
|
pub fn active_rows(table: &Table, header: usize, profile: &Profile) -> Vec<usize> {
|
||||||
|
(header + 1..table.rows.len())
|
||||||
|
.filter(|r| {
|
||||||
|
if profile
|
||||||
|
.row_kinds
|
||||||
|
.get(&(r + 1))
|
||||||
|
.is_some_and(|k| matches!(k.as_str(), "ignore" | "note" | "marker"))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if structural_row(table, *r, header) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// A repeated header must actually repeat the header cells, not merely contain a keyword.
|
||||||
|
let header_cells = &table.rows[header];
|
||||||
|
let repeated = header_cells
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, c)| !c.text.is_empty())
|
||||||
|
.all(|(c, h)| table.cell(*r, c).text == h.text);
|
||||||
|
!repeated && has_content(table, *r, profile)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
pub fn infer(table: &Table, profile: &Profile) -> Result<Mapping, Vec<Diagnostic>> {
|
||||||
|
inspect(table, profile).0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Automatic recommendations independent of manual column choices. When the
|
||||||
|
/// whole mapping is blocked, header hints remain suggestions, not validation.
|
||||||
|
#[cfg(feature = "desktop")]
|
||||||
|
pub(crate) fn suggested_roles(
|
||||||
|
table: &Table,
|
||||||
|
profile: &Profile,
|
||||||
|
) -> std::collections::BTreeMap<usize, &'static str> {
|
||||||
|
let mut automatic = profile.clone();
|
||||||
|
automatic.columns.clear();
|
||||||
|
automatic.column_usage.clear();
|
||||||
|
automatic.expected_headers.clear();
|
||||||
|
let (mapping, evidence) = inspect(table, &automatic);
|
||||||
|
let mut suggestions = std::collections::BTreeMap::new();
|
||||||
|
if let Ok(mapping) = mapping {
|
||||||
|
suggestions.insert(
|
||||||
|
mapping.start,
|
||||||
|
if mapping.start_end {
|
||||||
|
"Start–end"
|
||||||
|
} else {
|
||||||
|
"Start"
|
||||||
|
},
|
||||||
|
);
|
||||||
|
suggestions.insert(mapping.title, "Title");
|
||||||
|
if let Some(column) = mapping.end {
|
||||||
|
suggestions.insert(column, "End");
|
||||||
|
}
|
||||||
|
if let Some(column) = mapping.duration {
|
||||||
|
suggestions.insert(column, "Duration");
|
||||||
|
}
|
||||||
|
for (column, usage) in mapping.column_usage {
|
||||||
|
if let Some(column) = column_index(&column) {
|
||||||
|
match usage.as_str() {
|
||||||
|
"notes" => {
|
||||||
|
suggestions.insert(column, "Notes");
|
||||||
|
}
|
||||||
|
"metadata" => {
|
||||||
|
suggestions.insert(column, "Metadata");
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if let Some(header) = evidence
|
||||||
|
.first()
|
||||||
|
.and_then(|text| text.strip_prefix("Header row "))
|
||||||
|
.and_then(|text| text.parse::<usize>().ok())
|
||||||
|
{
|
||||||
|
for (column, cell) in table.rows[header - 1].iter().enumerate() {
|
||||||
|
let suggested = match role(&cell.text) {
|
||||||
|
Some("start") => Some("Start"),
|
||||||
|
Some("start_end") => Some("Start–end"),
|
||||||
|
Some("end") => Some("End"),
|
||||||
|
Some("duration") => Some("Duration"),
|
||||||
|
Some("title") => Some("Title"),
|
||||||
|
_ => match automatic_usage(&cell.text) {
|
||||||
|
"notes" => Some("Notes"),
|
||||||
|
"metadata" => Some("Metadata"),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if let Some(suggested) = suggested {
|
||||||
|
suggestions.insert(column, suggested);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
suggestions
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retain inference evidence even when a later ambiguity blocks the mapping.
|
||||||
|
pub fn inspect(
|
||||||
|
table: &Table,
|
||||||
|
profile: &Profile,
|
||||||
|
) -> (Result<Mapping, Vec<Diagnostic>>, Vec<String>) {
|
||||||
|
let mut evidence = Vec::new();
|
||||||
|
let result = infer_inner(table, profile, &mut evidence);
|
||||||
|
(result, evidence)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn infer_inner(
|
||||||
|
table: &Table,
|
||||||
|
profile: &Profile,
|
||||||
|
evidence: &mut Vec<String>,
|
||||||
|
) -> Result<Mapping, Vec<Diagnostic>> {
|
||||||
|
let header = if let Some(r) = profile.header_row {
|
||||||
|
if r == 0 || r > table.rows.len() {
|
||||||
|
return Err(vec![Diagnostic::new(
|
||||||
|
1,
|
||||||
|
"INVALID_HEADER",
|
||||||
|
&table.name,
|
||||||
|
"Header row is outside this sheet",
|
||||||
|
)]);
|
||||||
|
}
|
||||||
|
r - 1
|
||||||
|
} else {
|
||||||
|
let candidates: Vec<_> = table
|
||||||
|
.rows
|
||||||
|
.iter()
|
||||||
|
.take(100)
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, row)| (i, row.iter().filter(|c| role(&c.text).is_some()).count()))
|
||||||
|
.collect();
|
||||||
|
let best = candidates
|
||||||
|
.iter()
|
||||||
|
.map(|(_, score)| *score)
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0);
|
||||||
|
if best < 2 {
|
||||||
|
return Err(vec![Diagnostic::new(
|
||||||
|
1,
|
||||||
|
"HEADER_REQUIRED",
|
||||||
|
&table.name,
|
||||||
|
"Cannot identify the header band. Set header_row and columns in a mapping profile or clarify headers.",
|
||||||
|
)]);
|
||||||
|
}
|
||||||
|
candidates
|
||||||
|
.iter()
|
||||||
|
.find(|(_, score)| *score == best)
|
||||||
|
.unwrap()
|
||||||
|
.0
|
||||||
|
};
|
||||||
|
evidence.push(format!("Header row {}", header + 1));
|
||||||
|
let mut profile_errors = Vec::new();
|
||||||
|
for (&row, kind) in &profile.row_kinds {
|
||||||
|
if row <= header + 1
|
||||||
|
|| row > table.rows.len()
|
||||||
|
|| !["event", "gap", "marker", "note", "ignore"].contains(&kind.as_str())
|
||||||
|
{
|
||||||
|
profile_errors.push(Diagnostic::new(1,"INVALID_ROW_OVERRIDE",&table.name,format!("Invalid row/kind {row}: {kind}; use an existing data row and event, gap, marker, note or ignore")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (role, values) in [
|
||||||
|
("TITLE", &profile.titles),
|
||||||
|
("START", &profile.starts),
|
||||||
|
("END", &profile.ends),
|
||||||
|
("DURATION", &profile.durations),
|
||||||
|
] {
|
||||||
|
for &row in values.keys() {
|
||||||
|
if row <= header + 1 || row > table.rows.len() {
|
||||||
|
profile_errors.push(Diagnostic::new(
|
||||||
|
1,
|
||||||
|
&format!("INVALID_{role}_OVERRIDE"),
|
||||||
|
&table.name,
|
||||||
|
format!(
|
||||||
|
"{} override row {row} is outside data rows",
|
||||||
|
role.to_lowercase()
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (col, expected) in &profile.expected_headers {
|
||||||
|
if column_index(col).is_none_or(|c| table.cell(header, c).text != *expected) {
|
||||||
|
profile_errors.push(Diagnostic::new(
|
||||||
|
1,
|
||||||
|
"PROFILE_HEADER_CHANGED",
|
||||||
|
&table.name,
|
||||||
|
format!(
|
||||||
|
"Expected header {expected:?} in column {col}; review this mapping profile"
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !profile_errors.is_empty() {
|
||||||
|
return Err(profile_errors);
|
||||||
|
}
|
||||||
|
let width = table.rows.iter().map(Vec::len).max().unwrap_or(0);
|
||||||
|
let mut excluded = std::collections::BTreeSet::new();
|
||||||
|
let mut column_usage = std::collections::BTreeMap::new();
|
||||||
|
for (letter, usage) in &profile.column_usage {
|
||||||
|
match column_index(letter).filter(|c| *c < width) {
|
||||||
|
Some(c)
|
||||||
|
if ["notes", "metadata", "ignore"].contains(&usage.as_str())
|
||||||
|
&& excluded.insert(c) =>
|
||||||
|
{
|
||||||
|
column_usage.insert(column_name(c), usage.clone());
|
||||||
|
evidence.push(format!("Explicit {usage} column {}", column_name(c)));
|
||||||
|
}
|
||||||
|
_ => profile_errors.push(err("INVALID_COLUMN_USAGE", table, header, 0, format!("Invalid or duplicate column usage {letter}: {usage}; use an existing column with notes, metadata or ignore"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !profile_errors.is_empty() {
|
||||||
|
return Err(profile_errors);
|
||||||
|
}
|
||||||
|
let rows = active_rows(table, header, profile);
|
||||||
|
let mut diagnostics = vec![];
|
||||||
|
|
||||||
|
let mut selected = std::collections::BTreeMap::new();
|
||||||
|
for (r, col) in &profile.columns {
|
||||||
|
if ![
|
||||||
|
"start",
|
||||||
|
"start_end",
|
||||||
|
"end",
|
||||||
|
"duration",
|
||||||
|
"title",
|
||||||
|
"secondary_title",
|
||||||
|
]
|
||||||
|
.contains(&r.as_str())
|
||||||
|
{
|
||||||
|
diagnostics.push(err(
|
||||||
|
"INVALID_MAPPING",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
0,
|
||||||
|
format!("Unknown role {r}; use start, start_end, end, duration, title or secondary_title"),
|
||||||
|
));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match column_index(col).filter(|c| *c < width) {
|
||||||
|
Some(c) if excluded.contains(&c) => diagnostics.push(err(
|
||||||
|
"INVALID_MAPPING",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
c,
|
||||||
|
format!("Column {col} cannot be both {r} and metadata/ignore; choose one meaning"),
|
||||||
|
)),
|
||||||
|
Some(c) => {
|
||||||
|
selected.insert(r.as_str(), c);
|
||||||
|
evidence.push(format!("Explicit {} column {col}", role_label(r)));
|
||||||
|
}
|
||||||
|
None => diagnostics.push(err(
|
||||||
|
"INVALID_MAPPING",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
0,
|
||||||
|
format!("Invalid column {col}"),
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for r in ["start_end", "start", "end", "duration", "title"] {
|
||||||
|
if matches!(r, "start" | "start_end")
|
||||||
|
&& (selected.contains_key("start") || selected.contains_key("start_end"))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if selected.contains_key(r) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let candidates: Vec<_> = (0..width)
|
||||||
|
.filter(|c| !excluded.contains(c))
|
||||||
|
.filter(|c| !selected.values().any(|v| v == c))
|
||||||
|
.filter(|c| role(&table.cell(header, *c).text) == Some(r))
|
||||||
|
.collect();
|
||||||
|
if candidates.len() == 1 {
|
||||||
|
let candidate = candidates[0];
|
||||||
|
let timing_cells: Vec<_> = rows
|
||||||
|
.iter()
|
||||||
|
.map(|row| table.cell(*row, candidate))
|
||||||
|
.filter(|cell| !placeholder(&cell.text))
|
||||||
|
.collect();
|
||||||
|
let detected_role = if r == "start"
|
||||||
|
&& !timing_cells.is_empty()
|
||||||
|
&& timing_cells
|
||||||
|
.iter()
|
||||||
|
.all(|cell| clock_range(cell).is_some_and(|(_, end)| end.is_some()))
|
||||||
|
{
|
||||||
|
"start_end"
|
||||||
|
} else {
|
||||||
|
r
|
||||||
|
};
|
||||||
|
selected.insert(detected_role, candidate);
|
||||||
|
evidence.push(format!(
|
||||||
|
"Header suggests {} in {}",
|
||||||
|
role_label(detected_role),
|
||||||
|
column_name(candidate)
|
||||||
|
));
|
||||||
|
} else if candidates.len() > 1 {
|
||||||
|
diagnostics.push(err("AMBIGUOUS_COLUMN",table,header,candidates[0],format!("Several {} columns: {}. Clarify headers or explicitly select the intended column; parent and child timers cannot be flattened automatically.",role_label(r),candidates.iter().map(|c| column_name(*c)).collect::<Vec<_>>().join(", "))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Data can supply a missing start role when exactly one whole column agrees.
|
||||||
|
if !selected.contains_key("start")
|
||||||
|
&& !selected.contains_key("start_end")
|
||||||
|
&& !diagnostics.iter().any(|d| d.code == "AMBIGUOUS_COLUMN")
|
||||||
|
{
|
||||||
|
let candidates: Vec<_> = (0..width)
|
||||||
|
.filter(|c| !excluded.contains(c))
|
||||||
|
.filter(|c| !selected.values().any(|v| v == c))
|
||||||
|
.filter(|c| {
|
||||||
|
let cells: Vec<_> = rows
|
||||||
|
.iter()
|
||||||
|
.map(|row| table.cell(*row, *c))
|
||||||
|
.filter(|c| !placeholder(&c.text))
|
||||||
|
.collect();
|
||||||
|
cells.len() >= 2 && cells.iter().all(|cell| clock_range(cell).is_some())
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if candidates.len() == 1 {
|
||||||
|
let candidate = candidates[0];
|
||||||
|
let combined = rows
|
||||||
|
.iter()
|
||||||
|
.map(|row| table.cell(*row, candidate))
|
||||||
|
.filter(|cell| !placeholder(&cell.text))
|
||||||
|
.all(|cell| clock_range(&cell).is_some_and(|(_, end)| end.is_some()));
|
||||||
|
let inferred_role = if combined { "start_end" } else { "start" };
|
||||||
|
selected.insert(inferred_role, candidate);
|
||||||
|
evidence.push(format!(
|
||||||
|
"All populated data cells support {} in {}",
|
||||||
|
role_label(inferred_role),
|
||||||
|
column_name(candidate)
|
||||||
|
));
|
||||||
|
} else if candidates.len() > 1 {
|
||||||
|
diagnostics.push(err(
|
||||||
|
"AMBIGUOUS_COLUMN",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
candidates[0],
|
||||||
|
"Multiple data columns can mean start or start–end; clarify headers or select a column",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Duration inference remains separate from clock/range inference.
|
||||||
|
if !selected.contains_key("duration")
|
||||||
|
&& !diagnostics.iter().any(|d| d.code == "AMBIGUOUS_COLUMN")
|
||||||
|
{
|
||||||
|
let candidates: Vec<_> = (0..width)
|
||||||
|
.filter(|c| !excluded.contains(c))
|
||||||
|
.filter(|c| !selected.values().any(|v| v == c))
|
||||||
|
.filter(|c| {
|
||||||
|
let cells: Vec<_> = rows
|
||||||
|
.iter()
|
||||||
|
.map(|row| table.cell(*row, *c))
|
||||||
|
.filter(|cell| !placeholder(&cell.text))
|
||||||
|
.collect();
|
||||||
|
cells.len() >= 2 && cells.iter().all(|cell| duration(cell, None).is_some())
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if candidates.len() == 1 {
|
||||||
|
selected.insert("duration", candidates[0]);
|
||||||
|
evidence.push(format!(
|
||||||
|
"All populated data cells support duration in {}",
|
||||||
|
column_name(candidates[0])
|
||||||
|
));
|
||||||
|
} else if candidates.len() > 1 {
|
||||||
|
diagnostics.push(err(
|
||||||
|
"AMBIGUOUS_COLUMN",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
candidates[0],
|
||||||
|
"Multiple data columns can mean duration; clarify headers or select a column",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Cue is a title only as a fallback; it is also commonly a cue number.
|
||||||
|
if !selected.contains_key("title") {
|
||||||
|
let cols: Vec<_> = (0..width)
|
||||||
|
.filter(|c| !excluded.contains(c))
|
||||||
|
.filter(|c| !selected.values().any(|v| v == c))
|
||||||
|
.filter(|c| normalize(&table.cell(header, *c).text) == "cue")
|
||||||
|
.collect();
|
||||||
|
if cols.len() == 1 {
|
||||||
|
selected.insert("title", cols[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for required in ["start", "title"] {
|
||||||
|
let present = if required == "start" {
|
||||||
|
selected.contains_key("start") || selected.contains_key("start_end")
|
||||||
|
} else {
|
||||||
|
selected.contains_key(required)
|
||||||
|
};
|
||||||
|
if !present {
|
||||||
|
diagnostics.push(Diagnostic::new(
|
||||||
|
1,
|
||||||
|
"MISSING_COLUMN",
|
||||||
|
&table.name,
|
||||||
|
format!("Cannot infer {required}; clarify headers or map the column"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !diagnostics.is_empty() {
|
||||||
|
return Err(diagnostics);
|
||||||
|
}
|
||||||
|
if selected.contains_key("start") && selected.contains_key("start_end") {
|
||||||
|
diagnostics.push(err(
|
||||||
|
"INVALID_MAPPING",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
selected["start_end"],
|
||||||
|
"Choose either a Start column or a Start–end column, not both",
|
||||||
|
));
|
||||||
|
return Err(diagnostics);
|
||||||
|
}
|
||||||
|
if selected.contains_key("start_end") && selected.contains_key("end") {
|
||||||
|
diagnostics.push(err(
|
||||||
|
"INVALID_MAPPING",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
selected["end"],
|
||||||
|
"A Start–end column already supplies both values; remove the separate End mapping",
|
||||||
|
));
|
||||||
|
return Err(diagnostics);
|
||||||
|
}
|
||||||
|
let mut used = std::collections::BTreeSet::new();
|
||||||
|
for (&r, &c) in &selected {
|
||||||
|
if !used.insert(c) {
|
||||||
|
diagnostics.push(err(
|
||||||
|
"INVALID_MAPPING",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
c,
|
||||||
|
format!("{r} shares a column with another role"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for c in 0..width {
|
||||||
|
if !used.contains(&c) && !column_usage.contains_key(&column_name(c)) {
|
||||||
|
let usage = automatic_usage(&table.cell(header, c).text);
|
||||||
|
column_usage.insert(column_name(c), usage.into());
|
||||||
|
evidence.push(format!("Column {} defaults to {usage}", column_name(c)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let secondary_mode = profile.secondary_title_mode.as_deref().unwrap_or("either");
|
||||||
|
if !["either", "merge", "merge_previous", "notes", "metadata"].contains(&secondary_mode) {
|
||||||
|
diagnostics.push(err(
|
||||||
|
"INVALID_SECONDARY_TITLE_MODE",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
selected["title"],
|
||||||
|
"Secondary title handling must be either, merge, merge_previous, notes or metadata",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(&column) = selected.get("secondary_title")
|
||||||
|
&& matches!(secondary_mode, "notes" | "metadata")
|
||||||
|
{
|
||||||
|
column_usage.insert(column_name(column), secondary_mode.into());
|
||||||
|
}
|
||||||
|
let column_labels = column_usage
|
||||||
|
.keys()
|
||||||
|
.map(|letter| {
|
||||||
|
let c = column_index(letter).expect("validated column");
|
||||||
|
let header_text = table.cell(header, c).text.trim().to_owned();
|
||||||
|
(
|
||||||
|
letter.clone(),
|
||||||
|
if header_text.is_empty() {
|
||||||
|
letter.clone()
|
||||||
|
} else {
|
||||||
|
header_text
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let start_end = selected.get("start_end").copied();
|
||||||
|
let start = start_end.unwrap_or_else(|| selected["start"]);
|
||||||
|
let end = selected.get("end").copied();
|
||||||
|
let dur = selected.get("duration").copied();
|
||||||
|
let mut unit = profile.duration_unit.clone();
|
||||||
|
let duration_mode = profile.duration_mode.as_deref().unwrap_or("strict");
|
||||||
|
if ![
|
||||||
|
"strict", "minimum", "maximum", "median", "sum", "margin", "split",
|
||||||
|
]
|
||||||
|
.contains(&duration_mode)
|
||||||
|
{
|
||||||
|
diagnostics.push(err(
|
||||||
|
"INVALID_DURATION_MODE",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
dur.unwrap_or(start),
|
||||||
|
"Use strict, minimum, maximum, median, sum, margin or split",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if profile.duration_add_margin && profile.margin_ms().is_none() {
|
||||||
|
diagnostics.push(err(
|
||||||
|
"INVALID_MARGIN",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
dur.unwrap_or(start),
|
||||||
|
"Enter a positive margin duration with units, for example 2 min or 30 s.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if (profile.duration_split || duration_mode == "split")
|
||||||
|
&& profile
|
||||||
|
.duration_separator
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(str::is_empty)
|
||||||
|
{
|
||||||
|
diagnostics.push(err(
|
||||||
|
"INVALID_DURATION_SEPARATOR",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
dur.unwrap_or(start),
|
||||||
|
"Split separator cannot be empty; use \\n for newline",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(u) = &unit
|
||||||
|
&& !["minutes", "seconds", "hh:mm", "mm:ss", "excel"].contains(&u.as_str())
|
||||||
|
{
|
||||||
|
diagnostics.push(err(
|
||||||
|
"INVALID_UNIT",
|
||||||
|
table,
|
||||||
|
header,
|
||||||
|
dur.unwrap_or(start),
|
||||||
|
"Use minutes, seconds, hh:mm, mm:ss or excel",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(c) = dur {
|
||||||
|
let h = normalize(&table.cell(header, c).text);
|
||||||
|
if unit.is_none() {
|
||||||
|
unit = if h.contains("mm:ss") {
|
||||||
|
Some("mm:ss")
|
||||||
|
} else if h.contains("hh:mm") {
|
||||||
|
Some("hh:mm")
|
||||||
|
} else if h.contains("min") {
|
||||||
|
Some("minutes")
|
||||||
|
} else if h.contains("sec") {
|
||||||
|
Some("seconds")
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
.map(str::to_string);
|
||||||
|
}
|
||||||
|
let cells: Vec<_> = rows
|
||||||
|
.iter()
|
||||||
|
.filter(|r| !profile.durations.contains_key(&(*r + 1)))
|
||||||
|
.map(|r| (*r, table.cell(*r, c)))
|
||||||
|
.filter(|(_, c)| !placeholder(&c.text))
|
||||||
|
.collect();
|
||||||
|
if unit.is_none() && cells.iter().any(|(_, cell)| duration(cell, None).is_none()) {
|
||||||
|
let possible: Vec<_> = ["minutes", "seconds", "hh:mm", "mm:ss", "excel"]
|
||||||
|
.into_iter()
|
||||||
|
.filter(|u| {
|
||||||
|
let mut comparisons = 0;
|
||||||
|
let fits = cells.iter().all(|(r, cell)| {
|
||||||
|
let Some(d) = duration(cell, Some(u)) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
if profile.starts.contains_key(&(*r + 1))
|
||||||
|
|| profile.ends.contains_key(&(*r + 1))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let Some((a, b)) = clock_range(&table.cell(*r, start)) else {
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
let b = b.or_else(|| end.and_then(|c| clock(&table.cell(*r, c))));
|
||||||
|
if let Some(b) = b {
|
||||||
|
comparisons += 1;
|
||||||
|
(b - a - d).abs() <= 1
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
});
|
||||||
|
fits && comparisons > 0
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if possible.len() == 1 {
|
||||||
|
unit = Some(possible[0].into());
|
||||||
|
evidence.push(format!(
|
||||||
|
"Duration unit {} verified against all available start/end pairs",
|
||||||
|
possible[0]
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for &row in &rows {
|
||||||
|
for (&r, &col) in &selected {
|
||||||
|
if matches!(r, "title" | "secondary_title") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let cell = table.cell(row, col);
|
||||||
|
let overridden = match r {
|
||||||
|
"start" => profile.starts.contains_key(&(row + 1)),
|
||||||
|
"start_end" => {
|
||||||
|
profile.starts.contains_key(&(row + 1)) && profile.ends.contains_key(&(row + 1))
|
||||||
|
}
|
||||||
|
"end" => profile.ends.contains_key(&(row + 1)),
|
||||||
|
"duration" => profile.durations.contains_key(&(row + 1)),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if overridden {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if cell.formula.is_some() && placeholder(&cell.text) {
|
||||||
|
diagnostics.push(err(
|
||||||
|
"FORMULA_WITHOUT_VALUE",
|
||||||
|
table,
|
||||||
|
row,
|
||||||
|
col,
|
||||||
|
"Recalculate and save the workbook; this formula has no cached value",
|
||||||
|
));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if placeholder(&cell.text) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let valid = match r {
|
||||||
|
"start" => clock_range(&cell).is_some(),
|
||||||
|
"start_end" => clock_range(&cell).is_some_and(|(_, end)| end.is_some()),
|
||||||
|
"end" => clock(&cell).is_some(),
|
||||||
|
_ => select_duration_parts(
|
||||||
|
&cell,
|
||||||
|
unit.as_deref(),
|
||||||
|
profile.duration_mode.as_deref(),
|
||||||
|
profile.duration_split,
|
||||||
|
profile.margin_ms(),
|
||||||
|
profile.duration_separator.as_deref(),
|
||||||
|
)
|
||||||
|
.is_some(),
|
||||||
|
};
|
||||||
|
if !valid {
|
||||||
|
diagnostics.push(err("INCONSISTENT_COLUMN_MEANING",table,row,col,format!("Value {:?} does not fit {}{} for the whole column. Clarify headers/units or correct this value; rows cannot switch meanings.",cell.text,role_label(r),if r=="duration" {" with an unambiguous duration unit"}else{""})));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !diagnostics.is_empty() {
|
||||||
|
return Err(diagnostics);
|
||||||
|
}
|
||||||
|
evidence.push(
|
||||||
|
"Every relevant nonempty timing cell checked, including explicitly mapped columns".into(),
|
||||||
|
);
|
||||||
|
Ok(Mapping {
|
||||||
|
header_row: header + 1,
|
||||||
|
start,
|
||||||
|
start_end: start_end.is_some(),
|
||||||
|
end,
|
||||||
|
duration: dur,
|
||||||
|
title: selected["title"],
|
||||||
|
secondary_title: selected.get("secondary_title").copied(),
|
||||||
|
secondary_title_mode: profile.secondary_title_mode.clone(),
|
||||||
|
duration_unit: unit,
|
||||||
|
duration_mode: profile.duration_mode.clone(),
|
||||||
|
duration_separator: profile.duration_separator.clone(),
|
||||||
|
duration_split: profile.duration_split,
|
||||||
|
duration_add_margin: profile.duration_add_margin,
|
||||||
|
duration_margin: profile.duration_margin.clone(),
|
||||||
|
evidence: evidence.clone(),
|
||||||
|
column_usage,
|
||||||
|
column_labels,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,411 @@
|
||||||
|
use crate::{
|
||||||
|
model::{Analysis, Entry, OntimeSettings, Rundown, column_index, column_name},
|
||||||
|
pipeline::validate,
|
||||||
|
time::display,
|
||||||
|
};
|
||||||
|
use anyhow::{Result, bail, ensure};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use std::{
|
||||||
|
fmt::Write as _,
|
||||||
|
io::{Cursor, Write},
|
||||||
|
path::Path,
|
||||||
|
sync::atomic::{AtomicBool, Ordering},
|
||||||
|
};
|
||||||
|
use zip::{ZipWriter, write::SimpleFileOptions};
|
||||||
|
|
||||||
|
// Match Ontime v4 import-screen defaults (not the JSON property names).
|
||||||
|
// The import UI expects plural "notes", unlike Ontime's own XLSX exporter.
|
||||||
|
const SPREADSHEET_HEADERS: [&str; 16] = [
|
||||||
|
"Time Start",
|
||||||
|
"Time End",
|
||||||
|
"Duration",
|
||||||
|
"Cue",
|
||||||
|
"Title",
|
||||||
|
"Notes",
|
||||||
|
"Timer Type",
|
||||||
|
"Link Start",
|
||||||
|
"Colour",
|
||||||
|
"ID",
|
||||||
|
"Flag",
|
||||||
|
"Count to end",
|
||||||
|
"End Action",
|
||||||
|
"Warning Time",
|
||||||
|
"Danger Time",
|
||||||
|
"Skip",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn entry_values(entry: &Entry, rundown: &Rundown, usage: &str, column: Option<&str>) -> String {
|
||||||
|
entry
|
||||||
|
.source_rows
|
||||||
|
.iter()
|
||||||
|
.flat_map(|row| &row.cells)
|
||||||
|
.filter(|(letter, cell)| {
|
||||||
|
!cell.text.trim().is_empty()
|
||||||
|
&& rundown
|
||||||
|
.mapping
|
||||||
|
.column_usage
|
||||||
|
.get(*letter)
|
||||||
|
.map(String::as_str)
|
||||||
|
== Some(usage)
|
||||||
|
&& column.is_none_or(|expected| *letter == expected)
|
||||||
|
})
|
||||||
|
.map(|(_, cell)| cell.text.clone())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn metadata_columns(rundown: &Rundown) -> Vec<(String, String)> {
|
||||||
|
let mut columns = rundown
|
||||||
|
.mapping
|
||||||
|
.column_usage
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, usage)| usage.as_str() == "metadata")
|
||||||
|
.map(|(column, _)| {
|
||||||
|
let label = rundown
|
||||||
|
.mapping
|
||||||
|
.column_labels
|
||||||
|
.get(column)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_else(|| column.clone());
|
||||||
|
(column.clone(), label)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
columns.sort_by_key(|(column, _)| column_index(column).unwrap_or(usize::MAX));
|
||||||
|
let mut used = SPREADSHEET_HEADERS
|
||||||
|
.iter()
|
||||||
|
.map(|header| header.to_lowercase())
|
||||||
|
.collect::<BTreeSet<_>>();
|
||||||
|
for (column, label) in &mut columns {
|
||||||
|
let base = if label.trim().is_empty() {
|
||||||
|
format!("Metadata {column}")
|
||||||
|
} else {
|
||||||
|
label.trim().to_string()
|
||||||
|
};
|
||||||
|
let mut unique = base.clone();
|
||||||
|
if !used.insert(unique.to_lowercase()) {
|
||||||
|
unique = format!("{base} ({column})");
|
||||||
|
used.insert(unique.to_lowercase());
|
||||||
|
}
|
||||||
|
*label = unique;
|
||||||
|
}
|
||||||
|
columns
|
||||||
|
}
|
||||||
|
|
||||||
|
fn xml_text(value: &str) -> String {
|
||||||
|
let mut escaped = String::with_capacity(value.len());
|
||||||
|
for character in value.chars().filter(|character| {
|
||||||
|
matches!(*character, '\t' | '\n' | '\r')
|
||||||
|
|| ('\u{20}'..='\u{d7ff}').contains(character)
|
||||||
|
|| ('\u{e000}'..='\u{fffd}').contains(character)
|
||||||
|
|| ('\u{10000}'..='\u{10ffff}').contains(character)
|
||||||
|
}) {
|
||||||
|
escaped.push_str(match character {
|
||||||
|
'&' => "&",
|
||||||
|
'<' => "<",
|
||||||
|
'>' => ">",
|
||||||
|
'"' => """,
|
||||||
|
'\'' => "'",
|
||||||
|
_ => {
|
||||||
|
escaped.push(character);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
escaped
|
||||||
|
}
|
||||||
|
|
||||||
|
fn worksheet(rundown: &Rundown) -> String {
|
||||||
|
let metadata = metadata_columns(rundown);
|
||||||
|
let mut rows = vec![
|
||||||
|
SPREADSHEET_HEADERS
|
||||||
|
.iter()
|
||||||
|
.map(|header| (*header).to_string())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
];
|
||||||
|
rows[0].extend(metadata.iter().map(|(_, label)| label.clone()));
|
||||||
|
for entry in rundown.entries.iter().filter(|entry| entry.kind == "event") {
|
||||||
|
let mut row = vec![
|
||||||
|
display(entry.start_ms),
|
||||||
|
display(entry.end_ms),
|
||||||
|
display(entry.duration_ms),
|
||||||
|
entry
|
||||||
|
.source_rows
|
||||||
|
.first()
|
||||||
|
.map(|row| row.row.to_string())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
entry.title.clone(),
|
||||||
|
entry_values(entry, rundown, "notes", None),
|
||||||
|
"count-down".into(),
|
||||||
|
"FALSE".into(), // Ontime otherwise links events, removing intentional gaps.
|
||||||
|
"#5744b5".into(),
|
||||||
|
entry.id.clone(),
|
||||||
|
"FALSE".into(),
|
||||||
|
"FALSE".into(),
|
||||||
|
"none".into(),
|
||||||
|
display(120000.min(entry.duration_ms / 5)),
|
||||||
|
display(60000.min(entry.duration_ms / 10)),
|
||||||
|
"FALSE".into(),
|
||||||
|
];
|
||||||
|
row.extend(
|
||||||
|
metadata
|
||||||
|
.iter()
|
||||||
|
.map(|(column, _)| entry_values(entry, rundown, "metadata", Some(column))),
|
||||||
|
);
|
||||||
|
rows.push(row);
|
||||||
|
}
|
||||||
|
let mut xml = String::from(
|
||||||
|
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews><cols><col min="1" max="3" width="13" customWidth="1"/><col min="4" max="4" width="9" customWidth="1"/><col min="5" max="6" width="34" customWidth="1"/><col min="7" max="64" width="18" customWidth="1"/></cols><sheetData>"#,
|
||||||
|
);
|
||||||
|
for (row_index, row) in rows.iter().enumerate() {
|
||||||
|
let _ = write!(xml, "<row r=\"{}\">", row_index + 1);
|
||||||
|
for (column, value) in row.iter().enumerate() {
|
||||||
|
let _ = write!(
|
||||||
|
xml,
|
||||||
|
"<c r=\"{}{}\" t=\"inlineStr\"><is><t xml:space=\"preserve\">{}</t></is></c>",
|
||||||
|
column_name(column),
|
||||||
|
row_index + 1,
|
||||||
|
xml_text(value)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
xml.push_str("</row>");
|
||||||
|
}
|
||||||
|
xml.push_str("</sheetData><autoFilter ref=\"A1:");
|
||||||
|
xml.push_str(&column_name(rows[0].len() - 1));
|
||||||
|
let _ = write!(xml, "{}\"/></worksheet>", rows.len());
|
||||||
|
xml
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn xlsx(rundown: &Rundown) -> Result<Vec<u8>> {
|
||||||
|
ensure!(
|
||||||
|
validate(rundown).is_empty(),
|
||||||
|
"Cannot export an inconsistent rundown"
|
||||||
|
);
|
||||||
|
let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
|
||||||
|
let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||||
|
let sheet = worksheet(rundown);
|
||||||
|
for (name, contents) in [
|
||||||
|
(
|
||||||
|
"[Content_Types].xml",
|
||||||
|
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>"#,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"_rels/.rels",
|
||||||
|
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>"#,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"xl/workbook.xml",
|
||||||
|
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Ontime" sheetId="1" r:id="rId1"/></sheets></workbook>"#,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"xl/_rels/workbook.xml.rels",
|
||||||
|
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>"#,
|
||||||
|
),
|
||||||
|
("xl/worksheets/sheet1.xml", sheet.as_str()),
|
||||||
|
] {
|
||||||
|
zip.start_file(name, options)?;
|
||||||
|
zip.write_all(contents.as_bytes())?;
|
||||||
|
}
|
||||||
|
Ok(zip.finish()?.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ontime(r: &Rundown) -> Result<Value> {
|
||||||
|
ontime_with_settings(r, &OntimeSettings::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ontime_with_settings(r: &Rundown, settings: &OntimeSettings) -> Result<Value> {
|
||||||
|
ensure!(
|
||||||
|
matches!(settings.time_format.as_str(), "12" | "24"),
|
||||||
|
"Ontime clock format must be 12 or 24"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
matches!(
|
||||||
|
settings.language.as_str(),
|
||||||
|
"en" | "fr" | "de" | "it" | "pt" | "es" | "custom"
|
||||||
|
),
|
||||||
|
"Unsupported Ontime language"
|
||||||
|
);
|
||||||
|
for color in [
|
||||||
|
&settings.normal_color,
|
||||||
|
&settings.warning_color,
|
||||||
|
&settings.danger_color,
|
||||||
|
] {
|
||||||
|
ensure!(
|
||||||
|
color.starts_with('#')
|
||||||
|
&& matches!(color.len(), 7 | 9)
|
||||||
|
&& color[1..].bytes().all(|b| b.is_ascii_hexdigit()),
|
||||||
|
"Ontime colours must use #RRGGBB or #RRGGBBAA"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure!(
|
||||||
|
validate(r).is_empty(),
|
||||||
|
"Cannot export an inconsistent rundown"
|
||||||
|
);
|
||||||
|
let mut entries = serde_json::Map::new();
|
||||||
|
let mut order = vec![];
|
||||||
|
let mut custom_fields = serde_json::Map::new();
|
||||||
|
let mut metadata_keys = BTreeMap::new();
|
||||||
|
let mut used_keys = BTreeSet::new();
|
||||||
|
for (column, usage) in &r.mapping.column_usage {
|
||||||
|
if usage != "metadata" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let label = r
|
||||||
|
.mapping
|
||||||
|
.column_labels
|
||||||
|
.get(column)
|
||||||
|
.map(String::as_str)
|
||||||
|
.unwrap_or(column);
|
||||||
|
let base = crate::time::normalize(label)
|
||||||
|
.chars()
|
||||||
|
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
|
||||||
|
.collect::<String>()
|
||||||
|
.split('_')
|
||||||
|
.filter(|part| !part.is_empty())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("_");
|
||||||
|
let base = if base.is_empty() {
|
||||||
|
format!("column_{}", column.to_lowercase())
|
||||||
|
} else {
|
||||||
|
base
|
||||||
|
};
|
||||||
|
let mut key = base.clone();
|
||||||
|
if !used_keys.insert(key.clone()) {
|
||||||
|
key = format!("{base}_{}", column.to_lowercase());
|
||||||
|
used_keys.insert(key.clone());
|
||||||
|
}
|
||||||
|
custom_fields.insert(
|
||||||
|
key.clone(),
|
||||||
|
json!({"type":"text","colour":"#64748b","label":label}),
|
||||||
|
);
|
||||||
|
metadata_keys.insert(column.clone(), key);
|
||||||
|
}
|
||||||
|
for e in r.entries.iter().filter(|e| e.kind == "event") {
|
||||||
|
let mut notes = vec![];
|
||||||
|
let mut custom: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||||
|
for row in &e.source_rows {
|
||||||
|
for (col, cell) in &row.cells {
|
||||||
|
if cell.text.trim().is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match r.mapping.column_usage.get(col).map(String::as_str) {
|
||||||
|
Some("notes") => notes.push(cell.text.clone()),
|
||||||
|
Some("metadata") => {
|
||||||
|
if let Some(key) = metadata_keys.get(col) {
|
||||||
|
custom
|
||||||
|
.entry(key.clone())
|
||||||
|
.or_default()
|
||||||
|
.push(cell.text.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let custom: BTreeMap<_, _> = custom
|
||||||
|
.into_iter()
|
||||||
|
.map(|(key, values)| (key, values.join("\n")))
|
||||||
|
.collect();
|
||||||
|
entries.insert(e.id.clone(),json!({"id":e.id,"type":"event","cue":e.source_rows.first().map(|row| row.row.to_string()).unwrap_or_default(),"title":e.title,"note":notes.join("\n"),
|
||||||
|
"timeStart":e.start_ms,"timeEnd":e.end_ms,"duration":e.duration_ms,"linkStart":false,
|
||||||
|
"timeStrategy":"lock-duration","timerType":"count-down","endAction":"none","skip":false,
|
||||||
|
"colour":"#5744b5","timeWarning":120000.min(e.duration_ms/5),"timeDanger":60000.min(e.duration_ms/10),
|
||||||
|
"countToEnd":false,"flag":false,"custom":custom,"triggers":[]}));
|
||||||
|
order.push(e.id.clone());
|
||||||
|
}
|
||||||
|
Ok(
|
||||||
|
json!({"settings":{"version":"4.0.0","timeFormat":settings.time_format,"language":settings.language,"auxTimerNames":settings.aux_timer_names},"project":{"title":r.title,"description":"Imported schedule. Explicit starts and untimed gaps preserved; manual playback. Review inferred values before the show."},
|
||||||
|
"rundowns":{"default":{"id":"default","title":r.title,"entries":entries,"order":order,"flatOrder":order,"revision":0}},
|
||||||
|
"customFields":custom_fields,"urlPresets":[],"viewSettings":{"overrideStyles":settings.override_styles,"normalColor":settings.normal_color,"warningColor":settings.warning_color,"dangerColor":settings.danger_color},"automation":{"enabledAutomations":false,"enabledOscIn":false,"triggers":[],"automations":{}}}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/// Validate before publication, preserve existing output unless explicitly allowed.
|
||||||
|
pub fn write(
|
||||||
|
a: &Analysis,
|
||||||
|
input: &Path,
|
||||||
|
output: &Path,
|
||||||
|
neutral: bool,
|
||||||
|
overwrite: bool,
|
||||||
|
cancel: &AtomicBool,
|
||||||
|
) -> Result<()> {
|
||||||
|
write_with_settings(
|
||||||
|
a,
|
||||||
|
input,
|
||||||
|
output,
|
||||||
|
neutral,
|
||||||
|
overwrite,
|
||||||
|
cancel,
|
||||||
|
&OntimeSettings::default(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_with_settings(
|
||||||
|
a: &Analysis,
|
||||||
|
input: &Path,
|
||||||
|
output: &Path,
|
||||||
|
neutral: bool,
|
||||||
|
overwrite: bool,
|
||||||
|
cancel: &AtomicBool,
|
||||||
|
settings: &OntimeSettings,
|
||||||
|
) -> Result<()> {
|
||||||
|
ensure!(
|
||||||
|
a.completed_stage == 4 && a.diagnostics.is_empty(),
|
||||||
|
"Resolve all diagnostics before exporting"
|
||||||
|
);
|
||||||
|
let r = a
|
||||||
|
.rundown
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("No complete rundown"))?;
|
||||||
|
ensure!(validate(r).is_empty(), "Rundown failed validation");
|
||||||
|
ensure!(
|
||||||
|
input.canonicalize()?
|
||||||
|
!= output
|
||||||
|
.canonicalize()
|
||||||
|
.unwrap_or_else(|_| output.to_path_buf()),
|
||||||
|
"Output must not replace the source document"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
!output.exists() || overwrite,
|
||||||
|
"Output exists; use --overwrite or choose another path"
|
||||||
|
);
|
||||||
|
let extension = output
|
||||||
|
.extension()
|
||||||
|
.and_then(|extension| extension.to_str())
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_ascii_lowercase();
|
||||||
|
ensure!(
|
||||||
|
matches!(extension.as_str(), "json" | "xlsx"),
|
||||||
|
"Output must use .json or .xlsx"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
!(neutral && extension == "xlsx"),
|
||||||
|
"Neutral IR export requires a .json output"
|
||||||
|
);
|
||||||
|
let parent = output
|
||||||
|
.parent()
|
||||||
|
.filter(|p| !p.as_os_str().is_empty())
|
||||||
|
.unwrap_or(Path::new("."));
|
||||||
|
let mut temp = tempfile::NamedTempFile::new_in(parent)?;
|
||||||
|
if extension == "xlsx" {
|
||||||
|
temp.write_all(&xlsx(r)?)?;
|
||||||
|
} else {
|
||||||
|
let value = if neutral {
|
||||||
|
serde_json::to_value(r)?
|
||||||
|
} else {
|
||||||
|
ontime_with_settings(r, settings)?
|
||||||
|
};
|
||||||
|
serde_json::to_writer_pretty(&mut temp, &value)?;
|
||||||
|
writeln!(temp)?;
|
||||||
|
}
|
||||||
|
temp.as_file().sync_all()?;
|
||||||
|
if cancel.load(Ordering::Relaxed) {
|
||||||
|
bail!("Cancelled; no output published");
|
||||||
|
}
|
||||||
|
if overwrite {
|
||||||
|
temp.persist(output)?;
|
||||||
|
} else {
|
||||||
|
temp.persist_noclobber(output)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,10 @@
|
||||||
|
//! Local rundown conversion in five explicit stages, with provenance and blocking diagnostics.
|
||||||
|
pub mod detect;
|
||||||
|
pub mod export;
|
||||||
|
#[cfg(feature = "desktop")]
|
||||||
|
pub mod gui;
|
||||||
|
pub mod model;
|
||||||
|
pub mod pipeline;
|
||||||
|
pub mod reader;
|
||||||
|
pub mod resolution;
|
||||||
|
pub mod time;
|
||||||
|
|
@ -0,0 +1,133 @@
|
||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use clap::{Parser, ValueEnum};
|
||||||
|
use rundown_converter::{export, model::Profile, pipeline, reader};
|
||||||
|
use std::{path::PathBuf, sync::atomic::AtomicBool};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, ValueEnum)]
|
||||||
|
enum Action {
|
||||||
|
Inspect,
|
||||||
|
Validate,
|
||||||
|
Convert,
|
||||||
|
}
|
||||||
|
#[derive(Parser)]
|
||||||
|
#[command(
|
||||||
|
version,
|
||||||
|
about = "Infer spreadsheet rundown columns, preserve schedule gaps, export Ontime JSON or XLSX"
|
||||||
|
)]
|
||||||
|
struct Args {
|
||||||
|
#[arg(value_enum)]
|
||||||
|
action: Action,
|
||||||
|
input: PathBuf,
|
||||||
|
/// Required for workbooks with multiple sheets; exact name.
|
||||||
|
#[arg(long)]
|
||||||
|
sheet: Option<String>,
|
||||||
|
/// JSON profile: explicit columns, units, row classifications and row corrections.
|
||||||
|
#[arg(long)]
|
||||||
|
profile: Option<PathBuf>,
|
||||||
|
/// Destination .json or Ontime-importable .xlsx file.
|
||||||
|
#[arg(short, long)]
|
||||||
|
output: Option<PathBuf>,
|
||||||
|
/// Export the neutral IR instead of an Ontime project.
|
||||||
|
#[arg(long)]
|
||||||
|
neutral: bool,
|
||||||
|
#[arg(long)]
|
||||||
|
overwrite: bool,
|
||||||
|
/// Print structured analysis including source-located diagnostics.
|
||||||
|
#[arg(long)]
|
||||||
|
json: bool,
|
||||||
|
}
|
||||||
|
fn run(args: Args) -> Result<bool> {
|
||||||
|
let tables = reader::read(&args.input)?;
|
||||||
|
if matches!(args.action, Action::Inspect) {
|
||||||
|
if args.json {
|
||||||
|
println!("{}", serde_json::to_string_pretty(&tables)?);
|
||||||
|
} else {
|
||||||
|
for t in tables {
|
||||||
|
println!(
|
||||||
|
"{}: {} rows, {} merged ranges",
|
||||||
|
t.name,
|
||||||
|
t.rows.len(),
|
||||||
|
t.merges.len()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
let table = if let Some(sheet) = args.sheet {
|
||||||
|
tables
|
||||||
|
.iter()
|
||||||
|
.find(|t| t.name == sheet)
|
||||||
|
.context("Sheet not found; use inspect to list exact names")?
|
||||||
|
} else if tables.len() == 1 {
|
||||||
|
&tables[0]
|
||||||
|
} else {
|
||||||
|
bail!(
|
||||||
|
"Select --sheet; available: {}",
|
||||||
|
tables
|
||||||
|
.iter()
|
||||||
|
.map(|t| t.name.as_str())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let profile: Profile = if let Some(p) = args.profile {
|
||||||
|
serde_json::from_slice(&std::fs::read(p)?)?
|
||||||
|
} else {
|
||||||
|
Profile::default()
|
||||||
|
};
|
||||||
|
let cancel = AtomicBool::new(false);
|
||||||
|
let analysis = pipeline::analyze(table, &profile, &cancel, |stage, msg| {
|
||||||
|
eprintln!("{stage}/5 {msg}")
|
||||||
|
});
|
||||||
|
if args.json {
|
||||||
|
println!("{}", serde_json::to_string_pretty(&analysis)?);
|
||||||
|
} else {
|
||||||
|
if let Some(map) = &analysis.mapping {
|
||||||
|
for item in &map.evidence {
|
||||||
|
println!("{item}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for d in &analysis.diagnostics {
|
||||||
|
let name = if d.code == "UNTIMED_ROW" {
|
||||||
|
"ROW WITHOUT A TIMING".into()
|
||||||
|
} else {
|
||||||
|
d.code.clone()
|
||||||
|
};
|
||||||
|
eprintln!("{name} — {}: {}", d.location, d.message);
|
||||||
|
}
|
||||||
|
if let Some(r) = &analysis.rundown {
|
||||||
|
println!("{} entries, {} untimed gaps", r.entries.len(), r.gaps.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !analysis.diagnostics.is_empty() {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
if matches!(args.action, Action::Convert) {
|
||||||
|
let output = args
|
||||||
|
.output
|
||||||
|
.context("convert requires --output; choose a new .ontime.json path")?;
|
||||||
|
eprintln!("5/5 Export validated rundown");
|
||||||
|
export::write_with_settings(
|
||||||
|
&analysis,
|
||||||
|
&args.input,
|
||||||
|
&output,
|
||||||
|
args.neutral,
|
||||||
|
args.overwrite,
|
||||||
|
&cancel,
|
||||||
|
&profile.ontime,
|
||||||
|
)?;
|
||||||
|
eprintln!("Created {}", output.display());
|
||||||
|
}
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
fn main() {
|
||||||
|
let code = match run(Args::parse()) {
|
||||||
|
Ok(true) => 0,
|
||||||
|
Ok(false) => 2,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("{e:#}");
|
||||||
|
1
|
||||||
|
}
|
||||||
|
};
|
||||||
|
std::process::exit(code);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,317 @@
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||||
|
pub struct Cell {
|
||||||
|
pub text: String,
|
||||||
|
pub numeric: bool,
|
||||||
|
pub time_style: bool,
|
||||||
|
pub formula: Option<String>,
|
||||||
|
}
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Merge {
|
||||||
|
pub first_row: usize,
|
||||||
|
pub last_row: usize,
|
||||||
|
pub first_col: usize,
|
||||||
|
pub last_col: usize,
|
||||||
|
}
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Table {
|
||||||
|
pub name: String,
|
||||||
|
pub rows: Vec<Vec<Cell>>,
|
||||||
|
pub merges: Vec<Merge>,
|
||||||
|
}
|
||||||
|
impl Table {
|
||||||
|
pub fn cell(&self, row: usize, col: usize) -> Cell {
|
||||||
|
self.rows
|
||||||
|
.get(row)
|
||||||
|
.and_then(|r| r.get(col))
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
pub fn merged_until(&self, row: usize, col: usize) -> usize {
|
||||||
|
self.merges
|
||||||
|
.iter()
|
||||||
|
.find(|m| m.first_row == row && m.first_col == col && m.last_col == col)
|
||||||
|
.map_or(row, |m| m.last_row)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Diagnostic {
|
||||||
|
pub stage: u8,
|
||||||
|
pub code: String,
|
||||||
|
pub location: String,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
impl Diagnostic {
|
||||||
|
pub fn new(
|
||||||
|
stage: u8,
|
||||||
|
code: &str,
|
||||||
|
location: impl Into<String>,
|
||||||
|
message: impl Into<String>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
stage,
|
||||||
|
code: code.into(),
|
||||||
|
location: location.into(),
|
||||||
|
message: message.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Optional distribution of one gap across adjacent, contiguous events.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(default, deny_unknown_fields)]
|
||||||
|
pub struct GapOptions {
|
||||||
|
pub distribute: bool,
|
||||||
|
pub count: usize,
|
||||||
|
/// previous inserts after each preceding event; following inserts before each following event.
|
||||||
|
pub direction: String,
|
||||||
|
pub title: String,
|
||||||
|
}
|
||||||
|
impl Default for GapOptions {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
distribute: false,
|
||||||
|
count: 2,
|
||||||
|
direction: "previous".into(),
|
||||||
|
title: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Project-level Ontime export preferences, separate from the neutral schedule IR.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(default, deny_unknown_fields)]
|
||||||
|
pub struct OntimeSettings {
|
||||||
|
pub override_styles: bool,
|
||||||
|
pub time_format: String,
|
||||||
|
pub language: String,
|
||||||
|
pub normal_color: String,
|
||||||
|
pub warning_color: String,
|
||||||
|
pub danger_color: String,
|
||||||
|
pub aux_timer_names: [String; 3],
|
||||||
|
}
|
||||||
|
impl Default for OntimeSettings {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
override_styles: true,
|
||||||
|
time_format: "24".into(),
|
||||||
|
language: "en".into(),
|
||||||
|
normal_color: "#ffffffcc".into(),
|
||||||
|
warning_color: "#ffa528".into(),
|
||||||
|
danger_color: "#ff7300".into(),
|
||||||
|
aux_timer_names: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||||
|
#[serde(default, deny_unknown_fields)]
|
||||||
|
pub struct Profile {
|
||||||
|
pub ontime: OntimeSettings,
|
||||||
|
/// One-based header row. Column letters are Excel-style, e.g. A or AB.
|
||||||
|
pub header_row: Option<usize>,
|
||||||
|
pub columns: BTreeMap<String, String>,
|
||||||
|
/// Column letter -> notes, metadata (Ontime custom field), or ignore.
|
||||||
|
pub column_usage: BTreeMap<String, String>,
|
||||||
|
pub expected_headers: BTreeMap<String, String>,
|
||||||
|
/// either (main title first), merge, merge_previous (carry primary title forward), notes, or metadata.
|
||||||
|
pub secondary_title_mode: Option<String>,
|
||||||
|
/// minutes, seconds, hh:mm, mm:ss, or excel.
|
||||||
|
pub duration_unit: Option<String>,
|
||||||
|
/// strict, minimum, maximum, median (upper median), sum, or margin (legacy split is accepted).
|
||||||
|
pub duration_mode: Option<String>,
|
||||||
|
/// Separator used by split mode. Escaped forms such as \\n and \\t are accepted.
|
||||||
|
pub duration_separator: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub duration_split: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub duration_add_margin: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub duration_margin: Option<String>,
|
||||||
|
/// Explicitly retain rows without times as notes on the preceding event.
|
||||||
|
pub untimed_as_notes: bool,
|
||||||
|
/// Try excluding rows with unresolved-content warnings, then validate again.
|
||||||
|
pub ignore_warnings: bool,
|
||||||
|
/// One-based source row -> event, gap, marker, note, or ignore.
|
||||||
|
pub row_kinds: BTreeMap<usize, String>,
|
||||||
|
/// One-based source row -> one-based split parts excluded independently.
|
||||||
|
#[serde(default)]
|
||||||
|
pub ignored_parts: BTreeMap<usize, std::collections::BTreeSet<usize>>,
|
||||||
|
/// Explicit title overrides; original source cells remain in the IR.
|
||||||
|
pub titles: BTreeMap<usize, String>,
|
||||||
|
/// Explicit start clock overrides (e.g. 09:30 or 09:30:00).
|
||||||
|
pub starts: BTreeMap<usize, String>,
|
||||||
|
/// Explicit end clock overrides (e.g. 10:15 or 10:15:00).
|
||||||
|
pub ends: BTreeMap<usize, String>,
|
||||||
|
/// Explicit duration overrides, expressed with units (e.g. 2 min).
|
||||||
|
pub durations: BTreeMap<usize, String>,
|
||||||
|
/// Exact gap key -> keep, extend_previous, add_to_next, or create_event.
|
||||||
|
pub gap_resolutions: BTreeMap<String, String>,
|
||||||
|
pub gap_options: BTreeMap<String, GapOptions>,
|
||||||
|
/// Fallback name for unnamed breaks; source and individual names take precedence.
|
||||||
|
pub default_break_name: String,
|
||||||
|
}
|
||||||
|
impl Profile {
|
||||||
|
pub fn margin_ms(&self) -> Option<i64> {
|
||||||
|
if !self.duration_add_margin {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
crate::time::duration(
|
||||||
|
&Cell {
|
||||||
|
text: self.duration_margin.clone()?,
|
||||||
|
..Cell::default()
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.filter(|value| *value > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn usage(&self, col: usize) -> Option<&str> {
|
||||||
|
self.column_usage
|
||||||
|
.iter()
|
||||||
|
.find(|(letter, _)| column_index(letter) == Some(col))
|
||||||
|
.map(|(_, usage)| usage.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Mapping {
|
||||||
|
pub header_row: usize,
|
||||||
|
pub start: usize,
|
||||||
|
/// The start column contains a complete start/end range in every timed cell.
|
||||||
|
#[serde(default)]
|
||||||
|
pub start_end: bool,
|
||||||
|
pub end: Option<usize>,
|
||||||
|
pub duration: Option<usize>,
|
||||||
|
pub title: usize,
|
||||||
|
#[serde(default)]
|
||||||
|
pub secondary_title: Option<usize>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub secondary_title_mode: Option<String>,
|
||||||
|
pub duration_unit: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub duration_mode: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub duration_separator: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub duration_split: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub duration_add_margin: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub duration_margin: Option<String>,
|
||||||
|
pub evidence: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub column_usage: BTreeMap<String, String>,
|
||||||
|
/// Source header labels for notes and metadata columns.
|
||||||
|
#[serde(default)]
|
||||||
|
pub column_labels: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct SourceRow {
|
||||||
|
pub row: usize,
|
||||||
|
pub cells: BTreeMap<String, Cell>,
|
||||||
|
}
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Entry {
|
||||||
|
/// Original gap resolution that generated this timer; it has no source row.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub gap_origin: Option<String>,
|
||||||
|
/// One-based position in the source duration split, stable when siblings are ignored.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub split_part: Option<usize>,
|
||||||
|
pub id: String,
|
||||||
|
pub kind: String,
|
||||||
|
pub title: String,
|
||||||
|
pub start_ms: i64,
|
||||||
|
pub end_ms: i64,
|
||||||
|
pub duration_ms: i64,
|
||||||
|
pub explicit_start: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub inferred_end: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub inferred_duration: bool,
|
||||||
|
pub source_rows: Vec<SourceRow>,
|
||||||
|
pub decisions: Vec<String>,
|
||||||
|
}
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Gap {
|
||||||
|
/// Original interval controlling a redistributed untimed gap.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub origin: Option<String>,
|
||||||
|
pub after_row: Option<usize>,
|
||||||
|
pub before_row: Option<usize>,
|
||||||
|
pub start_ms: Option<i64>,
|
||||||
|
pub end_ms: Option<i64>,
|
||||||
|
pub title: String,
|
||||||
|
pub source_rows: Vec<SourceRow>,
|
||||||
|
pub display_timer: bool,
|
||||||
|
}
|
||||||
|
impl Gap {
|
||||||
|
pub fn key(&self) -> String {
|
||||||
|
if let Some(origin) = &self.origin {
|
||||||
|
return origin.clone();
|
||||||
|
}
|
||||||
|
format!(
|
||||||
|
"{:?}:{:?}:{:?}:{:?}",
|
||||||
|
self.after_row, self.before_row, self.start_ms, self.end_ms
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Rundown {
|
||||||
|
pub schema_version: u32,
|
||||||
|
pub title: String,
|
||||||
|
pub mapping: Mapping,
|
||||||
|
pub entries: Vec<Entry>,
|
||||||
|
/// Excluded virtual entries retained for review and restoration, never exported.
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub ignored_entries: Vec<Entry>,
|
||||||
|
pub gaps: Vec<Gap>,
|
||||||
|
/// Original intervals absorbed into event timing, retained for review/undo.
|
||||||
|
#[serde(default)]
|
||||||
|
pub resolved_gaps: Vec<Gap>,
|
||||||
|
pub decisions: Vec<String>,
|
||||||
|
}
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Analysis {
|
||||||
|
pub sheet: String,
|
||||||
|
pub completed_stage: u8,
|
||||||
|
pub mapping: Option<Mapping>,
|
||||||
|
pub rundown: Option<Rundown>,
|
||||||
|
pub diagnostics: Vec<Diagnostic>,
|
||||||
|
/// Derived exclusions; never persisted as manual row decisions.
|
||||||
|
#[serde(default)]
|
||||||
|
pub automatically_ignored_rows: Vec<usize>,
|
||||||
|
}
|
||||||
|
pub fn column_name(mut col: usize) -> String {
|
||||||
|
let mut s = String::new();
|
||||||
|
loop {
|
||||||
|
s.insert(0, (b'A' + (col % 26) as u8) as char);
|
||||||
|
if col < 26 {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
col = col / 26 - 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn column_index(s: &str) -> Option<usize> {
|
||||||
|
if s.is_empty() || !s.bytes().all(|b| b.is_ascii_alphabetic()) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut n = 0usize;
|
||||||
|
for b in s.bytes() {
|
||||||
|
n = n
|
||||||
|
.checked_mul(26)?
|
||||||
|
.checked_add((b.to_ascii_uppercase() - b'A' + 1) as usize)?;
|
||||||
|
}
|
||||||
|
(n <= 16384).then_some(n - 1)
|
||||||
|
}
|
||||||
|
pub fn source_row(table: &Table, row: usize) -> SourceRow {
|
||||||
|
SourceRow {
|
||||||
|
row: row + 1,
|
||||||
|
cells: table.rows[row]
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, c)| !c.text.is_empty() || c.formula.is_some())
|
||||||
|
.map(|(i, c)| (column_name(i), c.clone()))
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,494 @@
|
||||||
|
use crate::model::{Cell, Merge, Table, column_index};
|
||||||
|
use anyhow::{Context, Result, bail, ensure};
|
||||||
|
use roxmltree::Document;
|
||||||
|
use std::{collections::BTreeMap, fs::File, io::Read, path::Path};
|
||||||
|
use zip::ZipArchive;
|
||||||
|
|
||||||
|
const LIMIT: u64 = 32 * 1024 * 1024;
|
||||||
|
fn xml(zip: &mut ZipArchive<File>, name: &str) -> Result<String> {
|
||||||
|
let file = zip
|
||||||
|
.by_name(name)
|
||||||
|
.with_context(|| format!("Missing workbook part {name}"))?;
|
||||||
|
ensure!(
|
||||||
|
file.size() <= LIMIT,
|
||||||
|
"Workbook part {name} exceeds 32 MiB limit"
|
||||||
|
);
|
||||||
|
let mut text = String::new();
|
||||||
|
file.take(LIMIT + 1).read_to_string(&mut text)?;
|
||||||
|
ensure!(text.len() as u64 <= LIMIT, "Workbook part too large");
|
||||||
|
Ok(text)
|
||||||
|
}
|
||||||
|
fn value(node: roxmltree::Node<'_, '_>, tag: &str) -> String {
|
||||||
|
node.children()
|
||||||
|
.find(|n| n.has_tag_name(tag))
|
||||||
|
.and_then(|n| n.text())
|
||||||
|
.unwrap_or("")
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
fn rich(node: roxmltree::Node<'_, '_>) -> String {
|
||||||
|
node.descendants()
|
||||||
|
.filter(|n| n.has_tag_name("t"))
|
||||||
|
.filter_map(|n| n.text())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("")
|
||||||
|
}
|
||||||
|
fn coord(s: &str) -> Result<(usize, usize)> {
|
||||||
|
let split = s
|
||||||
|
.find(|c: char| c.is_ascii_digit())
|
||||||
|
.context("Missing cell row")?;
|
||||||
|
let col = column_index(&s[..split]).context("Invalid cell column")?;
|
||||||
|
let row: usize = s[split..].parse()?;
|
||||||
|
ensure!(
|
||||||
|
(1..=100_000).contains(&row),
|
||||||
|
"Cell row outside supported 1–100000 range"
|
||||||
|
);
|
||||||
|
Ok((row - 1, col))
|
||||||
|
}
|
||||||
|
/// Read XLSX or delimited UTF-8 CSV. Macros are never executed. Simple arithmetic
|
||||||
|
/// formulas that only reference cells on the same sheet are calculated locally.
|
||||||
|
pub fn read(path: &Path) -> Result<Vec<Table>> {
|
||||||
|
ensure!(
|
||||||
|
path.metadata()?.len() <= LIMIT,
|
||||||
|
"Input exceeds 32 MiB limit"
|
||||||
|
);
|
||||||
|
match path
|
||||||
|
.extension()
|
||||||
|
.and_then(|s| s.to_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_ascii_lowercase()
|
||||||
|
.as_str()
|
||||||
|
{
|
||||||
|
"xlsx" => xlsx(path),
|
||||||
|
"csv" | "tsv" => csv_table(path),
|
||||||
|
"xls" | "ods" => bail!(
|
||||||
|
"UNSUPPORTED_FORMAT: save a copy as XLSX or UTF-8 CSV; legacy XLS and ODS readers are not implemented yet"
|
||||||
|
),
|
||||||
|
"pdf" => bail!(
|
||||||
|
"PDF_REQUIRES_REVIEW: PDF extraction is a stretch goal; provide XLSX/CSV with separate tracks for simultaneous tasks"
|
||||||
|
),
|
||||||
|
_ => bail!("UNSUPPORTED_FORMAT: choose an XLSX or UTF-8 CSV/TSV rundown"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn csv_table(path: &Path) -> Result<Vec<Table>> {
|
||||||
|
let text = std::fs::read_to_string(path)?;
|
||||||
|
let text = text.trim_start_matches('\u{feff}');
|
||||||
|
let first = text.lines().next().unwrap_or("");
|
||||||
|
let delim = b",;\t"
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.max_by_key(|d| first.bytes().filter(|b| b == d).count())
|
||||||
|
.unwrap();
|
||||||
|
let mut reader = csv::ReaderBuilder::new()
|
||||||
|
.has_headers(false)
|
||||||
|
.flexible(true)
|
||||||
|
.delimiter(delim)
|
||||||
|
.from_reader(text.as_bytes());
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
for record in reader.records() {
|
||||||
|
let record = record?;
|
||||||
|
ensure!(
|
||||||
|
rows.len() < 100_000 && record.len() <= 16384,
|
||||||
|
"CSV dimensions exceed supported limits"
|
||||||
|
);
|
||||||
|
rows.push(
|
||||||
|
record
|
||||||
|
.iter()
|
||||||
|
.map(|s| Cell {
|
||||||
|
text: s.trim().into(),
|
||||||
|
..Cell::default()
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(vec![Table {
|
||||||
|
name: path
|
||||||
|
.file_stem()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_string_lossy()
|
||||||
|
.into(),
|
||||||
|
rows,
|
||||||
|
merges: vec![],
|
||||||
|
}])
|
||||||
|
}
|
||||||
|
fn xlsx(path: &Path) -> Result<Vec<Table>> {
|
||||||
|
let mut zip = ZipArchive::new(File::open(path)?)?;
|
||||||
|
ensure!(zip.len() <= 10_000, "Too many workbook parts");
|
||||||
|
let mut expanded_size = 0u64;
|
||||||
|
for i in 0..zip.len() {
|
||||||
|
expanded_size = expanded_size.saturating_add(zip.by_index(i)?.size());
|
||||||
|
}
|
||||||
|
ensure!(
|
||||||
|
expanded_size <= 4 * LIMIT,
|
||||||
|
"Workbook expands beyond 128 MiB limit"
|
||||||
|
);
|
||||||
|
let strings = if zip.file_names().any(|n| n == "xl/sharedStrings.xml") {
|
||||||
|
let text = xml(&mut zip, "xl/sharedStrings.xml")?;
|
||||||
|
Document::parse(&text)?
|
||||||
|
.descendants()
|
||||||
|
.filter(|n| n.has_tag_name("si"))
|
||||||
|
.map(rich)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
} else {
|
||||||
|
vec![]
|
||||||
|
};
|
||||||
|
let mut time_styles = vec![];
|
||||||
|
if zip.file_names().any(|n| n == "xl/styles.xml") {
|
||||||
|
let text = xml(&mut zip, "xl/styles.xml")?;
|
||||||
|
let doc = Document::parse(&text)?;
|
||||||
|
let formats: BTreeMap<_, _> = doc
|
||||||
|
.descendants()
|
||||||
|
.filter(|n| n.has_tag_name("numFmt"))
|
||||||
|
.filter_map(|n| {
|
||||||
|
Some((
|
||||||
|
n.attribute("numFmtId")?.parse::<u32>().ok()?,
|
||||||
|
n.attribute("formatCode")?.to_lowercase(),
|
||||||
|
))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if let Some(xfs) = doc.descendants().find(|n| n.has_tag_name("cellXfs")) {
|
||||||
|
for xf in xfs.children().filter(|n| n.has_tag_name("xf")) {
|
||||||
|
let id = xf.attribute("numFmtId").unwrap_or("0").parse::<u32>()?;
|
||||||
|
let custom = formats
|
||||||
|
.get(&id)
|
||||||
|
.is_some_and(|f| f.contains('h') || f.contains('s'));
|
||||||
|
time_styles.push((18..=21).contains(&id) || (45..=47).contains(&id) || custom);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let rel_text = xml(&mut zip, "xl/_rels/workbook.xml.rels")?;
|
||||||
|
let rel_doc = Document::parse(&rel_text)?;
|
||||||
|
let relationships: BTreeMap<_, _> = rel_doc
|
||||||
|
.descendants()
|
||||||
|
.filter(|n| n.has_tag_name("Relationship"))
|
||||||
|
.filter(|n| n.attribute("TargetMode") != Some("External"))
|
||||||
|
.filter_map(|n| Some((n.attribute("Id")?, n.attribute("Target")?)))
|
||||||
|
.collect();
|
||||||
|
let wb_text = xml(&mut zip, "xl/workbook.xml")?;
|
||||||
|
let wb = Document::parse(&wb_text)?;
|
||||||
|
let mut tables = vec![];
|
||||||
|
for sheet in wb.descendants().filter(|n| n.has_tag_name("sheet")) {
|
||||||
|
let id = sheet
|
||||||
|
.attributes()
|
||||||
|
.find(|a| a.name() == "id")
|
||||||
|
.context("Sheet relationship missing")?
|
||||||
|
.value();
|
||||||
|
let target = relationships.get(id).context("Sheet part missing")?;
|
||||||
|
ensure!(!target.contains(".."), "Unsupported relative workbook part");
|
||||||
|
let name = if target.starts_with('/') {
|
||||||
|
target.trim_start_matches('/').to_string()
|
||||||
|
} else {
|
||||||
|
format!("xl/{target}")
|
||||||
|
};
|
||||||
|
let text = xml(&mut zip, &name)?;
|
||||||
|
let doc = Document::parse(&text)?;
|
||||||
|
let mut table = Table {
|
||||||
|
name: sheet.attribute("name").unwrap_or("Sheet").into(),
|
||||||
|
rows: vec![],
|
||||||
|
merges: vec![],
|
||||||
|
};
|
||||||
|
let mut total_cells = 0usize;
|
||||||
|
for c in doc.descendants().filter(|n| n.has_tag_name("c")) {
|
||||||
|
let (row, col) = coord(c.attribute("r").context("Cell reference missing")?)?;
|
||||||
|
let raw = value(c, "v");
|
||||||
|
let kind = c.attribute("t").unwrap_or("n");
|
||||||
|
let text = match kind {
|
||||||
|
"s" => strings
|
||||||
|
.get(raw.parse::<usize>()?)
|
||||||
|
.context("Invalid shared string index")?
|
||||||
|
.clone(),
|
||||||
|
"inlineStr" => rich(c),
|
||||||
|
_ => raw,
|
||||||
|
};
|
||||||
|
let formula = c
|
||||||
|
.children()
|
||||||
|
.find(|n| n.has_tag_name("f"))
|
||||||
|
.map(|n| n.text().unwrap_or("").to_string());
|
||||||
|
if text.is_empty() && formula.is_none() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
table
|
||||||
|
.rows
|
||||||
|
.resize_with(table.rows.len().max(row + 1), Vec::new);
|
||||||
|
total_cells += (col + 1).saturating_sub(table.rows[row].len());
|
||||||
|
ensure!(
|
||||||
|
total_cells <= 1_000_000,
|
||||||
|
"Worksheet exceeds one million allocated cells"
|
||||||
|
);
|
||||||
|
let width = table.rows[row].len().max(col + 1);
|
||||||
|
table.rows[row].resize_with(width, Cell::default);
|
||||||
|
let style = c.attribute("s").unwrap_or("0").parse::<usize>()?;
|
||||||
|
table.rows[row][col] = Cell {
|
||||||
|
text: text.trim().into(),
|
||||||
|
numeric: kind == "n",
|
||||||
|
time_style: time_styles.get(style).copied().unwrap_or(false),
|
||||||
|
formula,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
for m in doc.descendants().filter(|n| n.has_tag_name("mergeCell")) {
|
||||||
|
let (first, last) = m
|
||||||
|
.attribute("ref")
|
||||||
|
.context("Missing merge reference")?
|
||||||
|
.split_once(':')
|
||||||
|
.context("Invalid merge range")?;
|
||||||
|
let (first_row, first_col) = coord(first)?;
|
||||||
|
let (last_row, last_col) = coord(last)?;
|
||||||
|
table.merges.push(Merge {
|
||||||
|
first_row,
|
||||||
|
last_row,
|
||||||
|
first_col,
|
||||||
|
last_col,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
calculate_simple_formulas(&mut table);
|
||||||
|
tables.push(table);
|
||||||
|
}
|
||||||
|
ensure!(!tables.is_empty(), "Workbook has no worksheets");
|
||||||
|
Ok(tables)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn calculate_simple_formulas(table: &mut Table) {
|
||||||
|
let formula_count = table
|
||||||
|
.rows
|
||||||
|
.iter()
|
||||||
|
.flatten()
|
||||||
|
.filter(|cell| cell.formula.is_some() && cell.text.is_empty())
|
||||||
|
.count();
|
||||||
|
for _ in 0..formula_count {
|
||||||
|
let mut calculated = Vec::new();
|
||||||
|
for (row, cells) in table.rows.iter().enumerate() {
|
||||||
|
for (col, cell) in cells.iter().enumerate() {
|
||||||
|
let Some(formula) = cell.formula.as_deref().filter(|_| cell.text.is_empty()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if let Some(value) = FormulaParser::new(formula, table).parse() {
|
||||||
|
calculated.push((row, col, value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if calculated.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
for (row, col, value) in calculated {
|
||||||
|
let cell = &mut table.rows[row][col];
|
||||||
|
cell.text = value.to_string();
|
||||||
|
cell.numeric = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FormulaParser<'a> {
|
||||||
|
input: &'a [u8],
|
||||||
|
position: usize,
|
||||||
|
table: &'a Table,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> FormulaParser<'a> {
|
||||||
|
fn new(formula: &'a str, table: &'a Table) -> Self {
|
||||||
|
Self {
|
||||||
|
input: formula.strip_prefix('=').unwrap_or(formula).as_bytes(),
|
||||||
|
position: 0,
|
||||||
|
table,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse(mut self) -> Option<f64> {
|
||||||
|
let value = self.expression()?;
|
||||||
|
self.space();
|
||||||
|
(self.position == self.input.len() && value.is_finite()).then_some(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expression(&mut self) -> Option<f64> {
|
||||||
|
let mut value = self.term()?;
|
||||||
|
loop {
|
||||||
|
self.space();
|
||||||
|
match self.peek() {
|
||||||
|
Some(b'+') => {
|
||||||
|
self.position += 1;
|
||||||
|
value += self.term()?;
|
||||||
|
}
|
||||||
|
Some(b'-') => {
|
||||||
|
self.position += 1;
|
||||||
|
value -= self.term()?;
|
||||||
|
}
|
||||||
|
_ => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn term(&mut self) -> Option<f64> {
|
||||||
|
let mut value = self.factor()?;
|
||||||
|
loop {
|
||||||
|
self.space();
|
||||||
|
match self.peek() {
|
||||||
|
Some(b'*') => {
|
||||||
|
self.position += 1;
|
||||||
|
value *= self.factor()?;
|
||||||
|
}
|
||||||
|
Some(b'/') => {
|
||||||
|
self.position += 1;
|
||||||
|
let divisor = self.factor()?;
|
||||||
|
if divisor == 0.0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
value /= divisor;
|
||||||
|
}
|
||||||
|
_ => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn factor(&mut self) -> Option<f64> {
|
||||||
|
self.space();
|
||||||
|
if self.consume(b'+') {
|
||||||
|
return self.factor();
|
||||||
|
}
|
||||||
|
if self.consume(b'-') {
|
||||||
|
return Some(-self.factor()?);
|
||||||
|
}
|
||||||
|
if self.consume(b'(') {
|
||||||
|
let value = self.expression()?;
|
||||||
|
self.space();
|
||||||
|
return self.consume(b')').then_some(value);
|
||||||
|
}
|
||||||
|
self.reference().or_else(|| self.number())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reference(&mut self) -> Option<f64> {
|
||||||
|
let start = self.position;
|
||||||
|
let value = (|| {
|
||||||
|
self.consume(b'$');
|
||||||
|
let letters = self.position;
|
||||||
|
while self.peek().is_some_and(|b| b.is_ascii_alphabetic()) {
|
||||||
|
self.position += 1;
|
||||||
|
}
|
||||||
|
(self.position > letters).then_some(())?;
|
||||||
|
let column = std::str::from_utf8(&self.input[letters..self.position]).ok()?;
|
||||||
|
self.consume(b'$');
|
||||||
|
let digits = self.position;
|
||||||
|
while self.peek().is_some_and(|b| b.is_ascii_digit()) {
|
||||||
|
self.position += 1;
|
||||||
|
}
|
||||||
|
let row = std::str::from_utf8(&self.input[digits..self.position])
|
||||||
|
.ok()?
|
||||||
|
.parse::<usize>()
|
||||||
|
.ok()?
|
||||||
|
.checked_sub(1)?;
|
||||||
|
let column = column_index(column)?;
|
||||||
|
let cell = self.table.rows.get(row)?.get(column)?;
|
||||||
|
(cell.numeric && !cell.text.is_empty()).then_some(())?;
|
||||||
|
cell.text.parse().ok()
|
||||||
|
})();
|
||||||
|
if value.is_none() {
|
||||||
|
self.position = start;
|
||||||
|
}
|
||||||
|
value
|
||||||
|
}
|
||||||
|
|
||||||
|
fn number(&mut self) -> Option<f64> {
|
||||||
|
let start = self.position;
|
||||||
|
while self.peek().is_some_and(|b| b.is_ascii_digit()) {
|
||||||
|
self.position += 1;
|
||||||
|
}
|
||||||
|
if self.consume(b'.') {
|
||||||
|
while self.peek().is_some_and(|b| b.is_ascii_digit()) {
|
||||||
|
self.position += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.peek().is_some_and(|b| matches!(b, b'e' | b'E')) {
|
||||||
|
self.position += 1;
|
||||||
|
if self.peek().is_some_and(|b| matches!(b, b'+' | b'-')) {
|
||||||
|
self.position += 1;
|
||||||
|
}
|
||||||
|
let exponent = self.position;
|
||||||
|
while self.peek().is_some_and(|b| b.is_ascii_digit()) {
|
||||||
|
self.position += 1;
|
||||||
|
}
|
||||||
|
if exponent == self.position {
|
||||||
|
self.position = start;
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if start == self.position || &self.input[start..self.position] == b"." {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let value = std::str::from_utf8(&self.input[start..self.position])
|
||||||
|
.ok()?
|
||||||
|
.parse()
|
||||||
|
.ok();
|
||||||
|
if value.is_none() {
|
||||||
|
self.position = start;
|
||||||
|
}
|
||||||
|
value
|
||||||
|
}
|
||||||
|
|
||||||
|
fn space(&mut self) {
|
||||||
|
while self.peek().is_some_and(|byte| byte.is_ascii_whitespace()) {
|
||||||
|
self.position += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn consume(&mut self, expected: u8) -> bool {
|
||||||
|
if self.peek() == Some(expected) {
|
||||||
|
self.position += 1;
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn peek(&self) -> Option<u8> {
|
||||||
|
self.input.get(self.position).copied()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn numeric(text: &str) -> Cell {
|
||||||
|
Cell {
|
||||||
|
text: text.into(),
|
||||||
|
numeric: true,
|
||||||
|
..Cell::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn formula(text: &str) -> Cell {
|
||||||
|
Cell {
|
||||||
|
formula: Some(text.into()),
|
||||||
|
..Cell::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn calculates_bounded_arithmetic_and_formula_dependencies() {
|
||||||
|
let mut table = Table {
|
||||||
|
name: "Formula".into(),
|
||||||
|
rows: vec![vec![
|
||||||
|
numeric("0.5"),
|
||||||
|
numeric("0.75"),
|
||||||
|
formula("=$B$1-A1"),
|
||||||
|
formula("C1 * 2"),
|
||||||
|
]],
|
||||||
|
merges: vec![],
|
||||||
|
};
|
||||||
|
calculate_simple_formulas(&mut table);
|
||||||
|
assert_eq!(table.rows[0][2].text, "0.25");
|
||||||
|
assert_eq!(table.rows[0][3].text, "0.5");
|
||||||
|
assert!(table.rows[0][2].numeric);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn leaves_functions_and_cycles_for_a_spreadsheet_application() {
|
||||||
|
let mut table = Table {
|
||||||
|
name: "Formula".into(),
|
||||||
|
rows: vec![vec![formula("SUM(B1:C1)"), formula("A1"), numeric("1")]],
|
||||||
|
merges: vec![],
|
||||||
|
};
|
||||||
|
calculate_simple_formulas(&mut table);
|
||||||
|
assert!(table.rows[0][0].text.is_empty());
|
||||||
|
assert!(table.rows[0][1].text.is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,230 @@
|
||||||
|
//! Portable clarification profiles and exact-sheet remembered resolutions.
|
||||||
|
use crate::{
|
||||||
|
detect,
|
||||||
|
model::{Profile, Table, column_name},
|
||||||
|
};
|
||||||
|
use anyhow::{Result, ensure};
|
||||||
|
use std::{
|
||||||
|
io::Write,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn directory() -> Option<PathBuf> {
|
||||||
|
directories::ProjectDirs::from("org", "beffroi", "rundown-converter")
|
||||||
|
.map(|p| p.config_dir().join("resolutions"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Include all cells, formats, formulas, merged ranges and the sheet name.
|
||||||
|
pub fn remembered_path(directory: &Path, table: &Table) -> Result<PathBuf> {
|
||||||
|
let bytes = serde_json::to_vec(table)?;
|
||||||
|
let id = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, &bytes);
|
||||||
|
Ok(directory.join(format!("{id}.json")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Match header text and order, independent of event content and sheet name.
|
||||||
|
pub fn column_path(directory: &Path, table: &Table, header_row: usize) -> Result<PathBuf> {
|
||||||
|
let row = table
|
||||||
|
.rows
|
||||||
|
.get(
|
||||||
|
header_row
|
||||||
|
.checked_sub(1)
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("Invalid header row"))?,
|
||||||
|
)
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("Header row is outside the sheet"))?;
|
||||||
|
let mut headers: Vec<_> = row
|
||||||
|
.iter()
|
||||||
|
.map(|cell| {
|
||||||
|
cell.text
|
||||||
|
.split_whitespace()
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(" ")
|
||||||
|
.to_lowercase()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
while headers.last().is_some_and(String::is_empty) {
|
||||||
|
headers.pop();
|
||||||
|
}
|
||||||
|
ensure!(
|
||||||
|
headers.iter().filter(|h| !h.is_empty()).count() >= 2,
|
||||||
|
"At least two named headers are needed to remember a column layout"
|
||||||
|
);
|
||||||
|
let id = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, &serde_json::to_vec(&headers)?);
|
||||||
|
Ok(directory.join("columns").join(format!("{id}.json")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve columns without requiring a consistent complete schedule.
|
||||||
|
pub fn column_profile(table: &Table, profile: &Profile) -> Result<Profile> {
|
||||||
|
let mapping = detect::infer(table, profile)
|
||||||
|
.map_err(|_| anyhow::anyhow!("Resolve column mapping issues before remembering columns"))?;
|
||||||
|
let mut saved = Profile {
|
||||||
|
header_row: Some(mapping.header_row),
|
||||||
|
..Profile::default()
|
||||||
|
};
|
||||||
|
saved.columns.insert(
|
||||||
|
if mapping.start_end {
|
||||||
|
"start_end"
|
||||||
|
} else {
|
||||||
|
"start"
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
column_name(mapping.start),
|
||||||
|
);
|
||||||
|
saved
|
||||||
|
.columns
|
||||||
|
.insert("title".into(), column_name(mapping.title));
|
||||||
|
for (role, column) in [
|
||||||
|
("end", mapping.end),
|
||||||
|
("duration", mapping.duration),
|
||||||
|
("secondary_title", mapping.secondary_title),
|
||||||
|
] {
|
||||||
|
if let Some(column) = column {
|
||||||
|
saved.columns.insert(role.into(), column_name(column));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
saved.column_usage = mapping.column_usage;
|
||||||
|
saved.expected_headers = mapping.column_labels;
|
||||||
|
saved.secondary_title_mode = mapping.secondary_title_mode;
|
||||||
|
saved.duration_unit = mapping.duration_unit;
|
||||||
|
saved.duration_mode = mapping.duration_mode;
|
||||||
|
saved.duration_separator = mapping.duration_separator;
|
||||||
|
saved.duration_split = mapping.duration_split;
|
||||||
|
saved.duration_add_margin = mapping.duration_add_margin;
|
||||||
|
saved.duration_margin = mapping.duration_margin;
|
||||||
|
Ok(saved)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find_columns(directory: &Path, table: &Table) -> Result<Option<(PathBuf, usize)>> {
|
||||||
|
let mut found = None;
|
||||||
|
for row in 1..=table.rows.len() {
|
||||||
|
if let Ok(path) = column_path(directory, table, row)
|
||||||
|
&& path.is_file()
|
||||||
|
{
|
||||||
|
ensure!(
|
||||||
|
found.is_none(),
|
||||||
|
"Several header rows match remembered layouts; select columns manually"
|
||||||
|
);
|
||||||
|
found = Some((path, row));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(found)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply only column decisions; never transfer row edits or project preferences.
|
||||||
|
pub fn apply_columns(current: &mut Profile, saved: Profile, header_row: usize) {
|
||||||
|
current.header_row = Some(header_row);
|
||||||
|
current.columns = saved.columns;
|
||||||
|
current.column_usage = saved.column_usage;
|
||||||
|
// Header signature already checked; expected_headers would reject harmless casing changes.
|
||||||
|
current.expected_headers.clear();
|
||||||
|
current.secondary_title_mode = saved.secondary_title_mode;
|
||||||
|
current.duration_unit = saved.duration_unit;
|
||||||
|
current.duration_mode = saved.duration_mode;
|
||||||
|
current.duration_separator = saved.duration_separator;
|
||||||
|
current.duration_split = saved.duration_split;
|
||||||
|
current.duration_add_margin = saved.duration_add_margin;
|
||||||
|
current.duration_margin = saved.duration_margin;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load(path: &Path) -> Result<Profile> {
|
||||||
|
Ok(serde_json::from_slice(&std::fs::read(path)?)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save(profile: &Profile, path: &Path, source: &Path, overwrite: bool) -> Result<()> {
|
||||||
|
ensure!(
|
||||||
|
path.extension().is_some_and(|e| e == "json"),
|
||||||
|
"Resolution files must use .json"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
source.canonicalize()? != path.canonicalize().unwrap_or_else(|_| path.to_path_buf()),
|
||||||
|
"A resolution must not replace the source document"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
!path.exists() || overwrite,
|
||||||
|
"Resolution exists; choose another name or explicitly enable replacement"
|
||||||
|
);
|
||||||
|
let parent = path
|
||||||
|
.parent()
|
||||||
|
.filter(|p| !p.as_os_str().is_empty())
|
||||||
|
.unwrap_or(Path::new("."));
|
||||||
|
let mut temp = tempfile::NamedTempFile::new_in(parent)?;
|
||||||
|
serde_json::to_writer_pretty(&mut temp, profile)?;
|
||||||
|
writeln!(temp)?;
|
||||||
|
temp.as_file().sync_all()?;
|
||||||
|
if overwrite {
|
||||||
|
temp.persist(path)?;
|
||||||
|
} else {
|
||||||
|
temp.persist_noclobber(path)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn column_matching_checks_order_and_handles_ambiguous_headers() {
|
||||||
|
use crate::model::Cell;
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let mut table = Table {
|
||||||
|
name: "One".into(),
|
||||||
|
rows: vec![
|
||||||
|
vec!["Start", "Duration", "Title"]
|
||||||
|
.into_iter()
|
||||||
|
.map(|s| Cell {
|
||||||
|
text: s.into(),
|
||||||
|
..Cell::default()
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
],
|
||||||
|
merges: vec![],
|
||||||
|
};
|
||||||
|
let path = column_path(dir.path(), &table, 1).unwrap();
|
||||||
|
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(&path, "{}").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
find_columns(dir.path(), &table).unwrap(),
|
||||||
|
Some((path.clone(), 1))
|
||||||
|
);
|
||||||
|
table.rows[0][0].text = " START ".into();
|
||||||
|
assert_eq!(column_path(dir.path(), &table, 1).unwrap(), path);
|
||||||
|
table.rows[0].swap(0, 1);
|
||||||
|
assert!(find_columns(dir.path(), &table).unwrap().is_none());
|
||||||
|
table.rows[0].swap(0, 1);
|
||||||
|
table.rows.push(table.rows[0].clone());
|
||||||
|
assert!(find_columns(dir.path(), &table).is_err());
|
||||||
|
assert!(column_path(dir.path(), &table, 0).is_err());
|
||||||
|
assert!(column_path(dir.path(), &table, 3).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn profiles_roundtrip_and_remember_only_identical_sheets() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let source = dir.path().join("source.json");
|
||||||
|
std::fs::write(&source, "original").unwrap();
|
||||||
|
let mut table = Table {
|
||||||
|
name: "Show".into(),
|
||||||
|
rows: vec![vec![Default::default()]],
|
||||||
|
merges: vec![],
|
||||||
|
};
|
||||||
|
let path = remembered_path(dir.path(), &table).unwrap();
|
||||||
|
let mut profile = Profile::default();
|
||||||
|
profile.titles.insert(2, "Opening".into());
|
||||||
|
profile.starts.insert(2, "09:00".into());
|
||||||
|
profile.ends.insert(2, "09:02".into());
|
||||||
|
profile.durations.insert(2, "2 min".into());
|
||||||
|
save(&profile, &path, &source, false).unwrap();
|
||||||
|
let loaded = load(&path).unwrap();
|
||||||
|
assert_eq!(loaded.titles[&2], "Opening");
|
||||||
|
assert_eq!(loaded.starts[&2], "09:00");
|
||||||
|
assert_eq!(loaded.ends[&2], "09:02");
|
||||||
|
assert_eq!(loaded.durations[&2], "2 min");
|
||||||
|
assert!(save(&profile, &path, &source, false).is_err());
|
||||||
|
save(&profile, &path, &source, true).unwrap();
|
||||||
|
assert!(save(&profile, &source, &source, true).is_err());
|
||||||
|
assert_eq!(std::fs::read_to_string(&source).unwrap(), "original");
|
||||||
|
table.rows[0][0].text = "changed".into();
|
||||||
|
assert_ne!(path, remembered_path(dir.path(), &table).unwrap());
|
||||||
|
table.name = "Other sheet".into();
|
||||||
|
assert!(!remembered_path(dir.path(), &table).unwrap().exists());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,401 @@
|
||||||
|
use crate::model::Cell;
|
||||||
|
use unicode_normalization::{UnicodeNormalization, char::is_combining_mark};
|
||||||
|
|
||||||
|
pub fn normalize(s: &str) -> String {
|
||||||
|
s.nfd()
|
||||||
|
.filter(|c| !is_combining_mark(*c))
|
||||||
|
.collect::<String>()
|
||||||
|
.to_lowercase()
|
||||||
|
}
|
||||||
|
fn millis(value: f64) -> Option<i64> {
|
||||||
|
(value.is_finite() && value.abs() <= 7.0 * 86_400_000.0).then(|| value.round() as i64)
|
||||||
|
}
|
||||||
|
/// Clock and range parsing never assumes a midnight rollover.
|
||||||
|
pub fn clock(cell: &Cell) -> Option<i64> {
|
||||||
|
if cell.numeric {
|
||||||
|
let v: f64 = cell.text.parse().ok()?;
|
||||||
|
return (0.0..1.0)
|
||||||
|
.contains(&v)
|
||||||
|
.then(|| millis(v * 86_400_000.0))
|
||||||
|
.flatten();
|
||||||
|
}
|
||||||
|
let mut s = normalize(cell.text.trim());
|
||||||
|
let am = s.ends_with("am");
|
||||||
|
let pm = s.ends_with("pm");
|
||||||
|
if am || pm {
|
||||||
|
s.truncate(s.len() - 2);
|
||||||
|
}
|
||||||
|
s = s.trim().replace('h', ":").replace(' ', "");
|
||||||
|
if s.ends_with(':') {
|
||||||
|
s.push_str("00");
|
||||||
|
}
|
||||||
|
let parts: Vec<_> = s.split(':').collect();
|
||||||
|
if !(2..=3).contains(&parts.len()) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut hours: i64 = parts[0].parse().ok()?;
|
||||||
|
let minutes: i64 = parts[1].parse().ok()?;
|
||||||
|
let seconds: i64 = if parts.len() == 3 {
|
||||||
|
parts[2].parse().ok()?
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
if am || pm {
|
||||||
|
if !(1..=12).contains(&hours) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
hours = hours % 12 + if pm { 12 } else { 0 };
|
||||||
|
}
|
||||||
|
if !(0..24).contains(&hours) || !(0..60).contains(&minutes) || !(0..60).contains(&seconds) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some((hours * 3600 + minutes * 60 + seconds) * 1000)
|
||||||
|
}
|
||||||
|
pub fn clock_range(cell: &Cell) -> Option<(i64, Option<i64>)> {
|
||||||
|
let s = cell.text.replace(['–', '—'], "-");
|
||||||
|
if let Some((a, b)) = s.split_once('-') {
|
||||||
|
let a = Cell {
|
||||||
|
text: a.trim().into(),
|
||||||
|
..Cell::default()
|
||||||
|
};
|
||||||
|
let b = Cell {
|
||||||
|
text: b.trim().into(),
|
||||||
|
..Cell::default()
|
||||||
|
};
|
||||||
|
return Some((clock(&a)?, Some(clock(&b)?)));
|
||||||
|
}
|
||||||
|
Some((clock(cell)?, None))
|
||||||
|
}
|
||||||
|
/// Ambiguous bare values and two-part times require a column-wide unit decision.
|
||||||
|
pub fn duration(cell: &Cell, unit: Option<&str>) -> Option<i64> {
|
||||||
|
let text = cell.text.trim();
|
||||||
|
if let Some(unsigned) = text.strip_prefix('-') {
|
||||||
|
let mut positive = cell.clone();
|
||||||
|
positive.text = unsigned.into();
|
||||||
|
return unsigned_duration(&positive, unit).map(|v| -v);
|
||||||
|
}
|
||||||
|
unsigned_duration(cell, unit)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct SelectedDurations {
|
||||||
|
/// One duration per event. More than one value creates virtual split entries.
|
||||||
|
pub events: Vec<i64>,
|
||||||
|
/// Untimed interval inserted after the event or split entries.
|
||||||
|
pub margin: i64,
|
||||||
|
/// Margin after each virtual entry when splitting.
|
||||||
|
pub margins: Vec<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn separator(value: Option<&str>) -> &str {
|
||||||
|
match value.unwrap_or("\\n") {
|
||||||
|
"\\n" => "\n",
|
||||||
|
"\\n\\n" => "\n\n",
|
||||||
|
"\\t" => "\t",
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn explicit_duration_values(text: &str, unit: Option<&str>) -> Vec<i64> {
|
||||||
|
let cell = Cell {
|
||||||
|
text: text.trim().into(),
|
||||||
|
..Cell::default()
|
||||||
|
};
|
||||||
|
if cell.text.is_empty() || clock_range(&cell).is_some_and(|(_, end)| end.is_some()) {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
if let Some(value) = duration(&cell, unit) {
|
||||||
|
return vec![value];
|
||||||
|
}
|
||||||
|
let normalized = normalize(&cell.text)
|
||||||
|
.replace("minutes", "m")
|
||||||
|
.replace("minute", "m")
|
||||||
|
.replace("mins", "m")
|
||||||
|
.replace("min", "m")
|
||||||
|
.replace("mn", "m")
|
||||||
|
.replace("secondes", "s")
|
||||||
|
.replace("seconds", "s")
|
||||||
|
.replace("seconde", "s")
|
||||||
|
.replace("second", "s")
|
||||||
|
.replace("secs", "s")
|
||||||
|
.replace("sec", "s");
|
||||||
|
let chars: Vec<char> = normalized.chars().collect();
|
||||||
|
let mut values = Vec::new();
|
||||||
|
let mut index = 0;
|
||||||
|
while index < chars.len() {
|
||||||
|
if !chars[index].is_ascii_digit() && chars[index] != '.' && chars[index] != ',' {
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let start = index;
|
||||||
|
while index < chars.len()
|
||||||
|
&& (chars[index].is_ascii_digit() || matches!(chars[index], '.' | ','))
|
||||||
|
{
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
let number: String = chars[start..index].iter().collect();
|
||||||
|
while index < chars.len() && chars[index].is_whitespace() {
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
let Some(&unit_char) = chars.get(index) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let factor = match unit_char {
|
||||||
|
'h' => 3_600_000.0,
|
||||||
|
'm' => 60_000.0,
|
||||||
|
's' => 1_000.0,
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
let Some(number) = number.replace(',', ".").parse::<f64>().ok() else {
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
index += 1;
|
||||||
|
let mut value = number * factor;
|
||||||
|
// Accept compact durations such as 1h30, while complete clock ranges were
|
||||||
|
// removed above and therefore cannot be mistaken for durations here.
|
||||||
|
if unit_char == 'h' {
|
||||||
|
let minute_start = index;
|
||||||
|
while index < chars.len() && chars[index].is_ascii_digit() {
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
if index > minute_start {
|
||||||
|
let minutes: String = chars[minute_start..index].iter().collect();
|
||||||
|
if let Ok(minutes) = minutes.parse::<f64>() {
|
||||||
|
value += minutes * 60_000.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(value) = millis(value) {
|
||||||
|
values.push(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
values
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract a duration from mixed text using an explicit, column-wide policy.
|
||||||
|
pub fn select_durations(
|
||||||
|
cell: &Cell,
|
||||||
|
unit: Option<&str>,
|
||||||
|
mode: Option<&str>,
|
||||||
|
split_separator: Option<&str>,
|
||||||
|
) -> Option<SelectedDurations> {
|
||||||
|
let mode = mode.unwrap_or("strict");
|
||||||
|
if mode == "strict" {
|
||||||
|
return duration(cell, unit).map(|value| SelectedDurations {
|
||||||
|
events: vec![value],
|
||||||
|
margin: 0,
|
||||||
|
margins: vec![],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if mode == "split" {
|
||||||
|
return select_duration_parts(cell, unit, Some("sum"), true, None, split_separator);
|
||||||
|
}
|
||||||
|
let groups: Vec<Vec<i64>> = cell
|
||||||
|
.text
|
||||||
|
.split(separator(split_separator))
|
||||||
|
.flat_map(|part| part.lines())
|
||||||
|
.map(|part| explicit_duration_values(part, unit))
|
||||||
|
.filter(|values| !values.is_empty())
|
||||||
|
.collect();
|
||||||
|
let largest = groups.iter().map(Vec::len).max()?;
|
||||||
|
// A one-value summary followed by a detailed “25 min + 5 min” line is an
|
||||||
|
// alternative expression of the same duration, not three independent values.
|
||||||
|
let preferred: Vec<Vec<i64>> = groups
|
||||||
|
.into_iter()
|
||||||
|
.filter(|values| values.len() == largest)
|
||||||
|
.collect();
|
||||||
|
let values: Vec<i64> = preferred.iter().flatten().copied().collect();
|
||||||
|
let selected = match mode {
|
||||||
|
"minimum" => SelectedDurations {
|
||||||
|
events: vec![*values.iter().min()?],
|
||||||
|
margin: 0,
|
||||||
|
margins: vec![],
|
||||||
|
},
|
||||||
|
"maximum" => SelectedDurations {
|
||||||
|
events: vec![*values.iter().max()?],
|
||||||
|
margin: 0,
|
||||||
|
margins: vec![],
|
||||||
|
},
|
||||||
|
"median" => {
|
||||||
|
let mut sorted = values;
|
||||||
|
sorted.sort_unstable();
|
||||||
|
let middle = sorted.len() / 2;
|
||||||
|
// Upper median: retain a source value, choosing the higher middle
|
||||||
|
// duration when there are an even number of values.
|
||||||
|
let value = sorted[middle];
|
||||||
|
SelectedDurations {
|
||||||
|
events: vec![value],
|
||||||
|
margin: 0,
|
||||||
|
margins: vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"sum" => SelectedDurations {
|
||||||
|
events: vec![values.iter().sum()],
|
||||||
|
margin: 0,
|
||||||
|
margins: vec![],
|
||||||
|
},
|
||||||
|
"margin" => {
|
||||||
|
let mut event = 0;
|
||||||
|
let mut margin = 0;
|
||||||
|
for group in preferred {
|
||||||
|
let maximum = *group.iter().max()?;
|
||||||
|
event += maximum;
|
||||||
|
margin += group.iter().sum::<i64>() - maximum;
|
||||||
|
}
|
||||||
|
SelectedDurations {
|
||||||
|
events: vec![event],
|
||||||
|
margin,
|
||||||
|
margins: vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
(!selected.events.is_empty()).then_some(selected)
|
||||||
|
}
|
||||||
|
/// Apply the selected handling independently to each separated entry.
|
||||||
|
pub fn select_duration_parts(
|
||||||
|
cell: &Cell,
|
||||||
|
unit: Option<&str>,
|
||||||
|
mode: Option<&str>,
|
||||||
|
split: bool,
|
||||||
|
margin_ms: Option<i64>,
|
||||||
|
split_separator: Option<&str>,
|
||||||
|
) -> Option<SelectedDurations> {
|
||||||
|
let legacy = mode == Some("split");
|
||||||
|
let mode = if legacy { Some("sum") } else { mode };
|
||||||
|
let select = |cell: &Cell| -> Option<SelectedDurations> {
|
||||||
|
let mut selected = select_durations(cell, unit, mode, None)?;
|
||||||
|
if let Some(margin) = margin_ms {
|
||||||
|
selected.margin = margin;
|
||||||
|
}
|
||||||
|
Some(selected)
|
||||||
|
};
|
||||||
|
if !split && !legacy {
|
||||||
|
return select(cell);
|
||||||
|
}
|
||||||
|
let separator = separator(split_separator);
|
||||||
|
if separator.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut result = SelectedDurations {
|
||||||
|
events: vec![],
|
||||||
|
margin: 0,
|
||||||
|
margins: vec![],
|
||||||
|
};
|
||||||
|
for part in cell.text.split(separator) {
|
||||||
|
if part.trim().is_empty()
|
||||||
|
|| clock_range(&Cell {
|
||||||
|
text: part.trim().into(),
|
||||||
|
..Cell::default()
|
||||||
|
})
|
||||||
|
.is_some_and(|(_, end)| end.is_some())
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let part = Cell {
|
||||||
|
text: part.into(),
|
||||||
|
..cell.clone()
|
||||||
|
};
|
||||||
|
let selected = select(&part)?;
|
||||||
|
result.events.extend(selected.events);
|
||||||
|
result.margins.push(selected.margin);
|
||||||
|
result.margin += selected.margin;
|
||||||
|
}
|
||||||
|
(!result.events.is_empty()).then_some(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unsigned_duration(cell: &Cell, unit: Option<&str>) -> Option<i64> {
|
||||||
|
let mut s = normalize(cell.text.trim()).replace(',', ".");
|
||||||
|
if cell.numeric && cell.time_style {
|
||||||
|
// Excel may serialize day fractions with a negative exponent, e.g. 6.94E-3.
|
||||||
|
return millis(s.parse::<f64>().ok()? * 86_400_000.0);
|
||||||
|
}
|
||||||
|
if cell.text.contains('-') {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if s.contains(':') {
|
||||||
|
let parts = s
|
||||||
|
.split(':')
|
||||||
|
.map(str::parse::<f64>)
|
||||||
|
.collect::<Result<Vec<_>, _>>()
|
||||||
|
.ok()?;
|
||||||
|
if parts.len() == 3 && parts[1].abs() < 60.0 && parts[2].abs() < 60.0 {
|
||||||
|
return millis((parts[0] * 3600.0 + parts[1] * 60.0 + parts[2]) * 1000.0);
|
||||||
|
}
|
||||||
|
if parts.len() == 2 && parts[1].abs() < 60.0 {
|
||||||
|
return match unit {
|
||||||
|
Some("hh:mm") => millis((parts[0] * 3600.0 + parts[1] * 60.0) * 1000.0),
|
||||||
|
Some("mm:ss") => millis((parts[0] * 60.0 + parts[1]) * 1000.0),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
for (from, to) in [
|
||||||
|
("minutes", "m"),
|
||||||
|
("minute", "m"),
|
||||||
|
("mins", "m"),
|
||||||
|
("min", "m"),
|
||||||
|
("mn", "m"),
|
||||||
|
("secondes", "s"),
|
||||||
|
("seconds", "s"),
|
||||||
|
("seconde", "s"),
|
||||||
|
("second", "s"),
|
||||||
|
("secs", "s"),
|
||||||
|
("sec", "s"),
|
||||||
|
("heures", "h"),
|
||||||
|
("heure", "h"),
|
||||||
|
("hours", "h"),
|
||||||
|
("hour", "h"),
|
||||||
|
] {
|
||||||
|
s = s.replace(from, to);
|
||||||
|
}
|
||||||
|
s = s.replace([' ', '\u{a0}'], "");
|
||||||
|
if s.chars().any(|c| matches!(c, 'h' | 'm' | 's')) {
|
||||||
|
let mut number = String::new();
|
||||||
|
let mut total = 0.0;
|
||||||
|
let mut last = ' ';
|
||||||
|
for c in s.chars() {
|
||||||
|
if c.is_ascii_digit() || c == '.' || (c == '-' && number.is_empty()) {
|
||||||
|
number.push(c);
|
||||||
|
} else {
|
||||||
|
let factor = match c {
|
||||||
|
'h' => 3600.0,
|
||||||
|
'm' => 60.0,
|
||||||
|
's' => 1.0,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
total += number.parse::<f64>().ok()? * factor;
|
||||||
|
number.clear();
|
||||||
|
last = c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !number.is_empty() {
|
||||||
|
if last != 'h' {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
total += number.parse::<f64>().ok()? * 60.0;
|
||||||
|
}
|
||||||
|
return millis(total * 1000.0);
|
||||||
|
}
|
||||||
|
let v = s.parse::<f64>().ok()?;
|
||||||
|
millis(
|
||||||
|
v * match unit {
|
||||||
|
Some("minutes") => 60_000.0,
|
||||||
|
Some("seconds") => 1000.0,
|
||||||
|
Some("excel") => 86_400_000.0,
|
||||||
|
_ => return None,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
pub fn display(ms: i64) -> String {
|
||||||
|
let sec = ms.abs() / 1000;
|
||||||
|
format!(
|
||||||
|
"{}{:02}:{:02}:{:02}",
|
||||||
|
if ms < 0 { "-" } else { "" },
|
||||||
|
sec / 3600,
|
||||||
|
sec / 60 % 60,
|
||||||
|
sec % 60
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,149 @@
|
||||||
|
use std::process::Command;
|
||||||
|
fn cli() -> Command {
|
||||||
|
Command::new(env!("CARGO_BIN_EXE_rundown-converter"))
|
||||||
|
}
|
||||||
|
fn sample() -> std::path::PathBuf {
|
||||||
|
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/lunch.csv")
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn inspect_validate_convert_and_exit_codes() {
|
||||||
|
let inspect = cli()
|
||||||
|
.args(["inspect", sample().to_str().unwrap(), "--json"])
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(inspect.status.success());
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::from_slice::<serde_json::Value>(&inspect.stdout).unwrap()[0]["name"],
|
||||||
|
"lunch"
|
||||||
|
);
|
||||||
|
let validate = cli()
|
||||||
|
.args(["validate", sample().to_str().unwrap(), "--json"])
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(validate.status.success());
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let output = dir.path().join("show.json");
|
||||||
|
let result = cli()
|
||||||
|
.arg("convert")
|
||||||
|
.arg(sample())
|
||||||
|
.arg("--output")
|
||||||
|
.arg(&output)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(result.status.success(), "{:?}", result);
|
||||||
|
let spreadsheet = dir.path().join("show.xlsx");
|
||||||
|
let result = cli()
|
||||||
|
.arg("convert")
|
||||||
|
.arg(sample())
|
||||||
|
.arg("--output")
|
||||||
|
.arg(&spreadsheet)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(result.status.success(), "{:?}", result);
|
||||||
|
assert!(std::fs::read(spreadsheet).unwrap().starts_with(b"PK"));
|
||||||
|
let result = cli()
|
||||||
|
.arg("convert")
|
||||||
|
.arg(sample())
|
||||||
|
.arg("--output")
|
||||||
|
.arg(&output)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(result.status.code(), Some(1));
|
||||||
|
let result = cli()
|
||||||
|
.arg("convert")
|
||||||
|
.arg(sample())
|
||||||
|
.arg("--output")
|
||||||
|
.arg(&output)
|
||||||
|
.args(["--overwrite", "--neutral"])
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(result.status.success());
|
||||||
|
let invalid = dir.path().join("bad.csv");
|
||||||
|
std::fs::write(&invalid, "Start,Duration,Title\n09:00,,Unknown\n").unwrap();
|
||||||
|
let result = cli().arg("validate").arg(invalid).output().unwrap();
|
||||||
|
assert_eq!(result.status.code(), Some(2));
|
||||||
|
assert!(String::from_utf8_lossy(&result.stderr).contains("MISSING_DURATION"));
|
||||||
|
assert!(
|
||||||
|
!cli()
|
||||||
|
.args(["validate", "/missing/file.xlsx"])
|
||||||
|
.output()
|
||||||
|
.unwrap()
|
||||||
|
.status
|
||||||
|
.success()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ontime_project_preferences_roundtrip_through_profile_and_export() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let output = dir.path().join("show.json");
|
||||||
|
let profile = dir.path().join("profile.json");
|
||||||
|
let settings = serde_json::json!({
|
||||||
|
"override_styles": false, "time_format": "12", "language": "fr",
|
||||||
|
"normal_color": "#112233cc", "warning_color": "#aabbcc", "danger_color": "#dd0011",
|
||||||
|
"aux_timer_names": ["Doors", "Break", "Stage"]
|
||||||
|
});
|
||||||
|
std::fs::write(
|
||||||
|
&profile,
|
||||||
|
serde_json::json!({"ontime": settings}).to_string(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let result = cli()
|
||||||
|
.arg("convert")
|
||||||
|
.arg(sample())
|
||||||
|
.arg("--output")
|
||||||
|
.arg(&output)
|
||||||
|
.arg("--profile")
|
||||||
|
.arg(&profile)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(result.status.success(), "{:?}", result);
|
||||||
|
let json: serde_json::Value = serde_json::from_slice(&std::fs::read(&output).unwrap()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
json["viewSettings"],
|
||||||
|
serde_json::json!({"overrideStyles": false,
|
||||||
|
"normalColor": "#112233cc", "warningColor": "#aabbcc", "dangerColor": "#dd0011"})
|
||||||
|
);
|
||||||
|
assert_eq!(json["settings"]["timeFormat"], "12");
|
||||||
|
assert_eq!(json["settings"]["language"], "fr");
|
||||||
|
assert_eq!(
|
||||||
|
json["settings"]["auxTimerNames"],
|
||||||
|
serde_json::json!(["Doors", "Break", "Stage"])
|
||||||
|
);
|
||||||
|
// Old profiles inherit the enabled stylesheet default.
|
||||||
|
std::fs::write(&profile, "{}").unwrap();
|
||||||
|
let result = cli()
|
||||||
|
.arg("convert")
|
||||||
|
.arg(sample())
|
||||||
|
.arg("--output")
|
||||||
|
.arg(&output)
|
||||||
|
.arg("--profile")
|
||||||
|
.arg(&profile)
|
||||||
|
.arg("--overwrite")
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(result.status.success());
|
||||||
|
let json: serde_json::Value = serde_json::from_slice(&std::fs::read(&output).unwrap()).unwrap();
|
||||||
|
assert_eq!(json["viewSettings"]["overrideStyles"], true);
|
||||||
|
// Invalid export settings must not replace an existing output.
|
||||||
|
let original = std::fs::read(&output).unwrap();
|
||||||
|
for bad in [
|
||||||
|
serde_json::json!({"time_format":"bad"}),
|
||||||
|
serde_json::json!({"language":"bad"}),
|
||||||
|
serde_json::json!({"normal_color":"invalid"}),
|
||||||
|
] {
|
||||||
|
std::fs::write(&profile, serde_json::json!({"ontime": bad}).to_string()).unwrap();
|
||||||
|
let result = cli()
|
||||||
|
.arg("convert")
|
||||||
|
.arg(sample())
|
||||||
|
.arg("--output")
|
||||||
|
.arg(&output)
|
||||||
|
.arg("--profile")
|
||||||
|
.arg(&profile)
|
||||||
|
.arg("--overwrite")
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(!result.status.success());
|
||||||
|
assert_eq!(std::fs::read(&output).unwrap(), original);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
Heure,Durée,Déroulement,Intervenants,Notes
|
||||||
|
11h30,20 min,Présentation du matin,Équipe A,Diapositives
|
||||||
|
11h50,10 min,Questions,Modération,Micro salle
|
||||||
|
,,Déjeuner,,Pas de timer pendant la pause
|
||||||
|
13h30,15 min,Reprise,Équipe B,Heure de reprise fixe
|
||||||
|
13h45,5 min,Conclusion,Modération,
|
||||||
|
|
|
@ -0,0 +1,92 @@
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"file": "stagetimer-1.xlsx",
|
||||||
|
"page": "https://stagetimer.io/blog/what-is-a-run-of-show/",
|
||||||
|
"url": "https://stagetimer.io/files/Stagetimer%20Run%20of%20Show%20Template.xlsx",
|
||||||
|
"sha256": "cb08277c0351bf87257c02b7532ecd5ce4a826e90cc0108b26eec1711a1caefd",
|
||||||
|
"bytes": 15805,
|
||||||
|
"retrieved": "2026-11-03",
|
||||||
|
"redistributed": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "attenditai-1.xlsx",
|
||||||
|
"page": "https://attenditai.com/templates/run-of-show-template",
|
||||||
|
"url": "https://attenditai.com/templates/run-of-show-template/run-of-show-template.xlsx",
|
||||||
|
"sha256": "43a93dae4472e4e1a2b0252cf75bc140795e878fbeffc99739e9a45fa5e49cab",
|
||||||
|
"bytes": 9633,
|
||||||
|
"retrieved": "2026-11-03",
|
||||||
|
"redistributed": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "joinways-1.xlsx",
|
||||||
|
"page": "https://joinways.app/solutions/run-of-show-example",
|
||||||
|
"url": "https://joinways.app/templates/run-of-show-template.xlsx",
|
||||||
|
"sha256": "ae994b42e97335ae49bcb5598b584f9b07d7477bd57142bc87cb6f0983b88f17",
|
||||||
|
"bytes": 8110,
|
||||||
|
"retrieved": "2026-11-03",
|
||||||
|
"redistributed": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "livefocus-1.xlsx",
|
||||||
|
"page": "https://livefocus.net/guides/event-run-of-show-template",
|
||||||
|
"url": "https://livefocus.net/downloads/livefocus-event-run-of-show-template.xlsx",
|
||||||
|
"sha256": "242fad6aabb36cbcd87834f10c3dd0efe6f5df8d983c901f923a7093c12d86fe",
|
||||||
|
"bytes": 13670,
|
||||||
|
"retrieved": "2026-11-03",
|
||||||
|
"redistributed": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "novus-1.xlsx",
|
||||||
|
"page": "https://examples.novusstreamsolutions.com/templates/planning/event-run-of-show-csv",
|
||||||
|
"url": "https://examples.novusstreamsolutions.com/files/templates/p6/event-run-of-show.xlsx",
|
||||||
|
"sha256": "cc750a250032a216fc9660119a9c595f394dd83b382b8ee419077a7d3b1c4ef2",
|
||||||
|
"bytes": 7229,
|
||||||
|
"retrieved": "2026-11-03",
|
||||||
|
"redistributed": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "events-authority-1.xlsx",
|
||||||
|
"page": "https://eventsauthority.com/corporate-event-planning/run-show-template/",
|
||||||
|
"url": "https://eventsauthority.com/downloads/sup_run_of_show_template/run-of-show.xlsx",
|
||||||
|
"sha256": "322de39018d1944c3a6c099ffd457d64338ad74012a775f13749bf67d99eee6d",
|
||||||
|
"bytes": 8174,
|
||||||
|
"retrieved": "2026-11-03",
|
||||||
|
"redistributed": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "arena-takeover-1.csv",
|
||||||
|
"page": "https://arenatakeover.com/resources.html",
|
||||||
|
"url": "https://arenatakeover.com/assets/downloads/run-of-show-template.csv",
|
||||||
|
"sha256": "bf068c3d03ce7d298b3301cb1e00ca28b2cf0418c06e2240ee9b118c48aff990",
|
||||||
|
"bytes": 1892,
|
||||||
|
"retrieved": "2026-11-03",
|
||||||
|
"redistributed": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "lasso-broadcast-1.csv",
|
||||||
|
"page": "https://www.lasso.io/rundown-templates/",
|
||||||
|
"url": "https://hi.lasso.io/hubfs/Rundown%20Templates/rundown-template-broadcast.csv",
|
||||||
|
"sha256": "b4dd8f5e6a28af6aba780e2bb8647b35ebaac59d8e6071da56ea3dc19d928890",
|
||||||
|
"bytes": 925,
|
||||||
|
"retrieved": "2026-11-03",
|
||||||
|
"redistributed": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "lasso-corporate-1.csv",
|
||||||
|
"page": "https://www.lasso.io/rundown-templates/",
|
||||||
|
"url": "https://hi.lasso.io/hubfs/Rundown%20Templates/rundown-template-corporate-run-of-show.csv",
|
||||||
|
"sha256": "d0b6767af5e5cb5b3c9fcd94509384016dd531d4633124311147a709c11bd72f",
|
||||||
|
"bytes": 1473,
|
||||||
|
"retrieved": "2026-11-03",
|
||||||
|
"redistributed": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "tavco-1.xlsx",
|
||||||
|
"page": "https://theavcompany.com/blog/run-of-show",
|
||||||
|
"url": "https://static1.squarespace.com/static/555c8055e4b0dc59ec841b7e/t/5a678909652dea7d6ea44dd0/1516734729883/TAVCO+Run+of+Show+Template.xlsx",
|
||||||
|
"sha256": "8b922ad110fe98962c428f1a7cb4c0a977f637aa42cb99929b6e7afdb30cf1b0",
|
||||||
|
"bytes": 113304,
|
||||||
|
"retrieved": "2026-11-03",
|
||||||
|
"redistributed": false
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
@ -0,0 +1,164 @@
|
||||||
|
//! User-supplied workbooks: exercise the actual XLSX reader and conversion pipeline.
|
||||||
|
use rundown_converter::{export, model::*, pipeline, reader};
|
||||||
|
use std::{path::PathBuf, sync::atomic::AtomicBool};
|
||||||
|
|
||||||
|
fn workbook(name: &str) -> Vec<Table> {
|
||||||
|
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
.join("../../rundowns")
|
||||||
|
.join(name);
|
||||||
|
reader::read(&path).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn analyze(table: &Table, profile: &Profile) -> Analysis {
|
||||||
|
pipeline::analyze(table, profile, &AtomicBool::new(false), |_, _| {})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn codes(analysis: &Analysis) -> Vec<&str> {
|
||||||
|
analysis
|
||||||
|
.diagnostics
|
||||||
|
.iter()
|
||||||
|
.map(|d| d.code.as_str())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn moebius_french_headers_and_excel_times_reach_schedule_validation() {
|
||||||
|
for (file, count, last_row, expected_codes) in [
|
||||||
|
(
|
||||||
|
"moebius-matin-pleniere-sante-environnement.xlsx",
|
||||||
|
26,
|
||||||
|
35,
|
||||||
|
vec!["INVALID_EVENT"],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"moebius-apres-midi-sante-mentale.xlsx",
|
||||||
|
20,
|
||||||
|
21,
|
||||||
|
vec!["INVALID_EVENT", "OVERLAP"],
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let tables = workbook(file);
|
||||||
|
assert_eq!(tables.len(), 1);
|
||||||
|
let analysis = analyze(&tables[0], &Profile::default());
|
||||||
|
let mapping = analysis.mapping.as_ref().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(
|
||||||
|
mapping.header_row,
|
||||||
|
mapping.start,
|
||||||
|
mapping.title,
|
||||||
|
mapping.duration
|
||||||
|
),
|
||||||
|
(1, 0, 1, Some(2)),
|
||||||
|
"{file}"
|
||||||
|
);
|
||||||
|
assert_eq!(codes(&analysis), expected_codes, "{file}");
|
||||||
|
assert!(
|
||||||
|
analysis
|
||||||
|
.diagnostics
|
||||||
|
.iter()
|
||||||
|
.all(|d| d.location == format!("Feuil1!row {last_row}"))
|
||||||
|
);
|
||||||
|
let rundown = analysis.rundown.unwrap();
|
||||||
|
assert_eq!(rundown.entries.len(), count);
|
||||||
|
let first = &rundown.entries[0];
|
||||||
|
assert_eq!(first.duration_ms, 15 * 60_000);
|
||||||
|
assert_eq!(first.end_ms - first.start_ms, first.duration_ms);
|
||||||
|
assert!(first.explicit_start);
|
||||||
|
assert!(!first.inferred_duration);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn competing_pleniere_timers_require_a_column_choice() {
|
||||||
|
let tables = workbook("pleniere-2.xlsx");
|
||||||
|
let analysis = analyze(&tables[0], &Profile::default());
|
||||||
|
assert!(analysis.mapping.is_none());
|
||||||
|
assert!(analysis.rundown.is_none());
|
||||||
|
assert_eq!(codes(&analysis), ["AMBIGUOUS_COLUMN"]);
|
||||||
|
assert!(analysis.diagnostics[0].message.contains("C, D"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn estivales_merged_blocks_preserve_notes_and_missing_final_duration() {
|
||||||
|
let tables = workbook("estivales-2025-plenieres.xlsx");
|
||||||
|
assert_eq!(tables.len(), 2);
|
||||||
|
let profile = Profile {
|
||||||
|
untimed_as_notes: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let opening = tables.iter().find(|t| t.name == "OUVERTURE").unwrap();
|
||||||
|
assert_eq!(opening.merges.len(), 9);
|
||||||
|
let analysis = analyze(opening, &profile);
|
||||||
|
assert_eq!(codes(&analysis), ["MISSING_DURATION"]);
|
||||||
|
let closing = tables.iter().find(|t| t.name == "CLOTURE").unwrap();
|
||||||
|
assert_eq!(closing.merges.len(), 2);
|
||||||
|
let analysis = analyze(closing, &profile);
|
||||||
|
assert!(
|
||||||
|
analysis.diagnostics.is_empty(),
|
||||||
|
"{:?}",
|
||||||
|
analysis.diagnostics
|
||||||
|
);
|
||||||
|
let rundown = analysis.rundown.unwrap();
|
||||||
|
assert_eq!(rundown.entries.len(), 5);
|
||||||
|
let output = export::ontime(&rundown).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
output["rundowns"]["default"]["order"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.len(),
|
||||||
|
5
|
||||||
|
);
|
||||||
|
let rows: Vec<_> = rundown
|
||||||
|
.entries
|
||||||
|
.iter()
|
||||||
|
.flat_map(|entry| entry.source_rows.iter().map(|source| source.row))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(rows, (2..=14).collect::<Vec<_>>());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gifav_parent_ranges_preserve_gaps_and_friday_overlap() {
|
||||||
|
let tables = workbook("gifav-2026-auditorium.xlsx");
|
||||||
|
assert_eq!(tables.len(), 2);
|
||||||
|
let profile = Profile {
|
||||||
|
columns: [
|
||||||
|
("start_end".into(), "A".into()),
|
||||||
|
("title".into(), "D".into()),
|
||||||
|
]
|
||||||
|
.into(),
|
||||||
|
column_usage: [("B".into(), "ignore".into()), ("E".into(), "notes".into())].into(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
for table in &tables {
|
||||||
|
let unmapped = analyze(table, &Profile::default());
|
||||||
|
assert_eq!(codes(&unmapped), ["MISSING_COLUMN"]);
|
||||||
|
let analysis = analyze(table, &profile);
|
||||||
|
assert!(analysis.mapping.as_ref().unwrap().start_end);
|
||||||
|
let thursday = table.name == "Jeudi 5nov26";
|
||||||
|
if thursday {
|
||||||
|
assert!(analysis.diagnostics.is_empty());
|
||||||
|
} else {
|
||||||
|
assert_eq!(table.name, "Vendredi 6nov26_Auditorium");
|
||||||
|
assert_eq!(codes(&analysis), ["OVERLAP"]);
|
||||||
|
assert_eq!(
|
||||||
|
analysis.diagnostics[0].location,
|
||||||
|
"Vendredi 6nov26_Auditorium!row 16"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let rundown = analysis.rundown.unwrap();
|
||||||
|
assert_eq!(rundown.entries.len(), if thursday { 11 } else { 10 });
|
||||||
|
assert_eq!(rundown.gaps.len(), 3);
|
||||||
|
assert!(rundown.gaps.iter().all(|gap| !gap.display_timer));
|
||||||
|
if thursday {
|
||||||
|
let output = export::ontime(&rundown).unwrap();
|
||||||
|
let entries = output["rundowns"]["default"]["entries"]
|
||||||
|
.as_object()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(entries.len(), 11);
|
||||||
|
for event in &rundown.entries {
|
||||||
|
assert_eq!(entries[&event.id]["timeStart"], event.start_ms);
|
||||||
|
assert_eq!(entries[&event.id]["duration"], event.duration_ms);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,38 @@
|
||||||
|
# Documentation
|
||||||
|
|
||||||
|
[Project portal](../README.md) · [Changelogs](changelogs.md) · [Development](development/README.md)
|
||||||
|
|
||||||
|
**[Read the full manuals →](https://books.dandaedre.com/manuals/)** — searchable mdBook documentation for this repository’s five tools and the independently maintained Canvas Pilot.
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
|
||||||
|
| Tool | Start here | Reference and background |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| PPTX Reporter | [Guide](pptx-reporter/README.md) · [Visual walkthrough](pptx-reporter/visual-guide.md) | [Report formats](pptx-reporter/report-formats.md) · [Windows quick start](pptx-reporter/windows-quickstart.txt) · [Portable quick start](pptx-reporter/portable-quickstart.txt) |
|
||||||
|
| Rundown Converter | [Guide](rundown-converter/README.md) · [Portable quick start](rundown-converter/portable-quickstart.txt) | [Corpus findings](rundown-converter/corpus.md) · [Plan](rundown-converter/plan.md) |
|
||||||
|
| Canvas Pilot | [Introduction](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/README.md) · [User guide](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/guide/README.md) | [Resolutions and cropping](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/resolutions.md) · [Device checks](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/device-check.md) · [Plan](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/plan.md) |
|
||||||
|
| PDF Presenter | [Repository](https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter) (access required; foundation only) | [Implementation plan](https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter/src/branch/main/docs/development/plan.md) · [CI](https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter/src/branch/main/docs/development/ci.md) |
|
||||||
|
| ASCII Names | [Guide](ascii-names/README.md) | [Changelog](ascii-names/changelog.md) |
|
||||||
|
| Document Exporter | [Guide](exporter/README.md) | [Changelog](exporter/changelog.md) |
|
||||||
|
| MPC-HC Companion | [Setup and development](../companion-modules/media-player-classic/README.md) | [Changelog](media-player-classic/changelog.md) |
|
||||||
|
|
||||||
|
## Shared resources
|
||||||
|
|
||||||
|
- **mdBook manuals:** [read online](https://books.dandaedre.com/manuals/) · [build, local preview and Jenkins publication](manuals/README.md).
|
||||||
|
|
||||||
|
- **Development:** [setup and checks](development/README.md), [CI and coverage](development/ci.md), [builds and portable releases](development/releases.md), [application artwork](development/releases.md#application-artwork).
|
||||||
|
- **File and device contracts:** [interface index](interfaces/README.md), including versioned examples and compatibility rules.
|
||||||
|
- **Starter files:** [Canvas Pilot catalog](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/templates/canvas-pilot/README.md), with Full HD and 4K base files in all nine exchange formats.
|
||||||
|
- **Release history:** [v0.7.0 notes](releases/v0.7.0.md), [v0.6.0 notes](releases/v0.6.0.md), [v0.3.0 notes](releases/v0.3.0.md) and [per-tool changelogs](changelogs.md).
|
||||||
|
- **Future work:** [ideas](../Ideas.md), [program task list](planning/program-task-list.md), [Flipper Link feasibility](planning/flipper-link.md).
|
||||||
|
|
||||||
|
## Where documentation belongs
|
||||||
|
|
||||||
|
Keep each tool's guide, plans, screenshots and changelog in its named folder.
|
||||||
|
Shared contributor instructions live in `development/`, historical release notes
|
||||||
|
in `releases/`, and cross-tool research in `planning/`. The Companion setup guide
|
||||||
|
stays beside its module source.
|
||||||
|
|
||||||
|
Keep save/export contracts and their versioned examples in `interfaces/`, and
|
||||||
|
reusable starter documents in `templates/`. These files are also used by tests;
|
||||||
|
update incoming links and code or packaging references whenever a document moves.
|
||||||
|
|
@ -0,0 +1,96 @@
|
||||||
|
# ASCII names
|
||||||
|
|
||||||
|
[Read the full manual →](https://books.dandaedre.com/manuals/ascii-names/)
|
||||||
|
|
||||||
|
[Documentation](../README.md) · [Changelog](changelog.md)
|
||||||
|
|
||||||
|
<img src="../../crates/ascii-names/assets/app-icon.png" width="96" alt="Application icon">
|
||||||
|
|
||||||
|
A small Rust application for cleaning filenames before using a folder on an
|
||||||
|
ASCII-only computer. Run it on your modern computer while the USB drive is plugged in.
|
||||||
|
It changes names in place; file contents are never opened or rewritten.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo run --locked -p ascii-names
|
||||||
|
```
|
||||||
|
|
||||||
|
Drop a folder into the window (or use **Choose folder**). **Preview** lists proposed
|
||||||
|
changes without writing anything. **Clean names** processes all files and subfolders.
|
||||||
|
**Stop** stops between entries; completed renames remain in place. The window keeps
|
||||||
|
the latest 200 messages. Drop one folder at a time.
|
||||||
|
|
||||||
|
The selected folder itself keeps its name, so selecting a drive's mount point is
|
||||||
|
safe. To clean a folder's own name too, select its parent. Symlinks and special
|
||||||
|
files are skipped, including links to other folders. Hidden files are included.
|
||||||
|
Nested mounted directories are treated as ordinary directories.
|
||||||
|
|
||||||
|
## Naming rules
|
||||||
|
|
||||||
|
- Accented Latin letters lose their accents, including decomposed macOS accents:
|
||||||
|
`Été.mov` → `Ete.mov`. Ligatures and common letters such as `œ`, `ß`, `ø`, `ł`
|
||||||
|
become `oe`, `ss`, `o`, `l`.
|
||||||
|
- Common Unicode quotes and dashes become ASCII punctuation. Other characters
|
||||||
|
without a supported equivalent become `_`. This is not transliteration of
|
||||||
|
every writing system: `日本.txt` becomes `__.txt`.
|
||||||
|
- ASCII control characters and `<>:"/\|?*` become `_` for filesystem compatibility.
|
||||||
|
Trailing dots/spaces are removed; empty names become `_`. Windows reserved
|
||||||
|
names such as `CON.txt` gain an underscore prefix.
|
||||||
|
- Names longer than 220 ASCII bytes are shortened, preserving short extensions.
|
||||||
|
- Existing destinations are never overwritten or merged. Collisions receive
|
||||||
|
`_1`, `_2`, etc., before a file's extension: `résumé.txt` becomes `resume_1.txt`
|
||||||
|
when `resume.txt` already exists. Directories get the suffix at the end.
|
||||||
|
|
||||||
|
Directories are handled inside out. Filesystem work runs on one worker, with
|
||||||
|
25 ms between rename attempts (at most about 40 renames per second). There are
|
||||||
|
no parallel scans, content copies, or per-file flushes. Eject the USB drive
|
||||||
|
normally afterward so the operating system finishes any buffered writes.
|
||||||
|
|
||||||
|
Keep the selected tree idle while running. Names referenced by playlists,
|
||||||
|
shortcuts, documents or projects are not updated inside those files. Preview
|
||||||
|
first when these references matter. There is no automatic undo. Read/rename
|
||||||
|
errors are reported and processing continues where possible; rerun after resolving
|
||||||
|
the reported cause. A failed directory rename can leave already-cleaned children.
|
||||||
|
|
||||||
|
## Command line
|
||||||
|
|
||||||
|
The same binary supports a folder argument, useful for terminal drag and drop:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo run --locked -p ascii-names -- /path/to/folder --dry-run
|
||||||
|
cargo run --locked -p ascii-names -- /path/to/folder
|
||||||
|
cargo run --locked -p ascii-names -- /path/to/folder --delay-ms 100
|
||||||
|
```
|
||||||
|
|
||||||
|
`--delay-ms` accepts 0–1000; the default is 25. Preview does not sleep.
|
||||||
|
The CLI prints every change and a summary, and exits nonzero on errors. Preview
|
||||||
|
paths show the traversal's intermediate paths before ancestor folders are renamed;
|
||||||
|
preview is not a saved plan, and cleanup scans again.
|
||||||
|
|
||||||
|
Build a standalone desktop binary with `cargo build --locked --release -p ascii-names`.
|
||||||
|
For a smaller CLI-only build, add `--no-default-features`. No FFprobe or other
|
||||||
|
external command is required. The desktop uses the same egui dependencies as the
|
||||||
|
other Rust tools. Linux/macOS use an atomic no-replace rename and Windows uses
|
||||||
|
MoveFileExW without replacement. Filesystems that do not support safe no-replace
|
||||||
|
renames produce an error; the tool never falls back to an overwriting rename.
|
||||||
|
|
||||||
|
The crate is included in workspace tests, Clippy, Rustdoc and coverage. Regression
|
||||||
|
tests cover collisions, nested directories, previews, cancellation, pacing,
|
||||||
|
symlinks, invalid UTF-8 filenames on Unix, and content preservation.
|
||||||
|
|
||||||
|
### FreeBSD CI hosts
|
||||||
|
|
||||||
|
FreeBSD uses `renameat2` with `AT_RENAME_NOREPLACE` when available. The symbol is
|
||||||
|
resolved at runtime, so older jail userlands (including FreeBSD 12) can still
|
||||||
|
build, launch and preview. Actual cleanup on those systems returns an actionable
|
||||||
|
unsupported-operation error without renaming anything. No overwriting fallback
|
||||||
|
is used. The kernel, jail userland and filesystem must all support the operation.
|
||||||
|
See the [FreeBSD API documentation change](https://lists.freebsd.org/archives/dev-commits-src-branches/2026-March/028297.html).
|
||||||
|
|
||||||
|
On a FreeBSD jail whose libc lacks `renameat2`, the rename integration tests
|
||||||
|
verify safe refusal and unchanged sources instead of executing their successful
|
||||||
|
rename assertions; this limitation is printed in CI output. Preview and name
|
||||||
|
conversion tests still run normally. Hosts exposing the API run the full rename
|
||||||
|
tests; unexpected filesystem/permission/kernel errors still fail them. Successful
|
||||||
|
renames and collision protection must also be tested on a supported host (Linux,
|
||||||
|
macOS, Windows, or a FreeBSD installation with the API). Jenkins prints its OS
|
||||||
|
version, and failing tests retain the underlying rename errors and CLI output.
|
||||||
|
|
@ -0,0 +1,27 @@
|
||||||
|
# ASCII Names changelog
|
||||||
|
|
||||||
|
[All changelogs](../changelogs.md)
|
||||||
|
|
||||||
|
## Unreleased
|
||||||
|
|
||||||
|
## v0.7.0 — 2026-11-14
|
||||||
|
|
||||||
|
- Update the shared Rust application version to 0.7.0; see the [release notes](../releases/v0.7.0.md).
|
||||||
|
|
||||||
|
- Add direct links to the published mdBook manual from the project README, tool guide and documentation indexes.
|
||||||
|
|
||||||
|
- Add an mdBook manual built from the existing guides, with local assets and downloads. Jenkins publishes successful main builds under `/mnt/books/manuals/`; staging, link validation and scoped publication have regression coverage.
|
||||||
|
|
||||||
|
- Use absolute Gitea main-branch URLs for repository file links in the root README; verify linked files exist.
|
||||||
|
|
||||||
|
## v0.6.0 — 2026-11-14
|
||||||
|
|
||||||
|
- Synchronize the shared Cargo package version with the v0.6.0 milestone tag; see the [release notes](../releases/v0.6.0.md).
|
||||||
|
|
||||||
|
- Group the guide and supporting documentation in this tool’s folder; update portal, cross-document and packaging links for the new paths.
|
||||||
|
|
||||||
|
- Add ImageGen application artwork in PNG, Windows ICO and macOS ICNS formats. Embed native icons and support Linux/BSD desktop entries and macOS app launchers; native Windows/macOS visual checks remain required.
|
||||||
|
|
||||||
|
## 2026-11-13
|
||||||
|
|
||||||
|
- `00a43e8`: Handle FreeBSD no-overwrite rename capabilities and safe-refusal CI expectations.
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
# Canvas Pilot has moved
|
||||||
|
|
||||||
|
Canvas Pilot now lives in its own [repository](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot). Its application,
|
||||||
|
device probe, templates, tests, documentation and book generation are maintained there.
|
||||||
|
|
||||||
|
[Full manual](https://books.dandaedre.com/manuals/canvas-pilot/) ·
|
||||||
|
[Changelog](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/changelog.md) ·
|
||||||
|
[Migration details](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/development/migration.md)
|
||||||
|
|
@ -0,0 +1,29 @@
|
||||||
|
# Changelogs
|
||||||
|
|
||||||
|
Latest release: [v0.7.0](releases/v0.7.0.md).
|
||||||
|
|
||||||
|
Short internal notes for testing and bookkeeping, newest first. Existing history
|
||||||
|
is only partially backfilled; Git has the full record.
|
||||||
|
|
||||||
|
- [Canvas Pilot](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/canvas-pilot/changelog.md) (including the Python device probe)
|
||||||
|
- [PDF Presenter](https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter/src/branch/main/docs/changelog.md) (standalone foundation; access required)
|
||||||
|
- [PPTX Reporter](pptx-reporter/changelog.md)
|
||||||
|
- [Rundown Converter](rundown-converter/changelog.md)
|
||||||
|
- [ASCII Names](ascii-names/changelog.md)
|
||||||
|
- [Document Exporter](exporter/changelog.md)
|
||||||
|
- [MPC-HC Companion module](media-player-classic/changelog.md)
|
||||||
|
|
||||||
|
For each change, add one short bullet under Unreleased: what changed and, when
|
||||||
|
useful, what to test or a known limitation. Use a commit hash when already known;
|
||||||
|
group entries under the tag when released. No full release write-up needed.
|
||||||
|
|
||||||
|
## Repository changes — Unreleased
|
||||||
|
|
||||||
|
- Linked the standalone PDF Presenter foundation, implementation plan and CI guide.
|
||||||
|
Its source and future multiscreen PDF application live in `idle-org/pdf-presenter`;
|
||||||
|
this workspace does not build it or publish its assets.
|
||||||
|
|
||||||
|
- Extracted Canvas Pilot and its manual into `idle-org/canvas-pilot`. The workspace
|
||||||
|
now owns three Rust applications and five books. Shared manual publication keeps
|
||||||
|
the separately published Canvas Pilot book intact; documentation links point to
|
||||||
|
its new home.
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
# Development
|
# Development
|
||||||
|
|
||||||
|
[Documentation](../README.md) · [CI and coverage](ci.md) · [Releases](releases.md)
|
||||||
|
|
||||||
## Layout and workflow
|
## Layout and workflow
|
||||||
|
|
||||||
| Directory | Purpose |
|
| Directory | Purpose |
|
||||||
|
|
@ -13,6 +15,9 @@
|
||||||
Prototype in Python, then add a Rust workspace member when the workflow is
|
Prototype in Python, then add a Rust workspace member when the workflow is
|
||||||
stable. Retire the Python implementation once the Rust port is validated.
|
stable. Retire the Python implementation once the Rust port is validated.
|
||||||
The PPTX reporter is now Rust-only; the document exporter remains Python.
|
The PPTX reporter is now Rust-only; the document exporter remains Python.
|
||||||
|
The [rundown converter](../rundown-converter/README.md) is a separate Rust workspace member
|
||||||
|
with CLI and egui interfaces. Its [implementation checklist](../rundown-converter/plan.md)
|
||||||
|
and [evaluation corpus](../rundown-converter/corpus.md) track coverage and remaining limitations.
|
||||||
Avoid speculative shared crates; extract common code when multiple tools need it.
|
Avoid speculative shared crates; extract common code when multiple tools need it.
|
||||||
|
|
||||||
The root `Cargo.toml` owns workspace metadata, the shared version and build
|
The root `Cargo.toml` owns workspace metadata, the shared version and build
|
||||||
|
|
@ -47,3 +52,13 @@ GUI or PDF engine; add `--features pdf` to restore embedded PDFs.
|
||||||
Keep generated files out of Git. Commit each completed task after checks; do
|
Keep generated files out of Git. Commit each completed task after checks; do
|
||||||
not push without authorization. See [CI and coverage](ci.md) and
|
not push without authorization. See [CI and coverage](ci.md) and
|
||||||
[cross builds and packaging](releases.md).
|
[cross builds and packaging](releases.md).
|
||||||
|
|
||||||
|
The converter can run without desktop dependencies using
|
||||||
|
`cargo run --locked -p rundown-converter --no-default-features --bin rundown-converter -- --help`.
|
||||||
|
Its tests generate synthetic XLSX inputs and never require private source files
|
||||||
|
or network downloads. The existing workspace test, lint, Rustdoc and coverage
|
||||||
|
commands include both tools; reporter release packaging remains separate.
|
||||||
|
|
||||||
|
The [ASCII filename cleaner](../ascii-names/README.md) is a separate Rust workspace member.
|
||||||
|
Run `cargo run --locked -p ascii-names` for its drag-and-drop window, or pass a
|
||||||
|
folder for CLI cleanup. It uses the same workspace checks and coverage gates.
|
||||||
|
|
@ -2,9 +2,15 @@
|
||||||
|
|
||||||
Jenkins must use a Multibranch Pipeline supplying `BRANCH_NAME`, with the
|
Jenkins must use a Multibranch Pipeline supplying `BRANCH_NAME`, with the
|
||||||
`rust_no_docker` worker, Python 3.11+ and Rust.
|
`rust_no_docker` worker, Python 3.11+ and Rust.
|
||||||
|
The current worker runs in a FreeBSD jail; the Tools stage logs `uname -sr`.
|
||||||
|
Older jails without `renameat2` verify the ASCII cleaner's safe refusal instead
|
||||||
|
of its successful-rename paths. Those paths must also run on a supported host;
|
||||||
|
see [FreeBSD test coverage](../ascii-names/README.md#freebsd-ci-hosts).
|
||||||
SCM credentials, webhooks and the publication mount are administrator setup.
|
SCM credentials, webhooks and the publication mount are administrator setup.
|
||||||
CI checks formatting, Clippy, rustdoc, Python/Rust tests and
|
CI checks formatting, Clippy, rustdoc, Python/Rust tests and
|
||||||
whole-workspace Rust coverage. It never creates tags or release artifacts.
|
whole-workspace Rust coverage. It also builds five mdBook manuals and publishes
|
||||||
|
successful non-PR main builds to `/mnt/books/manuals/`. It never creates tags or
|
||||||
|
release artifacts.
|
||||||
|
|
||||||
The Python reporter and cross-language parity checks are retired. CI uses the
|
The Python reporter and cross-language parity checks are retired. CI uses the
|
||||||
Rust reporter's own regression tests and embedded PDF engine, plus Python
|
Rust reporter's own regression tests and embedded PDF engine, plus Python
|
||||||
|
|
@ -22,9 +28,12 @@ CI installs pinned `cargo-llvm-cov 0.9.1` and `llvm-tools-preview`. The tracked
|
||||||
`.cargo/config.toml` alias `cargo coverage` expands to:
|
`.cargo/config.toml` alias `cargo coverage` expands to:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cargo llvm-cov --locked --workspace --all-features --json --summary-only --output-path coverage/summary.json
|
cargo llvm-cov --locked --workspace --json --summary-only --output-path coverage/summary.json
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Coverage includes every GUI/PDF feature in the three application crates.
|
||||||
|
Canvas Pilot has its own repository and CI pipeline.
|
||||||
|
|
||||||
Run the same lifecycle locally (no publication):
|
Run the same lifecycle locally (no publication):
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|
@ -76,3 +85,21 @@ Actual Jenkins archival/publication and public URL retrieval are separate
|
||||||
external checkpoints. Local checks do not establish that badges are live.
|
external checkpoints. Local checks do not establish that badges are live.
|
||||||
The asset server should mount assets read-only, disable listings, serve SVG
|
The asset server should mount assets read-only, disable listings, serve SVG
|
||||||
with restrictive CSP, and revalidate mutable URLs or use a short cache lifetime.
|
with restrictive CSP, and revalidate mutable URLs or use a short cache lifetime.
|
||||||
|
|
||||||
|
## Project manuals
|
||||||
|
|
||||||
|
The Tools stage installs the mdBook version pinned in
|
||||||
|
[`docs/manuals/mdbook-version`](../manuals/mdbook-version) and requires `rsync`.
|
||||||
|
The Build manuals stage stages existing documentation, builds all five books, and
|
||||||
|
checks rendered links, anchors and downloadable assets. No mdBook plugins or
|
||||||
|
additional Jenkins plugins are needed. Tests cover staging and publication into
|
||||||
|
temporary directories, including stale-file cleanup and preservation of unrelated
|
||||||
|
manuals. Publication runs after coverage, only when the whole build is successful,
|
||||||
|
on non-PR main. The helper independently enforces the branch/PR restriction.
|
||||||
|
|
||||||
|
The worker must expose the existing writable `/mnt/books` mount. The five manuals
|
||||||
|
and a shared landing page are published under `/mnt/books/manuals/`; deletion is
|
||||||
|
scoped to each owned book directory. This follows the referenced mdBook pipeline's
|
||||||
|
Cargo/build/rsync method while keeping the existing badge cleanup behavior intact.
|
||||||
|
See [manual configuration, preview and publication](../manuals/README.md) for
|
||||||
|
paths, prerequisites and update behavior.
|
||||||
|
|
@ -0,0 +1,10 @@
|
||||||
|
{
|
||||||
|
"generator": "Built-in image_gen",
|
||||||
|
"prompts": {
|
||||||
|
"ascii-names": "Use case: logo-brand. Asset type: professional desktop application icon for ascii-names in a coordinated suite of document and audiovisual tools. Subject: a refined folder containing a single clean capital A with a small check mark, representing filename cleanup. A single centered icon, square 1024x1024 canvas, rounded-square deep graphite tile with restrained luminous teal and cool silver pictogram. Premium contemporary desktop software visual identity, simple bold geometry, subtle depth and soft bevel, crisp silhouette legible at 32 pixels, front-facing orthographic view, balanced margins. Transparent background outside the tile, tile occupies 88% of canvas. No words, no labels, no watermark, no extra decorative objects.",
|
||||||
|
"pptx-reporter": "Use case: logo-brand. Asset type: professional desktop application icon for pptx-reporter in a coordinated suite of document and audiovisual tools. Subject: a presentation slide with a play triangle and a small clock, representing video timing reports. A single centered icon, square 1024x1024 canvas, rounded-square deep graphite tile with restrained luminous teal and cool silver pictogram. Premium contemporary desktop software visual identity, simple bold geometry, subtle depth and soft bevel, crisp silhouette legible at 32 pixels, front-facing orthographic view, balanced margins. Transparent background outside the tile, tile occupies 88% of canvas. No words, no labels, no watermark, no extra decorative objects.",
|
||||||
|
"rundown-converter": "Use case: logo-brand. Asset type: professional desktop application icon for rundown-converter in a coordinated suite of document and audiovisual tools. Subject: a clean schedule sheet with three horizontal rows and a clock, representing show rundown conversion. A single centered icon, square 1024x1024 canvas, rounded-square deep graphite tile with restrained luminous teal and cool silver pictogram. Premium contemporary desktop software visual identity, simple bold geometry, subtle depth and soft bevel, crisp silhouette legible at 32 pixels, front-facing orthographic view, balanced margins. Transparent background outside the tile, tile occupies 88% of canvas. No words, no labels, no watermark, no extra decorative objects.",
|
||||||
|
"exporter": "Use case: logo-brand. Asset type: professional desktop application icon for exporter in a coordinated suite of document and audiovisual tools. Subject: two layered documents and a bold outward arrow, representing document export. A single centered icon, square 1024x1024 canvas, rounded-square deep graphite tile with restrained luminous teal and cool silver pictogram. Premium contemporary desktop software visual identity, simple bold geometry, subtle depth and soft bevel, crisp silhouette legible at 32 pixels, front-facing orthographic view, balanced margins. Transparent background outside the tile, tile occupies 88% of canvas. No words, no labels, no watermark, no extra decorative objects.",
|
||||||
|
"media-player-classic": "Use case: logo-brand. Asset type: professional desktop application icon for media-player-classic in a coordinated suite of document and audiovisual tools. Subject: a play triangle within a professional media transport panel, representing remote media player control. A single centered icon, square 1024x1024 canvas, rounded-square deep graphite tile with restrained luminous teal and cool silver pictogram. Premium contemporary desktop software visual identity, simple bold geometry, subtle depth and soft bevel, crisp silhouette legible at 32 pixels, front-facing orthographic view, balanced margins. Transparent background outside the tile, tile occupies 88% of canvas. No words, no labels, no watermark, no extra decorative objects."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -74,7 +74,8 @@ LGPL 9.0 asset name and published SHA-256 digest per Windows/Linux target. Dated
|
||||||
versioned names, unlike the downloader's default `latest` assets. To update,
|
versioned names, unlike the downloader's default `latest` assets. To update,
|
||||||
review the provider release and its notices, then update all three fields together.
|
review the provider release and its notices, then update all three fields together.
|
||||||
These dated releases are not marked immutable by GitHub; digest verification
|
These dated releases are not marked immutable by GitHub; digest verification
|
||||||
fails closed if an asset changes. Metadata access is still needed with a warm cache.
|
fails closed if an asset changes. Pinned cached binaries and notices are rechecked locally before any network access;
|
||||||
|
unpinned downloads still refresh upstream metadata.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
rust_realease . --package pptx-reporter --target x86_64-unknown-linux-gnu --compile-only
|
rust_realease . --package pptx-reporter --target x86_64-unknown-linux-gnu --compile-only
|
||||||
|
|
@ -172,12 +173,68 @@ all platforms.
|
||||||
|
|
||||||
## Application artwork
|
## Application artwork
|
||||||
|
|
||||||
Artwork and fonts live in `crates/pptx-reporter/assets/`. Builds embed the PNG
|
All three Rust apps embed their own PNG window icon and Windows ICO resource,
|
||||||
window icon and the ICO Windows resource without image conversion tools.
|
including CLI-only Windows builds. Linux/FreeBSD X11 uses the window icon;
|
||||||
To regenerate derivatives with ImageMagick from that directory:
|
Wayland desktops match each app ID to its desktop entry. macOS uses the ICNS
|
||||||
|
resource in an app bundle. A bare Unix executable has no Finder/application-menu icon.
|
||||||
|
|
||||||
|
Five coordinated icons were generated with the built-in ImageGen tool. The
|
||||||
|
[exact prompts](icon-prompts.json) are retained. Each Rust crate keeps its
|
||||||
|
`app-icon-source.png`, `app-icon.png`, `app-icon.ico` and `app-icon.icns` in
|
||||||
|
`assets/`. Python artwork lives in `tools/assets/exporter/`; Companion artwork lives in
|
||||||
|
`companion-modules/media-player-classic/companion/assets/`. Earlier reporter and
|
||||||
|
converter artwork remains available under its original filenames.
|
||||||
|
|
||||||
|
Builds consume committed derivatives and need no image tools. To regenerate the
|
||||||
|
256px PNG, seven-size ICO (16–256px), and ICNS (128–1024px), install ImageMagick 7
|
||||||
|
and run `python3 scripts/build-icons.py` from the repository root.
|
||||||
|
|
||||||
|
### Desktop launchers
|
||||||
|
|
||||||
|
After building or extracting a release, create a launcher pointing to the binary
|
||||||
|
at its permanent location. The helper refuses existing launchers/icons. Linux/BSD launchers reference the
|
||||||
|
original executable and stop working if it moves. macOS bundles copy the binary
|
||||||
|
and adjacent LICENSES directory. Reporter bundles also copy an adjacent FFprobe
|
||||||
|
(requiring its LICENSES directory); otherwise FFprobe must be on PATH. Recreate
|
||||||
|
macOS bundles after updating binaries.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
magick rust-report.png -resize 256x256 -background none -gravity center \
|
# Linux / FreeBSD: install into your desktop's user application directory.
|
||||||
-extent 256x256 rust-report-icon.png
|
python3 scripts/create-desktop-launcher.py ascii-names \
|
||||||
magick rust-report-icon.png -define icon:auto-resize=256,128,64,48,32,24,16 rust-report.ico
|
--binary "$PWD/target/release/ascii-names" --output "$HOME/.local/share"
|
||||||
|
|
||||||
|
# macOS: create a Finder/Dock launcher (run on the Mac).
|
||||||
|
python3 scripts/create-desktop-launcher.py ascii-names --platform macos \
|
||||||
|
--binary "$PWD/target/release/ascii-names" --output "$HOME/Applications"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The same helper supports `pptx-reporter` and `rundown-converter`; pass their
|
||||||
|
`-gui` executable. Reporter and rundown portable archives include the helper,
|
||||||
|
its supporting module, and the icon formats, so these commands also work from
|
||||||
|
an extracted archive. Respect `XDG_DATA_HOME` instead of `~/.local/share` when
|
||||||
|
customized. Desktop menus may need a refresh. Windows executables have embedded
|
||||||
|
icons; shortcuts inherit those icons.
|
||||||
|
|
||||||
|
Python scripts and the Companion module run inside a host application and cannot
|
||||||
|
replace its OS icon. Their PNG/ICO/ICNS files are available for custom shortcuts;
|
||||||
|
the Companion README displays its module icon. Shared libraries, CI scripts,
|
||||||
|
packaging helpers and `progress.py` are not standalone applications.
|
||||||
|
|
||||||
|
Launcher output is described in [the desktop launcher contract](../interfaces/desktop-launchers.md).
|
||||||
|
Automated checks validate icon containers and launcher output on Linux. Finder,
|
||||||
|
Dock, Windows Explorer/taskbar and individual Wayland desktop behavior still
|
||||||
|
need native visual checks. The macOS launchers are not signed or notarized.
|
||||||
|
|
||||||
|
## Releases containing both tools
|
||||||
|
|
||||||
|
The workspace version applies to both tools. Build the reporter with the root
|
||||||
|
configuration, and the converter with its overlay (which omits FFprobe):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
rust_realease . --package pptx-reporter --compile-only
|
||||||
|
rust_realease . --package rundown-converter --config rust-release-rundown.toml --compile-only
|
||||||
|
```
|
||||||
|
|
||||||
|
Publish both packages' canonical and portable archives under the same version
|
||||||
|
tag. Aggregate their checksum lists into one `SHA256SUMS`; do not replace one
|
||||||
|
package's checksums with the other's. Each archive includes both CLI and GUI.
|
||||||
|
|
@ -1,5 +1,11 @@
|
||||||
# Export presentations and PDF pages
|
# Export presentations and PDF pages
|
||||||
|
|
||||||
|
[Read the full manual →](https://books.dandaedre.com/manuals/exporter/)
|
||||||
|
|
||||||
|
[Documentation](../README.md) · [Changelog](changelog.md)
|
||||||
|
|
||||||
|
<img src="../../tools/assets/exporter/app-icon.png" width="96" alt="Application icon">
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
python3 tools/exporter.py presentation.pptx --output pdf,images
|
python3 tools/exporter.py presentation.pptx --output pdf,images
|
||||||
python3 tools/exporter.py document.pdf --output images
|
python3 tools/exporter.py document.pdf --output images
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
# Document Exporter changelog
|
||||||
|
|
||||||
|
[All changelogs](../changelogs.md)
|
||||||
|
|
||||||
|
## Unreleased
|
||||||
|
|
||||||
|
## v0.7.0 — 2026-11-14
|
||||||
|
|
||||||
|
- Documentation release; see the [release notes](../releases/v0.7.0.md).
|
||||||
|
|
||||||
|
- Add direct links to the published mdBook manual from the project README, tool guide and documentation indexes.
|
||||||
|
|
||||||
|
- Add an mdBook manual built from the existing guides, with local assets and downloads. Jenkins publishes successful main builds under `/mnt/books/manuals/`; staging, link validation and scoped publication have regression coverage.
|
||||||
|
|
||||||
|
- Use absolute Gitea main-branch URLs for repository file links in the root README; verify linked files exist.
|
||||||
|
|
||||||
|
## v0.6.0 — 2026-11-14
|
||||||
|
|
||||||
|
- Group the guide and supporting documentation in this tool’s folder; update portal, cross-document and packaging links for the new paths.
|
||||||
|
|
||||||
|
- Add ImageGen application artwork in PNG, Windows ICO and macOS ICNS formats. Artwork is available for shortcuts and documentation; the tool remains hosted by its terminal or Companion.
|
||||||
|
|
||||||
|
## 2026-10-20
|
||||||
|
|
||||||
|
- `095e7c7`: Report selected export DPI and allow reusing it.
|
||||||
|
|
@ -0,0 +1,7 @@
|
||||||
|
# File and device interfaces
|
||||||
|
|
||||||
|
[Documentation](../README.md)
|
||||||
|
|
||||||
|
- [Desktop launchers](desktop-launchers.md): generated shortcuts and launcher metadata.
|
||||||
|
- [PPTX Reporter formats](../pptx-reporter/report-formats.md): report output semantics.
|
||||||
|
- [Canvas Pilot contracts](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/interfaces/README.md): project and settings schemas, geometry exchange, recovery, device adapters and reviewed transfers. These contracts and fixtures now live in the Canvas Pilot repository.
|
||||||
|
|
@ -0,0 +1,37 @@
|
||||||
|
# Desktop launcher output
|
||||||
|
|
||||||
|
`scripts/create-desktop-launcher.py` emits standard operating-system launcher
|
||||||
|
files for the three Rust desktop apps. It does not save application data or
|
||||||
|
import user projects. There is no custom schema version or round-trip importer;
|
||||||
|
compatibility follows Desktop Entry and macOS bundle conventions.
|
||||||
|
|
||||||
|
Linux/BSD output under `--output`:
|
||||||
|
|
||||||
|
- `applications/<tool>.desktop`: UTF-8 `[Desktop Entry]`, `Type=Application`,
|
||||||
|
human-readable `Name`, quoted absolute `Exec` with desktop field-code escaping,
|
||||||
|
absolute `Icon`, `Terminal=false`, `Categories=AudioVideo;Utility;`, and
|
||||||
|
`StartupWMClass=<tool>`. The filename matches the egui Wayland app ID.
|
||||||
|
- `icons/hicolor/256x256/apps/<tool>.png`: 256 × 256 RGBA application artwork.
|
||||||
|
|
||||||
|
macOS output is `<display name>.app/Contents/`:
|
||||||
|
|
||||||
|
- `Info.plist`: XML plist, `CFBundleName` and `CFBundleDisplayName` contain the
|
||||||
|
display name; `CFBundleIdentifier=com.beffroi.<tool>`;
|
||||||
|
`CFBundlePackageType=APPL`; `CFBundleExecutable=<tool>`;
|
||||||
|
`CFBundleIconFile=app-icon.icns`; `CFBundleVersion=1` identifies the launcher;
|
||||||
|
`NSHighResolutionCapable=true`.
|
||||||
|
- `MacOS/<tool>`: copied executable with mode 0755.
|
||||||
|
- `MacOS/ffprobe`: copied adjacent FFprobe when present for the reporter, requiring
|
||||||
|
a sibling `LICENSES` directory. Without it, the reporter uses PATH discovery.
|
||||||
|
- `Resources/LICENSES`: copied adjacent notices, when present. Symlinks in the
|
||||||
|
notices tree are refused.
|
||||||
|
- `Resources/app-icon.icns`: PNG-backed `ic07`, `ic08`, `ic09`, `ic10` entries,
|
||||||
|
at 128, 256, 512 and 1024 pixels respectively.
|
||||||
|
|
||||||
|
The binary must resolve to an existing executable regular file. Existing
|
||||||
|
launcher/icon destinations are refused, including symlinks. Linux/BSD paths are absolute and require the original installation to stay in
|
||||||
|
place. macOS copies are independent of their source location; recreate the bundle
|
||||||
|
to update its executables. Fonts stay embedded in the Rust binaries. The helper does not bypass macOS
|
||||||
|
Gatekeeper, sign bundles, register file associations, or make a binary for
|
||||||
|
another CPU/OS runnable. No timing values, numeric precision or user-data
|
||||||
|
migration applies to this format.
|
||||||
|
|
@ -0,0 +1,110 @@
|
||||||
|
# Project manuals
|
||||||
|
|
||||||
|
[Documentation](../README.md) · [CI and coverage](../development/ci.md)
|
||||||
|
|
||||||
|
**[Read all manuals online →](https://books.dandaedre.com/manuals/)**
|
||||||
|
|
||||||
|
Each project has an mdBook manual, built from the existing documentation. Edit the
|
||||||
|
original guides; the build stages them without creating a second maintained copy.
|
||||||
|
The published landing page includes five owned manuals and an external link to Canvas Pilot.
|
||||||
|
|
||||||
|
| Manual | Read online | Chapter sources |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| ASCII Names | [Full manual](https://books.dandaedre.com/manuals/ascii-names/) | [Chapter list](ascii-names/SUMMARY.md) |
|
||||||
|
| Document Exporter | [Full manual](https://books.dandaedre.com/manuals/exporter/) | [Chapter list](exporter/SUMMARY.md) |
|
||||||
|
| MPC-HC Companion | [Full manual](https://books.dandaedre.com/manuals/media-player-classic/) | [Chapter list](media-player-classic/SUMMARY.md) |
|
||||||
|
| Canvas Pilot | [Full manual](https://books.dandaedre.com/manuals/canvas-pilot/) | [Chapter list](https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot/src/branch/main/docs/manuals/canvas-pilot/SUMMARY.md) |
|
||||||
|
| PPTX Reporter | [Full manual](https://books.dandaedre.com/manuals/pptx-reporter/) | [Chapter list](pptx-reporter/SUMMARY.md) |
|
||||||
|
| Rundown Converter | [Full manual](https://books.dandaedre.com/manuals/rundown-converter/) | [Chapter list](rundown-converter/SUMMARY.md) |
|
||||||
|
|
||||||
|
The published site is served from `/mnt/books/manuals/` at
|
||||||
|
https://books.dandaedre.com/manuals/. Each `book.toml` declares a relative
|
||||||
|
`site-url` for its 404 page, so local previews also work.
|
||||||
|
|
||||||
|
## Build and preview
|
||||||
|
|
||||||
|
Requires Python 3.11+, Rust/Cargo for installation, and mdBook **0.5.4**, pinned in
|
||||||
|
[mdbook-version](mdbook-version). No mdBook plugins are required. From the repository root:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo install mdbook --version "$(cat docs/manuals/mdbook-version)" --locked
|
||||||
|
python3 scripts/manuals.py build
|
||||||
|
python3 scripts/manuals.py check
|
||||||
|
python3 -m http.server 8000 --directory build/manuals/site
|
||||||
|
```
|
||||||
|
|
||||||
|
Open `http://localhost:8000/manuals/`. Search, chapter navigation, themes and
|
||||||
|
printable manuals are supplied by mdBook. To use a separately installed binary,
|
||||||
|
pass `--mdbook /path/to/mdbook` to the build command.
|
||||||
|
|
||||||
|
Generated source trees are in `build/manuals/sources/<project>/`; rendered files
|
||||||
|
are in `build/manuals/site/manuals/`. Both are ignored. All books must build and
|
||||||
|
pass rendered-link validation before the output is made available for publication.
|
||||||
|
The validator checks local assets, downloads, chapter links and heading fragments;
|
||||||
|
it does not request external websites. mdBook's generated 404 heading links are
|
||||||
|
adjusted to remain on the 404 page despite its HTML base URL.
|
||||||
|
|
||||||
|
## Maintain a manual
|
||||||
|
|
||||||
|
Each project directory here contains a `book.toml` and `SUMMARY.md`:
|
||||||
|
|
||||||
|
- `SUMMARY.md` lists canonical Markdown chapters with paths relative to itself.
|
||||||
|
Add or reorder entries here. The linked files remain readable in the repository.
|
||||||
|
- `book.toml` configures the staged mdBook. Its `[manual]` table provides the
|
||||||
|
repository-relative project icon used by the landing page; the staging script
|
||||||
|
removes this table before calling mdBook.
|
||||||
|
- Run the helper rather than running `mdbook build` directly in these configuration
|
||||||
|
directories: it creates the `src` tree and rewrites chapter and asset links.
|
||||||
|
- Included chapters link to other included chapters locally. References to guides
|
||||||
|
outside the current book, source code and repository directories link to Gitea.
|
||||||
|
Referenced screenshots, icons, text quick starts, schema examples and starter
|
||||||
|
files are copied into the book with their original bytes. Canvas Pilot's starter
|
||||||
|
catalog is built and published from its own repository.
|
||||||
|
- Fenced code blocks retain their literal command examples. Keep documentation
|
||||||
|
links in ordinary Markdown or quoted HTML `href`/`src` attributes; the helper
|
||||||
|
currently handles inline Markdown links without optional title attributes.
|
||||||
|
- Update the tool's changelog for documentation changes. Keep generated HTML and
|
||||||
|
staging files out of Git.
|
||||||
|
|
||||||
|
## Jenkins publication
|
||||||
|
|
||||||
|
The repository [Jenkinsfile](../../Jenkinsfile) follows the supplied
|
||||||
|
[Deathwatch mdBook pipeline](https://proxy.dandaedre.com/gitea/Books/deathwatch-d10/raw/branch/main/Jenkinsfile):
|
||||||
|
use `rust_no_docker`, install mdBook with Cargo, build HTML, then publish using
|
||||||
|
`rsync -a --delete`. Here mdBook is pinned, installation errors fail the build,
|
||||||
|
and no unused preprocessors or custom Jenkins warning-parser plugins are installed.
|
||||||
|
Rendered-link validation supplies a build gate before publication.
|
||||||
|
|
||||||
|
Jenkins needs `rsync` on PATH and an existing writable `/mnt/books` mount visible
|
||||||
|
inside the worker jail. The helper creates `manuals/` and the five owned book directories;
|
||||||
|
it fails if the parent mount is missing. Web server routing and that mount are
|
||||||
|
administrator setup. Jenkins does not create them.
|
||||||
|
|
||||||
|
Every branch builds the manuals. Only a successful non-PR `main` build publishes,
|
||||||
|
after the test and coverage stages. Concurrent builds of the same job are disabled.
|
||||||
|
The publication helper also rejects any environment without `BRANCH_NAME=main`
|
||||||
|
or with `CHANGE_ID` set.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Run by Jenkins, with its existing branch/PR environment:
|
||||||
|
python3 scripts/manuals.py publish --destination /mnt/books/manuals
|
||||||
|
```
|
||||||
|
|
||||||
|
Publication validates the whole rendered set before writing, refuses symlinked
|
||||||
|
source/destination directories, and runs `rsync --delete` separately inside each
|
||||||
|
of the five owned book directories. It never synchronizes or deletes the shared
|
||||||
|
`/mnt/books` or `manuals` root. Unrelated manuals and root files survive. The landing
|
||||||
|
page is replaced atomically after all book synchronizations succeed. Each book's
|
||||||
|
rsync is an in-place update, not an atomic release of the entire collection; a
|
||||||
|
failed rsync fails Jenkins and leaves the existing landing page in place. A later
|
||||||
|
successful build retries the complete set. Removing a manual configuration does
|
||||||
|
not automatically delete its previously published directory.
|
||||||
|
|
||||||
|
Existing badge archival/publication stays separate and still archives exactly
|
||||||
|
three SVGs. This workflow does not create tags, releases or release binaries.
|
||||||
|
Local builds and temporary publication tests do not mean the live books server
|
||||||
|
has been updated; that happens when this commit runs successfully on Jenkins main.
|
||||||
|
|
||||||
|
Canvas Pilot is independently built and published by its own repository. This
|
||||||
|
publisher leaves `canvas-pilot/` intact and owns the shared landing page. The Canvas
|
||||||
|
Pilot publisher must never replace that page or any of these five books.
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
# Summary
|
||||||
|
|
||||||
|
- [User guide](../../ascii-names/README.md)
|
||||||
|
- [Builds and portable releases](../../development/releases.md)
|
||||||
|
- [Development](../../development/README.md)
|
||||||
|
- [Changelog](../../ascii-names/changelog.md)
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
[book]
|
||||||
|
title = "ASCII Names Manual"
|
||||||
|
description = "Clean up filenames while preserving file contents."
|
||||||
|
language = "en"
|
||||||
|
src = "src"
|
||||||
|
|
||||||
|
[build]
|
||||||
|
create-missing = false
|
||||||
|
|
||||||
|
[output.html]
|
||||||
|
site-url = "/manuals/ascii-names/"
|
||||||
|
default-theme = "light"
|
||||||
|
preferred-dark-theme = "navy"
|
||||||
|
git-repository-url = "https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools"
|
||||||
|
|
||||||
|
[output.html.fold]
|
||||||
|
enable = true
|
||||||
|
level = 1
|
||||||
|
|
||||||
|
[output.html.playground]
|
||||||
|
runnable = false
|
||||||
|
|
||||||
|
# Consumed by scripts/manuals.py when staging the book and landing page.
|
||||||
|
[manual]
|
||||||
|
icon = "crates/ascii-names/assets/app-icon.png"
|
||||||