RemoteProjectControlTests.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. #include "engine/RemoteProjectControl.h"
  2. #include "engine/RemoteJsonPatch.h"
  3. #include "engine/RemoteFileSecurity.h"
  4. #include "engine/ProjectFile.h"
  5. #include "engine/RemoteNotes.h"
  6. #include "core/SessionIds.h"
  7. #include "core/ClipLauncher.h"
  8. #include "core/Preferences.h"
  9. #include "core/Rack.h"
  10. #include "core/PluginSubstitutes.h"
  11. #include "core/FlExtraFx.h"
  12. #include "core/VideoPlayer.h"
  13. #include "core/VisualFx.h"
  14. #include "core/Vfx.h"
  15. #include <cstdio>
  16. #include <stdexcept>
  17. #include <limits>
  18. using namespace lynx;
  19. namespace
  20. {
  21. void check (bool condition, const char* message)
  22. {
  23. if (! condition) throw std::runtime_error (message);
  24. }
  25. juce::var json (const char* text)
  26. {
  27. juce::var result;
  28. check (juce::JSON::parse (text, result).wasOk(), "Bad test JSON");
  29. return result;
  30. }
  31. template <class Fn> void refuses (Fn&& operation)
  32. {
  33. bool rejected = false;
  34. try { operation(); } catch (const std::runtime_error&) { rejected = true; }
  35. check (rejected, "Invalid transaction was accepted");
  36. }
  37. template <class Fn> void refusesWith (Fn&& operation, const char* reason)
  38. {
  39. std::string actual = "operation was accepted";
  40. try { operation(); }
  41. catch (const std::runtime_error& error)
  42. {
  43. actual = error.what();
  44. if (actual.find (reason) != std::string::npos) return;
  45. }
  46. throw std::runtime_error (std::string ("Expected rejection containing '") + reason + "', got: " + actual);
  47. }
  48. juce::var addValue (const char* path, const juce::var& value)
  49. {
  50. auto* operation = new juce::DynamicObject();
  51. operation->setProperty ("op", "add");
  52. operation->setProperty ("path", path);
  53. operation->setProperty ("value", value);
  54. return juce::Array<juce::var> { juce::var (operation) };
  55. }
  56. juce::String encoded (const std::vector<std::uint8_t>& bytes)
  57. {
  58. return juce::Base64::toBase64 (bytes.data(), bytes.size());
  59. }
  60. Song fixture()
  61. {
  62. Song song;
  63. ChannelDef channel;
  64. channel.name = "Lead";
  65. channel.synth.cutoff = 2432.12353515625f;
  66. channel.synth.resonance = 0.123456791f;
  67. channel.modelParams = { 0.123456791f, 1.23456788e-12f, 1.23456789e20f };
  68. channel.synth.spectrum[0] = 0.123456791f;
  69. channel.synth.spectrum[1] = 1.23456788e-12f;
  70. channel.synth.spectrumPhase[0] = 0.234567896f;
  71. channel.synth.spectrumDecay[0] = 2.12345672f;
  72. channel.synth.spectrumTarget[0] = 0.345678925f;
  73. channel.volume = 0.73123455f;
  74. song.channels.push_back (channel);
  75. song.mixer = Song::defaultMixer (2);
  76. song.mixer[1].volume = 0.812345683f;
  77. song.mixer[1].pan = -0.123456791f;
  78. song.mixer[1].stereo = 0.234567896f;
  79. song.mixer[1].sends.push_back ({ 2, 0.345678925f });
  80. song.mixer[1].lostSends.push_back ({ "Deleted insert", 0.456789017f });
  81. song.swing = 0.123456791f;
  82. song.chanceSeed = 0x89abcdefu;
  83. song.bpm = 130.12345678901235;
  84. Pattern pattern;
  85. pattern.name = "Lead";
  86. pattern.lengthTicks = 3840;
  87. Note note;
  88. note.channel = 0;
  89. note.start = 13;
  90. note.length = 1001;
  91. note.velocity = 0.73123455f;
  92. note.pan = 0.123456791f;
  93. note.finePitch = 4.56789112f;
  94. note.release = 0.456789017f;
  95. note.modX = 0.89123404f;
  96. note.modY = 0.345678925f;
  97. note.chance = 0.73123455f;
  98. note.velocityRange = 0.123456791f;
  99. note.chanceGroup = 7;
  100. note.chanceOne = true;
  101. pattern.notes.push_back (note);
  102. note.start = 1920;
  103. note.chance = 1.0f;
  104. note.velocityRange = 0.0f;
  105. note.chanceGroup = 0;
  106. note.repeat = 9; // (issue #208: FL's note repeat survives the project document)
  107. pattern.notes.push_back (note); // Exact documents also preserve the inactive play-one flag.
  108. PatternEvents lane;
  109. lane.target = { AutomationTargetKind::channelVolume, 0 };
  110. lane.events.push_back ({ 17, 0.765432119f });
  111. pattern.events.push_back (lane);
  112. song.patterns.push_back (pattern);
  113. Automation automation;
  114. automation.name = "Level";
  115. automation.target = { AutomationTargetKind::channelVolume, 0 };
  116. automation.points.push_back ({ 0, 0.765432119f, 0.456789017f });
  117. song.automations.push_back (automation);
  118. Clip clip;
  119. clip.pattern = 0;
  120. clip.length = 3840;
  121. clip.gain = 0.123456791f;
  122. clip.offsetFraction = 0.234567896f;
  123. clip.pan = -0.345678925f;
  124. clip.pitch = 0.456789017f;
  125. clip.stretch = 1.123456789012345;
  126. song.playlist.push_back (clip);
  127. uids::normalize (song);
  128. return song;
  129. }
  130. #include "RemoteNotesTests.inc"
  131. void patchSemantics()
  132. {
  133. const auto source = json (R"({"a/b":{"~name":[1,2]},"x":1})");
  134. const auto result = remote_json::apply (source, json (R"([
  135. {"op":"test","path":"/x","value":1.0},
  136. {"op":"add","path":"/a~1b/~0name/1","value":3},
  137. {"op":"replace","path":"/x","value":4},
  138. {"op":"remove","path":"/a~1b/~0name/0"},
  139. {"op":"add","path":"/a~1b/~0name/-","value":5}
  140. ])"));
  141. check (remote_json::equal (result, json (R"({"a/b":{"~name":[3,2,5]},"x":4})")), "JSON Patch ordering/escaping differs");
  142. check (remote_json::equal (source, json (R"({"a/b":{"~name":[1,2]},"x":1})")), "Patching mutated its source");
  143. refuses ([&] { remote_json::apply (source, json (R"([{"op":"replace","path":"/x","value":3},{"op":"test","path":"/x","value":2}])")); });
  144. check (source["x"] == juce::var (1), "A failed later operation leaked an earlier change");
  145. refuses ([&] { remote_json::apply (source, json (R"([{"op":"test","path":"/x","value":1.00000001}])")); });
  146. refuses ([&] { remote_json::apply (source, json (R"([{"op":"add","path":"/a~1b/~0name/01","value":0}])")); });
  147. refuses ([&] { remote_json::apply (source, json (R"([{"op":"add","path":"/a~1b/~0name/4","value":0}])")); });
  148. refuses ([&] { remote_json::apply (source, json (R"([{"op":"replace","path":"/bad~2path","value":0}])")); });
  149. refuses ([&] { remote_json::apply (source, json (R"([{"op":"replace","path":"/missing","value":0}])")); });
  150. refuses ([&] { remote_json::apply (source, json (R"([{"op":"move","path":"/x","value":0}])")); });
  151. refuses ([&] { remote_json::apply (source, json (R"([{"op":"remove","path":"/x","value":0}])")); });
  152. refuses ([&] { remote_json::apply (source, json (R"([{"op":"replace","path":"/x","value":0,"extra":1}])")); });
  153. }
  154. void exactDocuments()
  155. {
  156. const auto source = fixture();
  157. const auto ordinary = ProjectFile::toJson (source);
  158. const auto exact = ProjectFile::toJsonExact (source);
  159. check (exact != ordinary, "Exact snapshots still use rounded save numbers");
  160. check (ProjectFile::toJson (source) == ordinary, "Exact serialization changed later ordinary saves");
  161. juce::String error;
  162. const auto loaded = ProjectFile::fromJson (exact, error);
  163. check (loaded.has_value(), "Exact project did not load");
  164. check (loaded->patterns == source.patterns && loaded->automations == source.automations
  165. && loaded->channels == source.channels && loaded->mixer == source.mixer
  166. && loaded->playlist == source.playlist && loaded->swing == source.swing
  167. && loaded->chanceSeed == source.chanceSeed,
  168. "Exact snapshots lost native float bits or unrequested data");
  169. const auto staged = remote_document::stage (source, json (R"([
  170. {"op":"test","path":"/bpm","value":130.12345678901235},
  171. {"op":"replace","path":"/bpm","value":142},
  172. {"op":"replace","path":"/patterns/0/name","value":"Verse"}
  173. ])"));
  174. auto expected = source;
  175. expected.bpm = 142;
  176. expected.patterns[0].name = "Verse";
  177. check (staged.bpm == 142 && staged.patterns == expected.patterns && staged.channels == source.channels
  178. && staged.mixer == source.mixer && staged.automations == source.automations && staged.playlist == source.playlist
  179. && staged.swing == source.swing && staged.chanceSeed == source.chanceSeed
  180. && staged.projectId == source.projectId && staged.nextUid == source.nextUid,
  181. "Metadata transaction changed unrelated native state");
  182. check (source.bpm == 130.12345678901235 && source.patterns[0].name == "Lead", "Staging mutated the live input");
  183. const auto onlyName = remote_document::stage (source, json (R"([{"op":"replace","path":"/patterns/0/name","value":"Only name"}])"));
  184. check (onlyName.bpm == source.bpm && onlyName.playlist[0].stretch == source.playlist[0].stretch,
  185. "Metadata-only edit changed unrelated double precision");
  186. check (remote_document::hash (remote_document::bytes (source)).size() == 64, "Document hash malformed");
  187. }
  188. // Issue #108 (MPE stage 2, round 190hy): a note's curves are saved in .lynx (the note's 20th element, three flat
  189. // [tick, value, ...] lanes), load back, leave notes without curves as they were saved before, and stay editable through
  190. // document edits (plain data arrays).
  191. void noteCurvesDocuments()
  192. {
  193. auto source = fixture();
  194. NoteCurves curves;
  195. curves.lane (NoteCurveLane::pitch) = { { 0.0f, -12.3456f }, { 480.25f, 1200.0f }, { 960.0f, -4800.0f } };
  196. curves.lane (NoteCurveLane::timbre) = { { 10.0f, 0.123456f } };
  197. curves.lane (NoteCurveLane::pressure) = { { 0.0f, 0.0f }, { 333.33f, 1.0f } };
  198. source.patterns[0].notes[1].curves = curves;
  199. source.patterns[0].notes[1].repeat = 0; // (the saved form of a note with curves only; repeats: noteRepeatDocuments)
  200. juce::String error;
  201. const auto ordinary = ProjectFile::fromJson (ProjectFile::toJson (source), error);
  202. check (ordinary.has_value(), "A project with note curves did not load");
  203. const auto& loaded = ordinary->patterns[0].notes[1].curves;
  204. check (loaded.has() && ! ordinary->patterns[0].notes[0].curves.has(), "Note curves were not saved or reached another note");
  205. for (int lane = 0; lane < noteCurveLaneCount; ++lane)
  206. {
  207. const auto& a = curves.lane ((NoteCurveLane) lane);
  208. const auto& b = loaded->lane ((NoteCurveLane) lane);
  209. check (a.size() == b.size(), "A saved curve lost points");
  210. for (std::size_t i = 0; i < a.size() && i < b.size(); ++i)
  211. check (std::abs (a[i].tick - b[i].tick) <= 0.005f && std::abs (a[i].value - b[i].value) <= (lane == 0 ? 0.005f : 0.00005f),
  212. "A saved curve point moved");
  213. }
  214. const auto exact = ProjectFile::fromJson (ProjectFile::toJsonExact (source), error);
  215. check (exact.has_value() && exact->patterns == source.patterns, "Exact documents lost note curves");
  216. // a note without curves keeps the old, shorter form (old LYNX versions read the curved note and drop its curves)
  217. const auto document = json (ProjectFile::toJson (source).toRawUTF8());
  218. const auto& notes = document["patterns"][0]["notes"];
  219. check (notes[0].size() < 20 && notes[1].size() == 20, "Note curves changed the saved form of plain notes");
  220. // document edits: a curve added to the first note through a replace of its note array
  221. auto withCurve = json (ProjectFile::toJsonExact (source).toRawUTF8())["patterns"][0]["notes"][1].clone();
  222. auto* patch = new juce::DynamicObject();
  223. patch->setProperty ("op", "replace");
  224. patch->setProperty ("path", "/patterns/0/notes/0");
  225. patch->setProperty ("value", withCurve);
  226. const auto staged = remote_document::stage (source, juce::Array<juce::var> { juce::var (patch) });
  227. check (staged.patterns[0].notes[0].curves == source.patterns[0].notes[1].curves, "A document edit could not set note curves");
  228. }
  229. // Issue #208: FL's note repeat is saved after the curves slot (null without curves) and loads back; older files and
  230. // notes without a repeat keep their form.
  231. void noteRepeatDocuments()
  232. {
  233. auto source = fixture();
  234. source.patterns[0].notes[0].repeat = 0;
  235. source.patterns[0].notes[1].repeat = 12;
  236. juce::String error;
  237. const auto ordinary = ProjectFile::fromJson (ProjectFile::toJson (source), error);
  238. check (ordinary.has_value(), "A project with a note repeat did not load");
  239. check (ordinary->patterns[0].notes[1].repeat == 12 && ordinary->patterns[0].notes[0].repeat == 0, "A note repeat was not saved");
  240. const auto document = json (ProjectFile::toJson (source).toRawUTF8());
  241. const auto& notes = document["patterns"][0]["notes"];
  242. check (notes[1].size() == 21 && notes[1][19].isVoid() && (int) notes[1][20] == 12, "A note repeat is not after an empty curves slot");
  243. check (notes[0].size() < 20, "A note without a repeat changed its saved form");
  244. NoteCurves bend;
  245. bend.lane (NoteCurveLane::pitch) = { { 0.0f, 100.0f }, { 240.0f, 0.0f } };
  246. source.patterns[0].notes[1].curves = bend;
  247. const auto both = ProjectFile::fromJson (ProjectFile::toJson (source), error);
  248. check (both.has_value() && both->patterns[0].notes[1].repeat == 12 && both->patterns[0].notes[1].curves.has(),
  249. "A note with curves and a repeat lost one of them");
  250. }
  251. void transactionValidation()
  252. {
  253. const auto source = fixture();
  254. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/bpm","value":1200}])")); });
  255. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/bpm","value":"fast"}])")); });
  256. refuses ([&] { remote_document::stage (source, json (R"([{"op":"add","path":"/unknown","value":1}])")); });
  257. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/projectId","value":"different"}])")); });
  258. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/patterns/0/notes/0/0","value":1.5}])")); });
  259. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/patterns/0/notes/0/2","value":4}])")); });
  260. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/patterns/0/uid","value":"ffffffffffffffff"}])")); });
  261. refuses ([&] { remote_document::stage (source, json (R"([{"op":"remove","path":"/patterns/0"}])")); });
  262. refuses ([&] { remote_document::stage (source, json (R"([{"op":"replace","path":"/bpm","value":140},{"op":"test","path":"/bpm","value":130}])")); });
  263. auto locked = source;
  264. locked.playlistTracks.resize (1);
  265. locked.playlistTracks[0].lockedToContent = true;
  266. refuses ([&] { remote_document::stage (locked, json (R"([{"op":"replace","path":"/playlist/0/2","value":960}])")); });
  267. const auto changed = remote_document::stage (locked, json (R"([
  268. {"op":"remove","path":"/playlistTrackLocks"},
  269. {"op":"replace","path":"/playlist/0/2","value":960}
  270. ])"));
  271. check ((changed.playlistTracks.empty() || ! changed.playlistTracks[0].lockedToContent)
  272. && changed.playlist[0].start == 960, "Explicit unlock/edit transaction failed");
  273. check (source.bpm == 130.12345678901235 && source.patterns[0].notes[0].channel == 0, "Rejected transactions changed their input");
  274. }
  275. void currentModelDocuments()
  276. {
  277. auto source = fixture();
  278. source.playlist[0].fadeInTension = 0.123456791f;
  279. source.playlist[0].fadeOutTension = -0.234567896f;
  280. source.playlist[0].linearFades = 1;
  281. source.playlist[0].flFadeFlags = 0x12345678;
  282. source.playlist[0].fadeCurve = 2;
  283. source.automations[0].lfo.on = true;
  284. source.automations[0].lfo.range = 0.345678925f;
  285. source.automations[0].lfo.amp = { { 0, 0.456789017f, -0.123456791f }, { 960, 0.765432119f, 0.234567896f } };
  286. Modulator mod;
  287. mod.name = "Preserve LFO";
  288. mod.routes.push_back ({ { AutomationTargetKind::mixerPan, 1, 0, 0 }, 0.234567896f });
  289. source.modulators.push_back (mod);
  290. source.playlistTracks.resize (1);
  291. source.playlistTracks[0].lanes.push_back ({ 0, 72 });
  292. source.playlistTracks[0].lanesFolded = true;
  293. source.clipGrid.emplace();
  294. source.clipGrid->scenes.emplace_back();
  295. source.clipGrid->slots.emplace_back();
  296. auto gridClip = source.playlist[0];
  297. gridClip.uid = 0;
  298. gridClip.start = 0;
  299. gridClip.gridSlot = 0;
  300. source.clipGrid->clips.push_back (gridClip);
  301. VideoTrack videoTrack;
  302. videoTrack.name = "Picture";
  303. videoTrack.clips.push_back ({ "/videos/existing.mp4", 0.123456789012345, 0.234567890123456, 3.345678901234567, 10.0, 99 });
  304. source.videoTracks.push_back (videoTrack);
  305. uids::normalize (source);
  306. const auto changed = remote_document::stage (source, addValue ("/patterns/0/name", "Preserved"));
  307. check (changed.playlist == source.playlist && changed.automations == source.automations
  308. && changed.modulators == source.modulators && changed.playlistTracks == source.playlistTracks
  309. && changed.clipGrid == source.clipGrid && changed.videoTracks == source.videoTracks,
  310. "A metadata edit changed clip fades, LFOs, lanes, grid clips or video tracks");
  311. refusesWith ([&] {
  312. remote_document::stage (source, addValue ("/video/tracks/0/clips/0/path", "\\\\server\\share\\new.mp4"));
  313. }, "native media, page or resource locations");
  314. refusesWith ([&] {
  315. remote_document::stage (source, json (R"([{"op":"replace","path":"/clipGrid/clips/0/clip/0/16","value":"ffffffffffffffff"}])"));
  316. }, "existing identities");
  317. auto locked = source;
  318. locked.playlistTracks[0].lockedToContent = true;
  319. refusesWith ([&] {
  320. remote_document::stage (locked, json (R"([{"op":"replace","path":"/clipGrid/clips/0/clip/0/3","value":1920}])"));
  321. }, "Unlock the Playlist row");
  322. check (locked.clipGrid == source.clipGrid && source.videoTracks[0].clips[0].path == "/videos/existing.mp4",
  323. "A refused grid or video edit changed the input");
  324. auto stopMarker = fixture();
  325. launcher::setStopButton (stopMarker, 0, 0, false);
  326. const auto unchanged = remote_document::bytes (stopMarker);
  327. refuses ([&] { remote_document::stage (stopMarker, addValue ("/patterns/0/name", "No data loss")); });
  328. check (remote_document::bytes (stopMarker) == unchanged,
  329. "A grid stop marker lost by the native loader was committed or changed its input");
  330. }
  331. void documentIoPolicy()
  332. {
  333. const auto source = fixture();
  334. refusesWith ([&] { remote_document::stage (source, addValue ("/mixer/1/recordTo", "/tmp/remote-output.wav")); },
  335. "recording output paths");
  336. refusesWith ([&] { remote_document::stage (source, addValue ("/dataFolder", "\\\\server\\share\\output")); },
  337. "output/data folders");
  338. refusesWith ([&] { remote_document::stage (source, addValue ("/channels/0/sample", "\\\\server\\share\\sample.wav")); },
  339. "introduce asset paths");
  340. auto nested = source;
  341. nested.channels[0].instrument = InstrumentKind::patcher;
  342. PatchNode node;
  343. node.generator = true;
  344. node.channel.name = "Nested";
  345. node.channel.instrument = InstrumentKind::sampler;
  346. nested.channels[0].patcher.nodes.push_back (node);
  347. refusesWith ([&] {
  348. remote_document::stage (nested, addValue ("/channels/0/patcher/nodes/0/channel/sample", "\\\\server\\share\\nested.wav"));
  349. }, "introduce asset paths");
  350. auto hosted = source;
  351. hosted.channels[0].instrument = InstrumentKind::plugin;
  352. hosted.channels[0].plugin.id = "existing-catalog-id";
  353. hosted.channels[0].plugin.name = "Existing";
  354. refusesWith ([&] { remote_document::stage (hosted, addValue ("/channels/0/plugin/id", "VST3-\\\\server\\share\\new.dll")); },
  355. "introduce plugin loader IDs");
  356. ForeignPlugin foreign;
  357. foreign.format = ForeignPlugin::Format::vst2;
  358. foreign.name = "External";
  359. foreign.path = "\\\\server\\share\\external.dll";
  360. refusesWith ([&] {
  361. remote_document::stage (hosted, addValue ("/channels/0/plugin/foreign", juce::String (foreignToText (foreign))));
  362. }, "introduce foreign plugin locations");
  363. auto assets = source;
  364. assets.channels[0].samplePath = "/samples/existing.wav";
  365. const auto document = json (ProjectFile::toJsonExact (assets).toRawUTF8());
  366. auto copy = document["channels"][0].clone();
  367. copy.getDynamicObject()->removeProperty ("uid");
  368. const auto cloned = remote_document::stage (assets, addValue ("/channels/-", copy));
  369. check (cloned.channels.size() == 2 && cloned.channels[1].samplePath == assets.channels[0].samplePath
  370. && cloned.channels[1].uid != assets.channels[0].uid, "Existing assets could not be reused by a fresh entity");
  371. copy.getDynamicObject()->setProperty ("sample", "\\\\server\\share\\new.wav");
  372. refusesWith ([&] { remote_document::stage (assets, addValue ("/channels/-", copy)); }, "introduce asset paths");
  373. check (source.mixer[1].recordTo.empty() && source.channels[0].samplePath.empty(), "I/O rejection changed its source");
  374. }
  375. void knownNativeStatePolicy()
  376. {
  377. auto notebook = fixture();
  378. EffectSlot html;
  379. html.kind = EffectKind::htmlNotebook;
  380. html.state = flextra::htmlnotebook::stateFor ("/pages/existing.html");
  381. notebook.mixer[1].effects.push_back (html);
  382. for (const auto* address : { "\\\\server\\share\\page.html", "/tmp/program.exe", "https://example.invalid/page" })
  383. refusesWith ([&] {
  384. remote_document::stage (notebook, addValue ("/mixer/1/effects/0/state", encoded (flextra::htmlnotebook::stateFor (address))));
  385. }, "native media, page or resource locations");
  386. const auto renamed = remote_document::stage (notebook, json (R"([{"op":"replace","path":"/patterns/0/name","value":"Same page"}])"));
  387. check (renamed.mixer[1].effects[0].state == html.state, "Metadata edit did not preserve an existing notebook page");
  388. auto player = fixture();
  389. player.channels[0].instrument = InstrumentKind::videoplayer;
  390. video::Settings videoSettings;
  391. videoSettings.path = "/videos/existing.mp4";
  392. player.channels[0].pluginState = video::write (videoSettings);
  393. auto incoming = videoSettings;
  394. incoming.path = "\\\\server\\share\\video.mp4";
  395. refusesWith ([&] {
  396. remote_document::stage (player, addValue ("/channels/0/pluginState", encoded (video::write (incoming))));
  397. }, "native media, page or resource locations");
  398. auto volumeOnly = videoSettings;
  399. volumeOnly.volume = 64;
  400. const auto adjustedVideo = remote_document::stage (player, addValue ("/channels/0/pluginState", encoded (video::write (volumeOnly))));
  401. check (video::readOrDefault (adjustedVideo.channels[0].pluginState).volume == 64
  402. && video::readOrDefault (adjustedVideo.channels[0].pluginState).path == videoSettings.path,
  403. "Allowlisted native state edit changed or refused an existing media resource");
  404. const auto playerDocument = json (ProjectFile::toJsonExact (player).toRawUTF8());
  405. auto newPlayer = playerDocument["channels"][0].clone();
  406. newPlayer.getDynamicObject()->removeProperty ("uid");
  407. newPlayer.getDynamicObject()->setProperty ("pluginState", encoded (video::write (incoming)));
  408. refusesWith ([&] { remote_document::stage (player, addValue ("/channels/-", newPlayer)); }, "native media, page or resource locations");
  409. auto visualizer = fixture();
  410. EffectSlot visual;
  411. visual.kind = EffectKind::visualizer;
  412. auto scene = visualfx::scene::defaultScene();
  413. visualfx::scene::Layer image;
  414. image.type = visualfx::scene::LayerType::image;
  415. image.path = "/images/existing.png";
  416. scene.layers = { image };
  417. visual.state = visualfx::scene::toState (scene);
  418. visualizer.mixer[1].effects.push_back (visual);
  419. scene.layers[0].path = "\\\\server\\share\\image.png";
  420. refusesWith ([&] {
  421. remote_document::stage (visualizer, addValue ("/mixer/1/effects/0/state", encoded (visualfx::scene::toState (scene))));
  422. }, "native media, page or resource locations");
  423. auto script = vfx::defaultScript();
  424. script.setSource ("while True:\n pass\n");
  425. vfx::State state;
  426. state.kind = vfx::Kind::script;
  427. state.fl = vfx::writeScript (script);
  428. const auto payload = vfx::writeState (state);
  429. auto noteProcessor = fixture();
  430. vfx::makeChannel (noteProcessor.channels[0], vfx::Kind::keyMapper);
  431. uids::normalize (noteProcessor);
  432. refusesWith ([&] {
  433. remote_document::stage (noteProcessor, addValue ("/channels/0/pluginState", encoded (payload)));
  434. }, "VFX Script payloads");
  435. auto processorCopy = json (ProjectFile::toJsonExact (noteProcessor).toRawUTF8())["channels"][0].clone();
  436. processorCopy.getDynamicObject()->removeProperty ("uid");
  437. processorCopy.getDynamicObject()->setProperty ("pluginState", encoded (payload));
  438. refusesWith ([&] { remote_document::stage (noteProcessor, addValue ("/channels/-", processorCopy)); }, "VFX Script payloads");
  439. auto nested = fixture();
  440. nested.channels[0].instrument = InstrumentKind::patcher;
  441. PatchNode node;
  442. node.generator = true;
  443. vfx::makeChannel (node.channel, vfx::Kind::keyMapper);
  444. nested.channels[0].patcher.nodes.push_back (node);
  445. refusesWith ([&] {
  446. remote_document::stage (nested, addValue ("/channels/0/patcher/nodes/0/channel/pluginState", encoded (payload)));
  447. }, "VFX Script payloads");
  448. }
  449. void hostedStateClearIsRejectedBeforeCommit()
  450. {
  451. auto source = fixture();
  452. const auto saved = juce::MemoryBlock ("saved state", 11).toBase64Encoding().toStdString();
  453. source.channels[0].instrument = InstrumentKind::plugin;
  454. source.channels[0].plugin.id = "Known hosted instrument";
  455. source.channels[0].plugin.state = saved;
  456. EffectSlot hosted;
  457. hosted.kind = EffectKind::plugin;
  458. hosted.plugin.id = "Known hosted effect";
  459. hosted.plugin.state = saved;
  460. source.mixer[1].effects.push_back (hosted);
  461. EffectSlot parallel;
  462. parallel.kind = EffectKind::parallel;
  463. parallel.branches.resize (1);
  464. parallel.branches[0].chain.push_back (hosted);
  465. source.mixer[1].effects.push_back (parallel);
  466. ChannelDef patcher;
  467. patcher.instrument = InstrumentKind::patcher;
  468. PatchNode node;
  469. node.generator = false;
  470. node.effect = hosted;
  471. node.busHeads.push_back ({ 1, hosted, 1.0f });
  472. patcher.patcher.nodes.push_back (node);
  473. source.channels.push_back (std::move (patcher));
  474. uids::normalize (source);
  475. const auto replacement = [&] (const Song& changed, const char* field) {
  476. juce::var document;
  477. check (juce::JSON::parse (ProjectFile::toJsonExact (changed), document).wasOk(), "Cannot build clear-state fixture");
  478. auto* operation = new juce::DynamicObject();
  479. operation->setProperty ("op", "replace");
  480. operation->setProperty ("path", juce::String ("/") + field);
  481. operation->setProperty ("value", document[field]);
  482. return juce::var (juce::Array<juce::var> { juce::var (operation) });
  483. };
  484. auto changed = source;
  485. changed.channels[0].plugin.state.clear();
  486. refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "Hosted plugin state is read-only");
  487. refusesWith ([&] { remote_document::stage (source, json (R"([{"op":"remove","path":"/channels/0/plugin/state"}])")); },
  488. "Hosted plugin state is read-only");
  489. changed = source;
  490. changed.mixer[1].effects[0].plugin.state.clear();
  491. refusesWith ([&] { remote_document::stage (source, replacement (changed, "mixer")); }, "Hosted plugin state is read-only");
  492. changed = source;
  493. changed.mixer[1].effects[1].branches[0].chain[0].plugin.state.clear();
  494. refusesWith ([&] { remote_document::stage (source, replacement (changed, "mixer")); }, "Hosted plugin state is read-only");
  495. changed = source;
  496. changed.channels[1].patcher.nodes[0].effect.plugin.state.clear();
  497. refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "Hosted plugin state is read-only");
  498. changed = source;
  499. changed.channels[1].patcher.nodes[0].busHeads[0].head->plugin.state.clear();
  500. refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "Hosted plugin state is read-only");
  501. check (source.channels[0].plugin.state == saved && source.mixer[1].effects[0].plugin.state == saved,
  502. "Clear-state rejection changed its input");
  503. // Metadata and typed wrapper routing remain editable without passing a vendor blob to a device.
  504. const auto renamed = remote_document::stage (source, json (R"([{"op":"replace","path":"/channels/0/name","value":"Renamed"}])"));
  505. check (renamed.channels[0].name == "Renamed" && renamed.channels[0].plugin.state == saved, "Metadata edit lost hosted state");
  506. changed = source;
  507. const auto other = juce::MemoryBlock ("new saved state", 15).toBase64Encoding().toStdString();
  508. changed.channels[0].plugin.state = other;
  509. refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "Hosted plugin state is read-only");
  510. for (const auto* path : { "/channels/0/plugin/state", "/mixer/1/effects/0/plugin/state",
  511. "/mixer/1/effects/1/branches/0/chain/0/plugin/state",
  512. "/channels/1/patcher/nodes/0/effect/plugin/state",
  513. "/channels/1/patcher/nodes/0/busHeads/0/head/plugin/state" })
  514. refusesWith ([&] { remote_document::stage (source, addValue (path, juce::String (other))); }, "Hosted plugin state is read-only");
  515. auto document = json (ProjectFile::toJsonExact (source).toRawUTF8());
  516. auto copy = document["channels"][0].clone();
  517. copy.getDynamicObject()->removeProperty ("uid");
  518. refusesWith ([&] { remote_document::stage (source, addValue ("/channels/-", copy)); }, "Hosted plugin state is read-only");
  519. copy = document["mixer"][1]["effects"][0].clone();
  520. refusesWith ([&] { remote_document::stage (source, addValue ("/mixer/2/effects", juce::Array<juce::var> { copy })); },
  521. "Hosted plugin state is read-only");
  522. changed = source;
  523. changed.channels[0].plugin.state = other;
  524. refusesWith ([&] { remote_document::stage (source, addValue ("", json (ProjectFile::toJsonExact (changed).toRawUTF8()))); },
  525. "Hosted plugin state is read-only");
  526. auto substitute = source;
  527. substitute.mixer[1].effects[0].kind = EffectKind::utility;
  528. substitute.mixer[1].effects[0].substituteFor = hosted.plugin;
  529. refusesWith ([&] { remote_document::stage (substitute, addValue ("/mixer/1/effects/0/substituteFor/state", juce::String (other))); },
  530. "Hosted plugin state is read-only");
  531. auto empty = source;
  532. empty.channels[0].plugin.state.clear();
  533. refusesWith ([&] { remote_document::stage (empty, addValue ("/channels/0/plugin/state", juce::String (saved))); }, "Hosted plugin state is read-only");
  534. const auto routed = remote_document::stage (source, addValue ("/channels/0/plugin/outputs", json ("[[1,1]]")));
  535. check (routed.channels[0].plugin.outputs.size() == 1 && routed.channels[0].plugin.outputs[0].offset == 1
  536. && routed.channels[0].plugin.state == saved, "Allowlisted wrapper output routing changed or refused hosted state");
  537. // Stable channel identities permit reordering without treating their saved states as new data.
  538. auto reordered = source;
  539. std::swap (reordered.channels[0], reordered.channels[1]);
  540. const auto moved = remote_document::stage (source, replacement (reordered, "channels"));
  541. check (moved.channels[1].plugin.state == saved, "Reordering stable channel identities lost hosted state");
  542. auto sameId = source;
  543. auto second = sameId.channels[0];
  544. second.uid = 0;
  545. second.plugin.state.clear();
  546. sameId.channels.push_back (second);
  547. uids::normalize (sameId);
  548. auto swapped = sameId;
  549. std::swap (swapped.channels[0], swapped.channels[2]);
  550. const auto sameIdMoved = remote_document::stage (sameId, replacement (swapped, "channels"));
  551. check (sameIdMoved.channels[0].plugin.state.empty() && sameIdMoved.channels[2].plugin.state == saved,
  552. "Reordering same-ID channels confused their stable device states");
  553. swapped = sameId;
  554. std::swap (swapped.channels[0].plugin.state, swapped.channels[2].plugin.state);
  555. refusesWith ([&] { remote_document::stage (sameId, replacement (swapped, "channels")); }, "Hosted plugin state is read-only");
  556. check (source.channels[0].plugin.state == saved && source.mixer[1].effects[0].plugin.state == saved,
  557. "Hosted-state rejection changed its input");
  558. }
  559. void documentFieldAllowlist()
  560. {
  561. auto source = fixture();
  562. source.info.title = "Original";
  563. source.info.url = "https://existing.example/project";
  564. source.info.showOnOpen = true;
  565. source.info.created = 1234.0;
  566. source.info.workSeconds = 42.0;
  567. const auto original = remote_document::bytes (source);
  568. const auto named = remote_document::stage (source, json (R"([
  569. {"op":"replace","path":"/info/title","value":"New title"},
  570. {"op":"add","path":"/info/author","value":"Producer"},
  571. {"op":"add","path":"/info/genre","value":"Electronic"},
  572. {"op":"add","path":"/info/comments","value":"Session notes"},
  573. {"op":"add","path":"/channels/0/synthSettings/chorus","value":1},
  574. {"op":"replace","path":"/patterns/0/events/0/events/0/1","value":0.5},
  575. {"op":"replace","path":"/automations/0/points/0/1","value":0.5}
  576. ])"));
  577. check (named.info.title == "New title" && named.info.author == "Producer" && named.info.genre == "Electronic"
  578. && named.info.comments == "Session notes" && named.info.url == source.info.url
  579. && named.info.showOnOpen && named.info.created == source.info.created && named.info.workSeconds == source.info.workSeconds
  580. && named.channels[0].synth.chorus == 1 && named.patterns[0].events[0].events[0].value == 0.5f
  581. && named.automations[0].points[0].value == 0.5f, "Allowlisted musical or project metadata edit failed");
  582. for (const auto* path : { "/info/url", "/info/showOnOpen", "/info/created", "/info/workSeconds" })
  583. refusesWith ([&] { remote_document::stage (source, addValue (path, juce::String (path) == "/info/url" ? juce::var ("file:///tmp/program") : juce::var (false))); },
  584. "read-only");
  585. refusesWith ([&] { remote_document::stage (source, json (R"([{"op":"remove","path":"/info"}])")); }, "read-only");
  586. auto changed = source;
  587. changed.info.url = "https://new.example/launch";
  588. refusesWith ([&] { remote_document::stage (source, addValue ("/info", json (ProjectFile::toJsonExact (changed).toRawUTF8())["info"])); },
  589. "read-only");
  590. refusesWith ([&] { remote_document::stage (source, addValue ("", json (ProjectFile::toJsonExact (changed).toRawUTF8()))); }, "read-only");
  591. refusesWith ([&] { remote_document::stage (fixture(), addValue ("/info", json (R"({"title":"Injected","url":"file:///tmp/program","showOnOpen":true})"))); },
  592. "read-only");
  593. for (const auto* path : { "/futureLoader", "/channels/0/futureLoader", "/channels/0/synthSettings/futureLoader",
  594. "/patterns/0/events/0/futureLoader", "/automations/0/futureLoader", "/mixer/1/futureLoader" })
  595. refusesWith ([&] { remote_document::stage (source, addValue (path, "file:///tmp/program")); }, "editable document allowlist");
  596. auto document = json (ProjectFile::toJsonExact (source).toRawUTF8());
  597. auto channel = document["channels"][0].clone();
  598. channel.getDynamicObject()->removeProperty ("uid");
  599. channel["synthSettings"].getDynamicObject()->setProperty ("futureLoader", "/tmp/program");
  600. refusesWith ([&] { remote_document::stage (source, addValue ("/channels/-", channel)); }, "editable document allowlist");
  601. refusesWith ([&] { remote_document::stage (source, addValue ("/patterns/0/notes/0/0", json (R"({"futureLoader":"/tmp/program"})"))); },
  602. "does not allow editable object members");
  603. const auto labeled = remote_document::stage (source, addValue ("/channels/0/keyLabels", json (R"({"60":"Middle C","127":"Top"})")));
  604. check (labeled.channels[0].keyLabels.at (60) == "Middle C", "MIDI key-label allowlist rejected a valid dictionary");
  605. refusesWith ([&] { remote_document::stage (source, addValue ("/channels/0/keyLabels", json (R"({"futureLoader":"/tmp/program"})"))); }, "MIDI keys");
  606. check (remote_document::bytes (source) == original, "Allowlist rejection changed its input");
  607. }
  608. void richDocumentAllowlist()
  609. {
  610. auto source = fixture();
  611. VideoTrack existingVideo;
  612. existingVideo.name = "Existing picture";
  613. existingVideo.clips.push_back ({ "/videos/existing.mp4", 0.0, 0.0, 2.0, 2.0, 99 });
  614. source.videoTracks.push_back (existingVideo);
  615. auto rich = source;
  616. rich.channelGroups = { "Instruments" };
  617. rich.channels[0].group = 0;
  618. rich.channels[0].keyLabels[60] = "Middle C";
  619. rich.channels[0].arp.direction = 1;
  620. rich.channels[0].misc.gateBeats = 0.5f;
  621. rich.channels[0].sampler.pitch = 3.0f;
  622. rich.channels[0].sampler.warp = { { 0.0, 0.0 }, { 1.0, 2.0 } };
  623. rich.channels[0].sampler.precompute.normalize = true;
  624. ChannelDef layered;
  625. layered.instrument = InstrumentKind::layer;
  626. layered.layer.children = { 0 };
  627. rich.channels.push_back (layered);
  628. EffectSlot parallel;
  629. parallel.kind = EffectKind::parallel;
  630. parallel.branches.resize (1);
  631. parallel.branches[0].chain.emplace_back();
  632. rich.mixer[1].effects.push_back (parallel);
  633. ChannelDef patcher;
  634. patcher.instrument = InstrumentKind::patcher;
  635. PatchNode node;
  636. node.effect.kind = EffectKind::utility;
  637. node.label = "Bus processor";
  638. node.paramIns = { 0 };
  639. node.busHeads.push_back ({ 1, node.effect, 0.5f });
  640. patcher.patcher.nodes.push_back (node);
  641. rich.channels.push_back (patcher);
  642. Modulator modulator;
  643. modulator.name = "LFO";
  644. modulator.routes.push_back ({ { AutomationTargetKind::mixerPan, 1, 0, 0 }, 0.25f });
  645. rich.modulators.push_back (modulator);
  646. Vca vca;
  647. vca.name = "Band";
  648. vca.members = { 1, 2 };
  649. rich.vcas.push_back (vca);
  650. rich.clipGrid.emplace();
  651. rich.clipGrid->scenes.emplace_back();
  652. rich.clipGrid->scenes[0].name = "Scene";
  653. rich.clipGrid->slots.emplace_back();
  654. auto gridClip = source.playlist[0];
  655. gridClip.uid = 0;
  656. gridClip.start = 0;
  657. gridClip.gridSlot = 0;
  658. rich.clipGrid->clips.push_back (gridClip);
  659. VideoTrack video;
  660. video.name = "Picture";
  661. video.clips.push_back ({ "/videos/existing.mp4", 0.0, 0.0, 2.0, 2.0, 0 });
  662. rich.videoTracks.push_back (video);
  663. AdrCue cue;
  664. cue.id = "101";
  665. cue.out = 2.0;
  666. cue.line = "Dialogue";
  667. cue.takes.emplace_back();
  668. cue.takes[0].clip = source.playlist[0].uid;
  669. cue.takes[0].note = "First take";
  670. rich.adr.cues.push_back (cue);
  671. auto document = json (ProjectFile::toJsonExact (rich).toRawUTF8());
  672. const auto accepted = remote_document::stage (source, addValue ("", document));
  673. check (accepted.channels.size() == 3 && accepted.channels[0].keyLabels.at (60) == "Middle C"
  674. && accepted.channels[0].sampler.warp.size() == 2 && accepted.channels[1].layer.children == layered.layer.children
  675. && accepted.channels[2].patcher.nodes[0].busHeads.size() == 1
  676. && accepted.mixer[1].effects[0].branches[0].chain.size() == 1 && accepted.modulators.size() == 1
  677. && accepted.vcas.size() == 1 && accepted.clipGrid->slots.size() == 1 && accepted.videoTracks.size() == 2
  678. && accepted.adr.cues[0].takes[0].note == "First take", "Allowlist discarded a supported rich native object/tuple workflow");
  679. for (const auto* path : { "/channels/2/patcher/nodes/0/futureLoader",
  680. "/channels/2/patcher/nodes/0/busHeads/0/head/futureLoader",
  681. "/mixer/1/effects/0/branches/0/chain/0/futureLoader",
  682. "/clipGrid/clips/0/futureLoader", "/video/tracks/0/clips/0/futureLoader",
  683. "/adr/cues/0/takes/0/futureLoader" })
  684. refusesWith ([&] { remote_document::stage (accepted, addValue (path, "file:///tmp/program")); }, "editable document allowlist");
  685. }
  686. // Round 190ha: fields LYNX gained after the allowlist was first written. An edit of an object that carries them is
  687. // accepted; the values a live session shares, racks and the groove pool pass through unchanged and stay read-only.
  688. void currentFieldsAllowlist()
  689. {
  690. auto base = fixture();
  691. ChannelDef hosted;
  692. hosted.name = "Hosted";
  693. hosted.instrument = InstrumentKind::plugin;
  694. hosted.plugin.id = "vst3:existing";
  695. hosted.plugin.name = "Existing";
  696. hosted.plugin.playedBy = 7;
  697. hosted.plugin.values = { { 0, 0.5f } };
  698. base.channels.push_back (hosted);
  699. ChannelDef racked;
  700. racked.name = "Rack";
  701. racked.instrument = InstrumentKind::patcher;
  702. racked.patcher = rack::makeRack (RackDoc::Kind::instrument);
  703. base.channels.push_back (racked);
  704. Groove groove;
  705. groove.id = 1;
  706. groove.name = "Swing";
  707. groove.points.push_back ({ 240, 0.25f });
  708. base.grooves.grooves.push_back (groove);
  709. uids::normalize (base);
  710. auto rich = base;
  711. auto& plugin = rich.channels[1].plugin;
  712. plugin.mpe = true;
  713. plugin.processInactive = false;
  714. plugin.pinned = true;
  715. plugin.velocityMode = prefs::pluginVelocityFixed;
  716. plugin.fixedVelocity = 90;
  717. plugin.inputs = { { 2, 1 } };
  718. rich.channels[0].cutOthersOnly = true;
  719. rich.channels[0].cutAtNoteEnd = true;
  720. rich.channels[0].simplePad = { 3, 1, 0.25f, 0.5f, 1, 2 };
  721. rich.channels[0].editorScale = 150; // (rollup 0.1.28: round 190he's per-channel window Scaling, editable)
  722. rich.mixer[1].sends[0].pre = true;
  723. rich.mixer[1].chainBlend = 0.123456791f;
  724. rich.mixer[1].chainPreset = "Vocal";
  725. rich.mixer[1].slotRows = 14; // (PR #260, round 190qf: FL 2026.2's slot rows, editable)
  726. EffectSlot knob;
  727. knob.kind = EffectKind::utility;
  728. knob.look = 1;
  729. knob.goal = 2;
  730. knob.goalAmount = 0.234567896f;
  731. rich.mixer[1].effects.push_back (knob);
  732. rich.beatUnit = 8;
  733. rich.muteRunsEffects = rich.patternClipTakeover = rich.mutedInsertsSkip = rich.flPluginLevels = rich.loopOff = true;
  734. rich.tempoViewLow = 90.0;
  735. rich.tempoViewHigh = 150.0;
  736. rich.clipGrid.emplace();
  737. rich.clipGrid->scenes.emplace_back();
  738. rich.clipGrid->scenes[0].beatsPerBar = 6;
  739. rich.clipGrid->scenes[0].beatUnit = 8;
  740. const auto document = json (ProjectFile::toJsonExact (rich).toRawUTF8());
  741. const auto accepted = remote_document::stage (base, addValue ("", document));
  742. const auto& p = accepted.channels[1].plugin;
  743. check (p.mpe && ! p.processInactive && p.pinned && p.velocityMode == prefs::pluginVelocityFixed && p.fixedVelocity == 90
  744. && p.inputs == plugin.inputs && p.playedBy == 7 && p.values == hosted.plugin.values
  745. && accepted.channels[0].cutOthersOnly && accepted.channels[0].cutAtNoteEnd && accepted.channels[0].simplePad == rich.channels[0].simplePad && accepted.channels[0].editorScale == 150
  746. && accepted.mixer[1].sends[0].pre && accepted.mixer[1].chainBlend == 0.123456791f && accepted.mixer[1].chainPreset == "Vocal" && accepted.mixer[1].slotRows == 14
  747. && accepted.mixer[1].effects[0].goalAmount == 0.234567896f && accepted.mixer[1].effects[0].look == 1
  748. && accepted.beatUnit == 8 && accepted.muteRunsEffects && accepted.flPluginLevels && accepted.loopOff
  749. && accepted.tempoViewHigh == 150.0 && accepted.clipGrid->scenes[0].beatUnit == 8
  750. && accepted.channels[2].patcher.isRack() && accepted.grooves == base.grooves,
  751. "Allowlist refused or discarded a field added since it was written");
  752. const auto edited = remote_document::stage (accepted, json (R"([
  753. {"op":"replace","path":"/channels/1/plugin/fixedVelocity","value":64},
  754. {"op":"replace","path":"/channels/2/name","value":"Keys rack"},
  755. {"op":"replace","path":"/bpm","value":128}
  756. ])"));
  757. check (edited.channels[1].plugin.fixedVelocity == 64 && edited.channels[2].name == "Keys rack" && edited.bpm == 128.0,
  758. "An edit next to read-only plugin, rack or groove data was refused");
  759. for (const auto& [path, value] : { std::pair { "/channels/1/plugin/playedBy", juce::var (8) },
  760. std::pair { "/channels/1/plugin/values", json ("[0, 0.25]") },
  761. std::pair { "/channels/2/patcher/rack/name", juce::var ("Changed") },
  762. std::pair { "/grooves/amount", juce::var (0.5) } })
  763. refusesWith ([&] { remote_document::stage (accepted, addValue (path, value)); }, "read-only");
  764. }
  765. // Round 190lq (issue #204): FL's law for the notes of an audio clip channel (whole clip, layered, key-transposed) is the
  766. // default; a project saved before the "clipNotes190lq" mark keeps LYNX's earlier law on its audio clip channels, and that
  767. // survives a save / open
  768. void audioClipNoteLaw190lq()
  769. {
  770. Song song;
  771. ChannelDef clip;
  772. clip.instrument = InstrumentKind::audioClip;
  773. clip.name = "Clip";
  774. ChannelDef sampler;
  775. sampler.instrument = InstrumentKind::sampler;
  776. sampler.name = "Sampler";
  777. song.channels = { clip, sampler };
  778. check (! song.channels[0].sampler.clipNoteLegacy, "A new audio clip channel is on FL's law");
  779. juce::String error;
  780. const auto saved = ProjectFile::toJson (song);
  781. check (saved.contains ("\"clipNotes190lq\""), "A save writes the mark");
  782. check (! saved.contains ("clipNoteLegacy"), "FL's law is not written per channel");
  783. auto reopened = ProjectFile::fromJson (saved, error);
  784. check (reopened.has_value() && ! reopened->channels[0].sampler.clipNoteLegacy, "A marked project keeps FL's law");
  785. // an older project (no mark): its audio clip channels keep the legacy law, other channels are left alone
  786. const auto old = saved.replace ("\"clipNotes190lq\"", "\"someOtherMark\"");
  787. auto legacy = ProjectFile::fromJson (old, error);
  788. check (legacy.has_value() && legacy->channels[0].sampler.clipNoteLegacy, "An older project's audio clip channel is legacy");
  789. check (! legacy->channels[1].sampler.clipNoteLegacy, "An older project's Sampler is not touched");
  790. // saved again by this build: the legacy channel stays legacy
  791. const auto resaved = ProjectFile::toJson (*legacy);
  792. check (resaved.contains ("\"clipNotes190lq\"") && resaved.contains ("\"clipNoteLegacy\""), "The legacy law is written per channel");
  793. auto again = ProjectFile::fromJson (resaved, error);
  794. check (again.has_value() && again->channels[0].sampler.clipNoteLegacy && ! again->channels[1].sampler.clipNoteLegacy,
  795. "The legacy law survives a save and open");
  796. }
  797. void discoveryCleanup()
  798. {
  799. const auto directory = juce::File::getCurrentWorkingDirectory()
  800. .getChildFile ("lynx-control-test-" + remote_files::randomToken());
  801. struct Cleanup
  802. {
  803. juce::File directory;
  804. ~Cleanup() { directory.deleteRecursively(); }
  805. } cleanup { directory };
  806. const auto file = directory.getChildFile ("connection.json");
  807. const juce::String record = R"({"token":"owned"})";
  808. remote_files::writeDiscovery (file, record);
  809. remote_files::removeDiscoveryIfOwned (file, "another process");
  810. check (file.existsAsFile(), "Cleanup removed another process's discovery record");
  811. remote_files::removeDiscoveryIfOwned (file, "owned");
  812. check (! file.exists(), "Cleanup kept its own discovery record");
  813. // The original crash payload must also be harmless during disable/shutdown.
  814. for (const auto size : { 16384, 100000 })
  815. {
  816. remote_files::writeDiscovery (file, juce::String (std::string ((std::size_t) size, '[')));
  817. remote_files::removeDiscoveryIfOwned (file, "owned");
  818. check (file.existsAsFile(), "Cleanup removed a malformed discovery record");
  819. }
  820. // JUCE's release parser accepts overlong UTF-8 as recursive array brackets.
  821. // The raw-byte gate must reject it before parsing even with a matching token.
  822. std::string invalidUtf8 = R"({"token":"owned","deep":)";
  823. for (int i = 0; i < 32; ++i) invalidUtf8 += "\xc1\x9b";
  824. invalidUtf8 += "0";
  825. for (int i = 0; i < 32; ++i) invalidUtf8 += "\xc1\x9d";
  826. invalidUtf8 += "}";
  827. // Keep malformed bytes outside JUCE strings: release-build conversion itself
  828. // can corrupt memory before JSON parsing, so the raw gate must run first.
  829. check (! remote_json::withinNestingLimit (invalidUtf8, 8), "Noncanonical UTF-8 passed the pre-conversion gate");
  830. {
  831. auto output = file.createOutputStream();
  832. check (output != nullptr && output->setPosition (0) && output->truncate().wasOk()
  833. && output->write (invalidUtf8.data(), invalidUtf8.size()), "Could not write malformed UTF-8 discovery fixture");
  834. output->flush();
  835. }
  836. remote_files::removeDiscoveryIfOwned (file, "owned");
  837. check (file.existsAsFile(), "Cleanup parsed a noncanonical UTF-8 discovery record");
  838. const juce::String unicodeRecord = juce::String::fromUTF8 ("{\"token\":\"owned\",\"name\":\""
  839. "\xe9\x9f\xb3\xe6\xa8\x82\xf0\x9f\x8e\xb5\"}");
  840. remote_files::writeDiscovery (file, unicodeRecord);
  841. remote_files::removeDiscoveryIfOwned (file, "owned");
  842. check (! file.exists(), "Cleanup rejected a canonical Unicode discovery record");
  843. // An oversized record with a valid prefix must be rejected rather than parsed
  844. // from a truncated buffer. A record at the byte limit remains valid.
  845. remote_files::writeDiscovery (file, record + juce::String::repeatedString (" ", 16385 - record.length()));
  846. remote_files::removeDiscoveryIfOwned (file, "owned");
  847. check (file.existsAsFile(), "Cleanup accepted an oversized discovery record");
  848. remote_files::writeDiscovery (file, record + juce::String::repeatedString (" ", 16384 - record.length()));
  849. remote_files::removeDiscoveryIfOwned (file, "owned");
  850. check (! file.exists(), "Cleanup rejected a discovery record at the byte limit");
  851. }
  852. }
  853. int main()
  854. {
  855. const char* activeTest = "initialization";
  856. const auto run = [&] (const char* name, auto test) { activeTest = name; test(); };
  857. try
  858. {
  859. run ("patchSemantics", patchSemantics);
  860. run ("exactDocuments", exactDocuments);
  861. run ("remoteNotesRoundtrip", remoteNotesRoundtrip);
  862. run ("noteCurvesDocuments", noteCurvesDocuments);
  863. run ("noteRepeatDocuments", noteRepeatDocuments);
  864. run ("transactionValidation", transactionValidation);
  865. run ("currentModelDocuments", currentModelDocuments);
  866. run ("documentIoPolicy", documentIoPolicy);
  867. run ("hostedStateClearIsRejectedBeforeCommit", hostedStateClearIsRejectedBeforeCommit);
  868. run ("documentFieldAllowlist", documentFieldAllowlist);
  869. run ("richDocumentAllowlist", richDocumentAllowlist);
  870. run ("currentFieldsAllowlist", currentFieldsAllowlist);
  871. run ("knownNativeStatePolicy", knownNativeStatePolicy);
  872. run ("discoveryCleanup", discoveryCleanup);
  873. run ("audioClipNoteLaw190lq", audioClipNoteLaw190lq);
  874. std::puts ("Remote JSON Patch, exact project documents, atomic staging and discovery cleanup tests passed");
  875. return 0;
  876. }
  877. catch (const std::exception& error)
  878. {
  879. std::fprintf (stderr, "%s: %s\n", activeTest, error.what());
  880. return 1;
  881. }
  882. }