diff --git a/CMakeLists.txt b/CMakeLists.txt index ab6f1cd81..310d3a859 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -436,6 +436,19 @@ if(BUILD_TESTING) target_compile_features(ARMixDurableMixerSessionTests PRIVATE cxx_std_20) target_compile_definitions(ARMixDurableMixerSessionTests PRIVATE JUCE_MODAL_LOOPS_PERMITTED=1) add_test(NAME P0DynamicMixerSessionDocumentAndCrashSafeRecovery COMMAND ARMixDurableMixerSessionTests) + # H1 OS-global shortcut registration and stable identity are control-only. + juce_add_console_app(ARMixNativeHotkeyTests PRODUCT_NAME "ArSonMix Native Hotkey Registry Tests") + target_sources(ARMixNativeHotkeyTests PRIVATE tests/native_hotkey_registry_test.cpp + src/NativeHotkeyRegistry.h) + target_link_libraries(ARMixNativeHotkeyTests PRIVATE + juce::juce_core juce::juce_recommended_config_flags) + if(WIN32) + target_link_libraries(ARMixNativeHotkeyTests PRIVATE user32 comctl32) + endif() + target_compile_features(ARMixNativeHotkeyTests PRIVATE cxx_std_20) + add_test(NAME H1NativeGlobalShortcutRegistrationConflictAndPersistence + COMMAND ARMixNativeHotkeyTests) + # Presentation-only native identity; no audio-thread access. juce_add_console_app(ARMixChannelAppearanceTests PRODUCT_NAME "ArSonMix Channel Appearance Tests") target_sources(ARMixChannelAppearanceTests PRIVATE diff --git a/engine/core/LiveChannelFxGraph.h b/engine/core/LiveChannelFxGraph.h index ed374c3e8..0c32f3edb 100644 --- a/engine/core/LiveChannelFxGraph.h +++ b/engine/core/LiveChannelFxGraph.h @@ -50,13 +50,32 @@ class LiveChannelFxGraph final { std::atomic exceptions{0}; FxInstance(std::unique_ptr p,juce::String id,juce::String label, - int maxSamples) + int maxSamples,juce::String restoredInstance={}) : processor(std::move(p)),catalogId(std::move(id)),name(std::move(label)), - instanceId("g5c-"+juce::String(static_cast( - nextId.fetch_add(1,std::memory_order_relaxed)))), + // A restored .smix insert retains the SAME logical identity. + // Newly-added FX still receive a fresh per-process token. + instanceId(restoredInstance.isNotEmpty()?std::move(restoredInstance): + "g5c-"+juce::String(static_cast( + nextId.fetch_add(1,std::memory_order_relaxed)))), latencySamples(processor?processor->getLatencySamples():0), dryLeft(static_cast(maxSamples)), dryRight(static_cast(maxSamples)) { + // CONTROL thread only. A restored ID must reserve its numeric + // space before subsequent Add FX operations in this process. + // The codec validates the prefix and decimal range; no RT work. + const auto number=instanceId.startsWith("g5c-")? + instanceId.substring(4):juce::String{}; + if(number.isNotEmpty() && number.length()<=18 && + number.containsOnly("0123456789")) { + const auto raw=number.getLargeIntValue(); + if(raw>0) { + const auto next=static_cast(raw)+1u; + auto observed=nextId.load(std::memory_order_relaxed); + while(observedgetSampleRate():48000.0,0); diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index d0bd9b720..43db33593 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2276,7 +2276,8 @@ class LiveDryRoutingLab final { const auto hash=juce::SHA256(bytes).toHexString(); draft.inserts.push_back({channel.id,slot,(*owner)->catalogId, {},hash,(*owner)->name,0, - (*owner)->bypassRequested.load(std::memory_order_acquire)}); + (*owner)->bypassRequested.load(std::memory_order_acquire), + (*owner)->instanceId}); if(hashes.insert(hash).second) { armix::shows::BinaryState entry; entry.sha256=hash;entry.bytes=std::move(bytes); diff --git a/src/Main.cpp b/src/Main.cpp index 1fe70e22c..8fd58c156 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -38,6 +38,7 @@ #include "NativeChannelAppearanceStore.h" #include "NativeMixerSessionSaveWorker.h" #include "NativeLogicalMixerControl.h" +#include "NativeHotkeyRegistry.h" #include "NativeDeviceApplyCoordinator.h" #include #include @@ -273,6 +274,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr .withEventListener ("arMixLogicalIntent", [this] (juce::var args) { handleLogicalMixerIntent(args); }) + .withEventListener ("arMixHotkeyIntent", [this] (juce::var args) { + handleNativeHotkeyIntent(args); + }) + .withEventListener ("arMixHotkeyCapture", [this] (juce::var args) { + hotkeys_.setCaptureMode(args.getProperty("enabled",false)==juce::var(true)); + }) .withEventListener ("arMixConsoleSubscribe", [this] (juce::var) { // G0 real-device native producer, NEVER a synthetic ChannelId callback. consoleSubscribed_ = true; @@ -295,6 +302,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr .withResourceProvider (assetFor)) { settingsDirectory().createDirectory(); + hotkeys_.setHandler([this](const armix::hotkey::Mapping& mapping) { + fireNativeHotkey(mapping); + }); restorePlayerLibrary(); // portable, local song paths only; NEVER autoplay on launch catalog_.onChanged = [this] { emitCatalog(); emitScanProgress(); }; catalog_.scanFactoryIfPresent(); // Only the signed-off local manifest; never global VST scans. @@ -349,6 +359,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr ~ConsoleWindow() override { + hotkeys_.detach(); // release global keys before the JUCE HWND disappears stopTimer(); orbit_.stop(); catalog_.onChanged = nullptr; @@ -397,6 +408,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr armix::storage::NativePresetArchive presets_; std::function onStartupStage_; Browser browser_; + armix::hotkey::Registry hotkeys_{settingsDirectory()}; + juce::StringArray consumedHotkeyRequests_; + std::uint64_t firedHotkeySerial_=0; armix::storage::StudioBackup::Worker studioBackupWorker_; armix::shows::NativeShowSaveWorker nativeShowWorker_; armix::session::NativeMixerSessionSaveWorker mixerSessionWorker_; @@ -1076,7 +1090,18 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto [found,error]=logicalMixer_.ensureLoaded(); if(found && !mixerSessionStartupInspected_) mixerSessionRecoveryPending_=true; - if(error.isEmpty())return; + if(error.isEmpty()) { + if(found && hotkeys_.activeSession()!=logicalMixer_.workspace().document().id) { + const auto& document=logicalMixer_.workspace().document(); + (void)hotkeys_.activateSession(document.id); + // Local shortcut journal is newer than checkpoint on crash. + if(hotkeys_.sessionEntries().empty() && !document.hotkeys.empty()) { + const auto issue=hotkeys_.activateSession(document.id,&document.hotkeys); + if(issue.isNotEmpty())diagnostics_.record("HOTKEY_IMPORT_REJECTED",issue); + } + } + return; + } mixerSessionRecoveryPending_=true; mixerSessionStatus_="DAMAGED_SESSION"; mixerSessionError_=error; @@ -1227,6 +1252,226 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr reply("Offline FX settings could not be saved"); } + // Native hotkeys share the accepted ChannelId mixer control path. + // WM_HOTKEY is delivered on the JUCE message thread even while the + // WebView is minimized, and never synthesizes a browser mouse click. + void sendHotkeyRegistry(const juce::String& requestId={}, + const juce::String& error={}) { + auto state=hotkeys_.snapshot(); + const auto accepted=approvedNativeSnapshot(); + const auto graph=accepted.getProperty("graph",{}); + const auto caps=graph.getProperty("capabilities",{}); + const auto channels=graph.getProperty("channels",{}); + const auto ops=caps.getProperty("supportedOps",{}); + const auto* permitted=ops.getArray(); + const bool admitted=static_cast( + caps.getProperty("callbackOwnsChannelIds",false)); + const auto rows=state.getProperty("entries",{}); + if(auto* entries=rows.getArray())for(auto& row:*entries) { + if(row.getProperty("scope","").toString()!="SESSION")continue; + const auto id=row.getProperty("channelId","").toString(); + const auto op=row.getProperty("operation","").toString(); + bool found=false,fxAvailable=false; + if(channels.isArray())for(const auto& channel:*channels.getArray()) { + if(channel.getProperty("id","").toString()!=id || + (channel.getProperty("role","").toString()!="INPUT" && + channel.getProperty("role","").toString()!="GROUP" && + channel.getProperty("role","").toString()!="FX_RETURN"))continue; + found=true; + if(op=="SET_FX_RACK_BYPASS") + fxAvailable=channel.getProperty("fxRackBypassed",{}).isBool(); + else if(op=="SET_FX_SLOT_BYPASS") { + const auto inserts=channel.getProperty("inserts",{}); + const int slot=static_cast(row.getProperty("slot",-1)); + if(auto* all=inserts.getArray())if(slot>=0&&slotsize()) + fxAvailable=all->getReference(slot).getProperty("id","").toString()== + row.getProperty("insertId","").toString(); + } + break; + } + const bool fx=op=="SET_FX_RACK_BYPASS"||op=="SET_FX_SLOT_BYPASS"; + const juce::String status= + !admitted?"WAITING_NATIVE_AUDIO": + !found?"NEEDS_REMAP": + fx&&!fxAvailable?"NEEDS_REMAP": + (!fx&&(!permitted||!permitted->contains(juce::var(op))))? + "ACTION_UNAVAILABLE": + row.getProperty("status","").toString(); + row.getDynamicObject()->setProperty("status",status); + } + if(requestId.isNotEmpty()) { + state.getDynamicObject()->setProperty("requestId",requestId); + state.getDynamicObject()->setProperty("status", + error.isEmpty()?"ACCEPTED":"REJECTED"); + state.getDynamicObject()->setProperty("errorCode", + error.isEmpty()?"NONE":error); + } + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible("arMixHotkeyRegistry",state); + } + + void handleNativeHotkeyIntent(const juce::var& args) { + const auto action=args.getProperty("operation","").toString(); + const auto requestId=args.getProperty("requestId","").toString(); + if(action=="LIST")return sendHotkeyRegistry(); + // Capture releases OS chords; restore registrations before Save. + hotkeys_.setCaptureMode(false); + juce::String error; + if(requestId.isEmpty()||requestId.length()>96 || + consumedHotkeyRequests_.contains(requestId)) + error="INVALID_OR_DUPLICATE_HOTKEY_REQUEST"; + else { + consumedHotkeyRequests_.add(requestId); + if(consumedHotkeyRequests_.size()>128) + consumedHotkeyRequests_.remove(0); + if(action=="DELETE") { + const auto id=args.getProperty("mappingId",{}).toString(); + error=hotkeys_.remove(id); + } else if(action=="REGISTER") { + const auto supplied=args.getProperty("mapping",{}); + const auto scope=supplied.getProperty("scope","").toString(); + auto cleaned=juce::var(new juce::DynamicObject()); + for(const char* field:{"id","scope","sessionId","channelId", + "operation","vk","modifiers","slot","insertId"}) { + const auto value=supplied.getProperty(field,{}); + if(!value.isVoid())cleaned.getDynamicObject()->setProperty(field,value); + } + if(scope=="SESSION") { + const auto accepted=approvedNativeSnapshot(); + const auto graph=accepted.getProperty("graph",{}); + const auto channels=graph.getProperty("channels",{}); + const auto caps=graph.getProperty("capabilities",{}); + const auto id=supplied.getProperty("channelId",{}).toString(); + const auto op=supplied.getProperty("operation","").toString(); + const bool fxRack=op=="SET_FX_RACK_BYPASS"; + const bool fxSlot=op=="SET_FX_SLOT_BYPASS"; + bool found=false,fxAvailable=false; + if(static_cast(caps.getProperty("callbackOwnsChannelIds",false)) && + channels.isArray())for(const auto& c:*channels.getArray()) { + if(c.getProperty("id","").toString()!=id || + (c.getProperty("role","").toString()!="INPUT" && + c.getProperty("role","").toString()!="GROUP" && + c.getProperty("role","").toString()!="FX_RETURN"))continue; + found=true; + if(fxRack)fxAvailable=c.getProperty("fxRackBypassed",{}).isBool(); + else if(fxSlot) { + const auto inserts=c.getProperty("inserts",{}); + const auto slot=supplied.getProperty("slot",{}); + const auto token=supplied.getProperty("insertId",{}); + if(slot.isInt()&&token.isString()&&inserts.isArray()) { + const int index=static_cast(slot); + if(index>=0&&indexsize()) + fxAvailable=inserts.getArray()->getReference(index) + .getProperty("id","").toString()==token.toString(); + } + } + break; + } + if(!found)error="HOTKEY_CHANNEL_NOT_ADMITTED"; + if(error.isEmpty()&&(fxRack||fxSlot)&&!fxAvailable) + error="HOTKEY_FX_INSTANCE_NOT_ADMITTED"; + const auto ops=caps.getProperty("supportedOps",{}); + const auto* allowed=ops.getArray(); + if(error.isEmpty() && !fxRack && !fxSlot && + op!="SET_MUTE" && op!="SET_SOLO") + error="HOTKEY_ACTION_UNSUPPORTED"; + if(error.isEmpty() && !fxRack && !fxSlot && + (!allowed || !allowed->contains(juce::var(op)))) + error="HOTKEY_ACTION_NOT_ADMITTED"; + if(error.isEmpty()) { + if(mixerSessionId_.isEmpty()) + mixerSessionId_=juce::Uuid().toDashedString().toLowerCase(); + if(hotkeys_.activeSession()!=mixerSessionId_) + hotkeys_.activateSession(mixerSessionId_); + cleaned.getDynamicObject()->setProperty("sessionId",mixerSessionId_); + } + } + armix::hotkey::Mapping mapping; + if(error.isEmpty() && !armix::hotkey::Registry::decode(cleaned,mapping)) + error="INVALID_HOTKEY_MAPPING"; + if(error.isEmpty())error=hotkeys_.upsert(std::move(mapping)); + } else error="UNSUPPORTED_HOTKEY_OPERATION"; + } + sendHotkeyRegistry(requestId,error); + } + + void fireNativeHotkey(const armix::hotkey::Mapping& mapping) { + if(mapping.operation=="PANIC_MUTE") { + engine_.setOutputMuted(true); + emitApprovedNativeSnapshot(); + return; + } + if(mapping.scope!="SESSION" || + mapping.sessionId!=mixerSessionId_ || deviceApply_.busy() || + nativeShowBusy_ || studioBackupBusy_ || engine_.isGraphSwitchPending()) + return; + const auto accepted=approvedNativeSnapshot(); + const auto graph=accepted.getProperty("graph",{}); + if(!static_cast(graph.getProperty("capabilities",{}) + .getProperty("callbackOwnsChannelIds",false)))return; + const auto channels=graph.getProperty("channels",{}); + if(!channels.isArray())return; + const juce::var* match=nullptr; + for(const auto& ch:*channels.getArray()) + if(ch.getProperty("id","").toString()==mapping.channelId && + (ch.getProperty("role","").toString()=="INPUT" || + ch.getProperty("role","").toString()=="GROUP" || + ch.getProperty("role","").toString()=="FX_RETURN")) { + match=&ch;break; + } + if(!match)return; + const bool fxRack=mapping.operation=="SET_FX_RACK_BYPASS"; + const bool fxSlot=mapping.operation=="SET_FX_SLOT_BYPASS"; + if(fxRack||fxSlot) { + juce::var bypass; + if(fxRack)bypass=match->getProperty("fxRackBypassed",{}); + else { + const auto inserts=match->getProperty("inserts",{}); + if(!inserts.isArray()||mapping.slot<0|| + mapping.slot>=inserts.getArray()->size())return; + const auto insert=inserts.getArray()->getReference(mapping.slot); + // Fail closed: if a plugin was replaced or reordered, hotkey + // must never touch the different processor at the same slot. + if(insert.getProperty("id","").toString()!=mapping.insertId)return; + bypass=insert.getProperty("bypassed",{}); + } + if(!bypass.isBool())return; + auto native=juce::var(new juce::DynamicObject()); + auto* n=native.getDynamicObject(); + n->setProperty("action",fxRack?"routingNativeFxRackBypass": + "routingNativeFxInsertBypass"); + n->setProperty("requestId","hotkey-fx-"+juce::String( + static_cast(++firedHotkeySerial_))); + n->setProperty("channelId",mapping.channelId); + n->setProperty("deviceEpoch",accepted.getProperty("device",{}).getProperty("epoch","0")); + n->setProperty("revision",graph.getProperty("revision","0")); + n->setProperty("value",!static_cast(bypass)); + if(fxSlot) { + n->setProperty("slot",mapping.slot); + n->setProperty("insertId",mapping.insertId); + } + // Exact same owner, guardrails and ACK as GUI rack/slot Power. + onAction(native); + return; + } + if(mapping.operation!="SET_MUTE"&&mapping.operation!="SET_SOLO")return; + const auto control=mapping.operation=="SET_MUTE"?"mute":"solo"; + const auto existing=match->getProperty("controls",{}).getProperty(control,{}); + if(!existing.isBool())return; + auto payload=juce::var(new juce::DynamicObject()); + payload.getDynamicObject()->setProperty("value",!static_cast(existing)); + auto request=juce::var(new juce::DynamicObject()); + auto* o=request.getDynamicObject(); + o->setProperty("requestId","hotkey-"+juce::String(static_cast(++firedHotkeySerial_))); + o->setProperty("operation",mapping.operation); + o->setProperty("targetChannelId",mapping.channelId); + o->setProperty("deviceEpoch",accepted.getProperty("device",{}).getProperty("epoch","0")); + o->setProperty("baseGraphRevision",graph.getProperty("revision","0")); + o->setProperty("baseRosterRevision",graph.getProperty("rosterRevision","0")); + o->setProperty("payload",payload); + handleApprovedNativeControl(request); + } + void handleLogicalMixerIntent(const juce::var& request) { const auto snapshot=approvedNativeSnapshot(); logicalMixer_.handleIntent(request,{ @@ -2704,10 +2949,16 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return error; } mixerSessionId_=doc.id; + const auto restoredHotkeys=doc.hotkeys; if(usedPrevious) (void)logicalMixer_.restoreCheckpoint(doc,states); const bool firstBinding=doc.logicalOnly; if(firstBinding && !engine_.hasPristineStartupMixer()) { + (void)hotkeys_.activateSession(mixerSessionId_); + if(hotkeys_.sessionEntries().empty() && !restoredHotkeys.empty()) { + const auto issue=hotkeys_.activateSession(mixerSessionId_,&restoredHotkeys); + if(issue.isNotEmpty())diagnostics_.record("HOTKEY_IMPORT_REJECTED",issue); + } mixerSessionRecoveryPending_=true; mixerSessionStatus_="LOGICAL_SESSION_SAVED_UNBOUND"; return "Saved mixer is offline and awaiting verified device binding"; @@ -2760,6 +3011,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return error; } mixerSessionRecoveryPending_=false; + (void)hotkeys_.activateSession(mixerSessionId_); + if(hotkeys_.sessionEntries().empty() && !restoredHotkeys.empty()) { + const auto issue=hotkeys_.activateSession(mixerSessionId_,&restoredHotkeys); + if(issue.isNotEmpty())diagnostics_.record("HOTKEY_IMPORT_REJECTED",issue); + } if(resume)requestAutomaticMain(bindingMode!=MixerBindingMode::verifiedAsioRestart); mixerSessionStatus_=engine_.isMonitorEnabled()?"RESTORED_MONITORING":"RESTORED_MUTED"; mixerSessionError_.clear(); @@ -2810,6 +3066,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(automatic)doc.resumeMain=resumeMain; doc.id=mixerSessionId_.isNotEmpty()?mixerSessionId_: juce::Uuid().toDashedString().toLowerCase(); + // Shortcut entries are additive .smix data, never callback state. + if(hotkeys_.activeSession()==doc.id) + doc.hotkeys=hotkeys_.sessionEntries(); // Use the verified installed vendor identity; never load using a // browser-provided plugin name or relocate an arbitrary VST3 path. error=resolveMixerSessionCatalog(doc,true); @@ -2875,14 +3134,19 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr session.getProperty("authority","").toString()=="M4"; if(error.isEmpty()&&!physical&&engine.hasRetainedNativeSession()) error="Retained native mixer still owns the session"; + const auto importedHotkeys=doc.hotkeys; + const auto importedId=doc.id; if(error.isEmpty()&&!physical) { // Open the real .smix into the same stable-ID logical // document. Never demand audio hardware or instantiate VST3 // just to inspect and edit a saved mixer. if(!safe->logicalMixer_.open(std::move(doc),std::move(states), - [safe,file](juce::String openError){ + [safe,file,importedHotkeys,importedId](juce::String openError){ if(safe==nullptr)return; if(openError.isEmpty()) { + safe->mixerSessionId_=importedId; + const auto keyError=safe->hotkeys_.activateSession(importedId,&importedHotkeys); + if(keyError.isNotEmpty())safe->emitNotice("Hotkey import: "+keyError,true); safe->mixerSessionStatus_="LOGICAL_SESSION_OPENED_UNBOUND"; safe->lastMixerFile_=file; } @@ -2905,6 +3169,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr safe->closePluginEditor(); safe->stopOrbit(); safe->mixerSessionId_=id; + const auto keyError=safe->hotkeys_.activateSession(id,&importedHotkeys); + if(keyError.isNotEmpty())safe->emitNotice("Hotkey import: "+keyError,true); safe->mixerSessionRecoveryPending_=false; safe->lastMixerSessionFingerprint_.clear(); safe->mixerSessionStatus_=engine.isMonitorEnabled()?"RESTORED_MONITORING":"RESTORED_MUTED"; @@ -5868,6 +6134,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void timerCallback() override { +#if defined(_WIN32) + // A startup splash can delay HWND creation; attach once the real JUCE + // peer exists. Never install a low-level keyboard hook. + if(auto* peer=getPeer()) + hotkeys_.attach(peer->getNativeHandle()); +#endif if(deviceApply_.busy())return; // a vendor modal loop may re-enter JUCE // Always disabled unless the user explicitly starts a bounded trace. const bool timing = guiPerf_.active; diff --git a/src/NativeHotkeyRegistry.h b/src/NativeHotkeyRegistry.h new file mode 100644 index 000000000..08df695cf --- /dev/null +++ b/src/NativeHotkeyRegistry.h @@ -0,0 +1,350 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// This header is included from the mixer/FX translation unit. Win32's legacy +// min/max macros corrupt std::numeric_limits and std::min/max throughout JUCE +// and the DSP headers. Suppress them BEFORE any transitive Windows include. +#if defined(_WIN32) && !defined(NOMINMAX) +#define NOMINMAX 1 +#endif +#include +#include +#include +#include +#if defined(_WIN32) +#include +#include +// Some consumers may have included windows.h before this service: make sure +// neither legacy macro escapes into the audio engine's source translation unit. +#ifdef min +#undef min +#endif +#ifdef max +#undef max +#endif +#if defined(_MSC_VER) +#pragma comment(lib, "Comctl32.lib") +#endif +#endif + +// Control-thread only. Win32 registers chords; the existing JUCE mixer +// dispatcher performs the action. This class NEVER touches audio callbacks. +namespace armix::hotkey { +struct Mapping final { + juce::String id, scope, sessionId, channelId, operation; + int vk=0, modifiers=0; + // Preserve the exact plugin instance, not merely the positional slot. + int slot=-1; + juce::String insertId; +}; +class Registry final { +public: + explicit Registry(juce::File home) : file_(home.getChildFile("hotkey-registry.v1.json")) { + load(); + } + ~Registry() { detach(); } + Registry(const Registry&)=delete; + Registry& operator=(const Registry&)=delete; + + static bool valid(const Mapping& m) { + const bool key=(m.vk>=0x30&&m.vk<=0x39) || + (m.vk>=0x41&&m.vk<=0x5a) || + (m.vk>=0x70&&m.vk<=0x7a); + const bool chord=(m.modifiers&~7)==0 && + (m.modifiers&3)!=0; // global chords need Ctrl or Alt + const bool fxSlot=m.operation=="SET_FX_SLOT_BYPASS"; + const bool command=m.operation=="PANIC_MUTE" || + m.operation=="SET_MUTE"||m.operation=="SET_SOLO"|| + m.operation=="SET_FX_RACK_BYPASS"||fxSlot; + const bool target=fxSlot? + m.slot>=0 && m.slot<8 && m.insertId.isNotEmpty() && + m.insertId.length()<=128: + m.slot==-1 && m.insertId.isEmpty(); + const bool app=m.scope=="APP" && m.operation=="PANIC_MUTE" && + m.channelId.isEmpty() && m.sessionId.isEmpty(); + const bool session=m.scope=="SESSION" && m.operation!="PANIC_MUTE" && + m.channelId.containsOnly("0123456789") && + m.channelId.isNotEmpty() && m.channelId!="0" && + m.sessionId.isNotEmpty() && m.sessionId.length()<=48; + return m.id.isNotEmpty()&&m.id.length()<=64 && key && chord && + command && target && (app||session); + } + static juce::var encode(const Mapping& m) { + auto out=juce::var(new juce::DynamicObject()); + auto* o=out.getDynamicObject(); + o->setProperty("id",m.id);o->setProperty("scope",m.scope); + o->setProperty("sessionId",m.sessionId); + o->setProperty("channelId",m.channelId); + o->setProperty("operation",m.operation); + o->setProperty("vk",m.vk);o->setProperty("modifiers",m.modifiers); + if(m.operation=="SET_FX_SLOT_BYPASS") { + o->setProperty("slot",m.slot); + o->setProperty("insertId",m.insertId); + } + return out; + } + static bool decode(const juce::var& v,Mapping& m) { + if(!v.isObject())return false; + auto field=[&](const char* name,juce::String& target) { + const auto value=v.getProperty(name,{}); + if(!value.isString()||value.toString().length()>64)return false; + target=value.toString();return true; + }; + const auto vk=v.getProperty("vk",{}),mods=v.getProperty("modifiers",{}); + if(!field("id",m.id)||!field("scope",m.scope)|| + !field("sessionId",m.sessionId)||!field("channelId",m.channelId)|| + !field("operation",m.operation)||!vk.isInt()||!mods.isInt())return false; + m.vk=static_cast(vk);m.modifiers=static_cast(mods); + m.slot=-1;m.insertId.clear(); // old H1 documents remain readable + if(m.operation=="SET_FX_SLOT_BYPASS") { + const auto slot=v.getProperty("slot",{}),token=v.getProperty("insertId",{}); + if(!slot.isInt()||!token.isString()||token.toString().length()>128) + return false; + m.slot=static_cast(slot);m.insertId=token.toString(); + } else if(!v.getProperty("slot",{}).isVoid() || + !v.getProperty("insertId",{}).isVoid())return false; + return valid(m); + } + void setHandler(std::function handler) { + handler_=std::move(handler); + } + juce::String activeSession() const {return activeSession_;} + void setCaptureMode(bool enabled) { + if(capturing_==enabled)return; + capturing_=enabled; + if(enabled)clearRegistrations(); + else registerActive(); + } + // Import is explicit only for opening .smix. Implicit restart recovery + // keeps the newer crash-safe local journal instead of overwriting it with + // an older checkpoint. An empty imported list intentionally clears keys. + juce::String activateSession(juce::String id, + const std::vector* imported=nullptr) { + if(id==activeSession_ && !imported)return {}; + if(imported) { + auto next=entries_; + next.erase(std::remove_if(next.begin(),next.end(), + [&id](const Mapping& m){return m.scope=="SESSION"&&m.sessionId==id;}), + next.end()); + for(const auto& m:*imported) { + if(!valid(m)||m.scope!="SESSION"||m.sessionId!=id) + return "INVALID_IMPORTED_HOTKEY"; + if(std::any_of(next.begin(),next.end(), + [&m](const Mapping& other){return other.id==m.id || + (other.scope=="SESSION"&&other.sessionId==m.sessionId && + other.vk==m.vk&&other.modifiers==m.modifiers);})) + return "DUPLICATE_IMPORTED_HOTKEY"; + next.push_back(m); + } + if(next.size()>256)return "HOTKEY_LIMIT_REACHED"; + if(!save(next))return "HOTKEY_IMPORT_PERSISTENCE_FAILED"; + entries_=std::move(next); + } + clearRegistrations(); + activeSession_=std::move(id); + registerActive(); + return {}; + } + std::vector sessionEntries() const { + std::vector result; + for(const auto& m:entries_)if(m.scope=="SESSION"&&m.sessionId==activeSession_) + result.push_back(m); + return result; + } + juce::var snapshot() const { + auto o=juce::var(new juce::DynamicObject()); + o.getDynamicObject()->setProperty("schema","arsonmix.hotkey-registry.v1"); + o.getDynamicObject()->setProperty("sessionId",activeSession_); + juce::Array rows; + for(const auto& m:entries_)if(active(m)) { + auto row=encode(m); + row.getDynamicObject()->setProperty("status", + registered(m.id)?"REGISTERED": +#if defined(_WIN32) + "UNAVAILABLE"); +#else + "UNSUPPORTED_PLATFORM"); +#endif + rows.add(row); + } + o.getDynamicObject()->setProperty("entries",juce::var(rows)); + return o; + } + // A refused registration changes neither the OS registration nor disk. + juce::String upsert(Mapping m) { + if(!valid(m)|| (m.scope=="SESSION" && m.sessionId!=activeSession_)) + return "INVALID_HOTKEY_TARGET"; + const auto it=std::find_if(entries_.begin(),entries_.end(), + [&m](const Mapping& item){return item.id==m.id;}); + if(it==entries_.end()&&entries_.size()>=256)return "HOTKEY_LIMIT_REACHED"; + for(const auto& old:entries_) { + if(old.id!=m.id && active(old) && old.vk==m.vk && + old.modifiers==m.modifiers)return "HOTKEY_ALREADY_MAPPED"; + } + const bool sameKey=it!=entries_.end() && active(*it) && + it->vk==m.vk&&it->modifiers==m.modifiers; + int staged=0; + if(!sameKey) { +#if defined(_WIN32) + if(!window_)return "HOTKEY_NATIVE_WINDOW_NOT_READY"; + staged=++nextId_; + if(!::RegisterHotKey(window_,staged, + static_cast(m.modifiers)|MOD_NOREPEAT,static_cast(m.vk))) + return "HOTKEY_OS_CONFLICT"; +#else + return "HOTKEY_PLATFORM_UNSUPPORTED"; +#endif + } + auto next=entries_; + if(it==entries_.end())next.push_back(m); + else next[static_cast(it-entries_.begin())]=m; + if(!save(next)) { +#if defined(_WIN32) + if(staged)::UnregisterHotKey(window_,staged); +#endif + return "HOTKEY_PERSISTENCE_FAILED"; + } + if(!sameKey) { + unregisterId(m.id); + registrations_.push_back({staged,m.id}); + } + entries_=std::move(next); + return {}; + } + juce::String remove(const juce::String& id) { + auto next=entries_; + auto it=std::find_if(next.begin(),next.end(), + [&id](const Mapping& m){return m.id==id;}); + if(it==next.end()||!active(*it))return "UNKNOWN_HOTKEY_MAPPING"; + next.erase(it); + if(!save(next))return "HOTKEY_PERSISTENCE_FAILED"; + unregisterId(id); + entries_=std::move(next); + return {}; + } + bool attached() const noexcept { +#if defined(_WIN32) + return window_!=nullptr; +#else + return false; +#endif + } + void attach(void* nativeWindow) { +#if defined(_WIN32) + auto* newWindow=static_cast(nativeWindow); + if(newWindow==window_)return; + detach(); + if(!newWindow||!::IsWindow(newWindow))return; + if(!::SetWindowSubclass(newWindow,&Registry::windowProc,0xA551, + reinterpret_cast(this)))return; + window_=newWindow; + registerActive(); +#else + (void)nativeWindow; +#endif + } + void detach() { + clearRegistrations(); +#if defined(_WIN32) + if(window_)::RemoveWindowSubclass(window_,&Registry::windowProc,0xA551); + window_=nullptr; +#endif + } +private: + struct Registration {int id;juce::String mapping;}; + bool active(const Mapping& m) const { + return m.scope=="APP" || + (m.scope=="SESSION" && m.sessionId==activeSession_); + } + bool registered(const juce::String& id) const { + return std::any_of(registrations_.begin(),registrations_.end(), + [&id](const Registration& r){return r.mapping==id;}); + } + void unregisterId(const juce::String& mapping) { + auto it=registrations_.begin(); + while(it!=registrations_.end()) { + if(it->mapping==mapping) { +#if defined(_WIN32) + if(window_)::UnregisterHotKey(window_,it->id); +#endif + it=registrations_.erase(it); + } else ++it; + } + } + void clearRegistrations() { +#if defined(_WIN32) + if(window_)for(const auto& r:registrations_)::UnregisterHotKey(window_,r.id); +#endif + registrations_.clear(); + } + void registerActive() { +#if defined(_WIN32) + if(!window_ || capturing_)return; + for(const auto& m:entries_)if(active(m) && !registered(m.id)) { + const int id=++nextId_; + if(::RegisterHotKey(window_,id, + static_cast(m.modifiers)|MOD_NOREPEAT,static_cast(m.vk))) + registrations_.push_back({id,m.id}); + } +#endif + } + bool save(const std::vector& entries) const { + auto o=juce::var(new juce::DynamicObject()); + o.getDynamicObject()->setProperty("schema","arsonmix.hotkey-registry.v1"); + juce::Array rows; + for(const auto& m:entries)rows.add(encode(m)); + o.getDynamicObject()->setProperty("entries",juce::var(rows)); + if(file_.getParentDirectory().createDirectory().failed())return false; + juce::TemporaryFile tmp(file_); + return tmp.getFile().replaceWithText(juce::JSON::toString(o,false)) && + tmp.overwriteTargetFileWithTemporary(); + } + void load() { + if(!file_.existsAsFile())return; + const auto content=file_.loadFileAsString(); + if(content.getNumBytesAsUTF8()>128*1024)return; + const auto doc=juce::JSON::parse(content); + if(doc.getProperty("schema","").toString()!="arsonmix.hotkey-registry.v1")return; + const auto entriesValue=doc.getProperty("entries",{}); + const auto* rows=entriesValue.getArray(); + if(!rows || rows->size()>256)return; + std::vector read; + for(const auto& row:*rows) { + Mapping m; + if(!decode(row,m))return; + if(std::any_of(read.begin(),read.end(),[&m](const Mapping& other) { + return other.id==m.id || + (other.scope==m.scope && other.sessionId==m.sessionId && + other.vk==m.vk && other.modifiers==m.modifiers); + }))return; + read.push_back(std::move(m)); + } + entries_=std::move(read); + } +#if defined(_WIN32) + static LRESULT CALLBACK windowProc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp, + UINT_PTR subclass,DWORD_PTR data) { + auto* self=reinterpret_cast(data); + if(msg==WM_HOTKEY && self) { + const int keyId=static_cast(wp); + for(const auto& r:self->registrations_)if(r.id==keyId) { + const auto it=std::find_if(self->entries_.begin(),self->entries_.end(), + [&r](const Mapping& m){return m.id==r.mapping;}); + if(it!=self->entries_.end() && self->active(*it)) { + if(self->handler_)self->handler_(*it); + return 0; + } + } + } + return ::DefSubclassProc(hwnd,msg,wp,lp); + } + HWND window_=nullptr; +#endif + juce::File file_; + juce::String activeSession_; + std::vector entries_; + std::vector registrations_; + std::function handler_; + int nextId_=0x7000; + bool capturing_=false; +}; +} // namespace armix::hotkey diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index cc1ae62c1..b19517128 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -4,6 +4,7 @@ #include #include "../engine/core/UnifiedLegacyProductionAdmission.h" #include "NativeShowStore.h" +#include "NativeHotkeyRegistry.h" #include #include #include @@ -39,6 +40,7 @@ struct StoredInsert final { juce::String catalogId,path,sha256,name; int uid=0; bool bypass=false; + juce::String instanceId; // durable identity of this specific native FX owner }; struct PlannedSlotBypass final { ChannelId channel{}; @@ -58,6 +60,8 @@ struct MixerSessionDocument final { // Logical-only per-slot bypass intentions; no fabricated FX processor // state or fake vendor SHA. Physical sessions keep existing inserts. std::vector plannedSlotBypassed; + // Session-specific global shortcuts; app-wide keys live in native settings. + std::vector hotkeys; float masterGain=1.f; bool masterMute=false,masterMono=false; // Internal checkpoint preference, distinct from the hardware monitor pair. @@ -417,6 +421,11 @@ class Codec final { set(root,"savedMs",decimal(static_cast(d.savedMs))); if(d.resumeMain.has_value())set(root,"resumeMain",*d.resumeMain); set(root,"legacyIds",ids(d.legacyIds)); + if(!d.hotkeys.empty()) { + juce::Array hotkeys; + for(const auto& mapping:d.hotkeys)hotkeys.add(armix::hotkey::Registry::encode(mapping)); + set(root,"hotkeys",juce::var(hotkeys)); + } auto bind=object(); set(bind,"backend",d.binding.backend); set(bind,"capture",d.binding.capture); @@ -503,6 +512,8 @@ class Codec final { set(fx,"catalogId",f.catalogId);set(fx,"path",f.path); set(fx,"uid",f.uid);set(fx,"name",f.name); set(fx,"sha256",f.sha256);set(fx,"bypass",f.bypass); + // Optional v1 field; old .smix files remain byte-for-byte valid. + if(f.instanceId.isNotEmpty())set(fx,"instanceId",f.instanceId); inserts.add(fx); } for(auto id:d.rackBypassed)racks.add(decimal(id.value)); @@ -633,6 +644,31 @@ class Codec final { entries.push_back(std::move(row)); } if(!doc.roster.restoreExact(doc.acceptedRevision,entries))return false; + // Optional additive H1 field. Old .smix sessions decode unchanged. + // Exact ChannelId ownership prevents rename/reorder/strip replacement + // from silently retargeting an operator's global shortcut. + const auto hotkeys=get(root,"hotkeys"); + if(!hotkeys.isVoid()) { + const auto* mappings=hotkeys.getArray(); + if(!mappings || mappings->size()>128)return false; + std::set ids; + std::set> chords; + for(const auto& entry:*mappings) { + armix::hotkey::Mapping mapping; + if(!armix::hotkey::Registry::decode(entry,mapping) || + mapping.scope!="SESSION" || mapping.sessionId!=doc.id || + !ids.insert(mapping.id).second || + !chords.emplace(mapping.vk,mapping.modifiers).second)return false; + std::uint64_t channelId=0; + // A removed channel retains an inert stable-id shortcut so + // the operator can explicitly remap/delete it. Reject + // malformed IDs, never rebind to the same strip ordinal. + if(!parseDecimal(juce::var(mapping.channelId),channelId) || + juce::String(std::to_string(channelId))!=mapping.channelId) + return false; + doc.hotkeys.push_back(std::move(mapping)); + } + } const auto seek=[&doc](ChannelId id,ChannelRole role){ const auto* row=doc.roster.find(id); return row && row->role==role; @@ -708,6 +744,7 @@ class Codec final { const auto* racks=racksVar.getArray(); if(!fx||!racks||fx->size()>16384||racks->size()>channels->size())return false; std::set> seenFx; + std::set seenInstances; for(const auto& item:*fx) { StoredInsert p;int slot=0; if(!parseDecimal(get(item,"channel"),p.channel.value)|| @@ -724,6 +761,17 @@ class Codec final { p.sha256.length()!=64 || !p.sha256.containsOnly("0123456789abcdef")|| !strictBool(get(item,"bypass"),p.bypass))return false; + const auto durable=get(item,"instanceId"); + if(!durable.isVoid()) { + if(!durable.isString())return false; + const auto token=durable.toString(); + const auto digits=token.startsWith("g5c-")? + token.substring(4):juce::String{}; + if(digits.isEmpty()||digits.length()>18||digits[0]=='0'|| + !digits.containsOnly("0123456789")|| + !seenInstances.insert(token).second)return false; + p.instanceId=token; + } doc.inserts.push_back(std::move(p)); } for(const auto& item:*racks) { diff --git a/src/NativeMixerSessionFxRestore.h b/src/NativeMixerSessionFxRestore.h index fe85bc31d..a3a3b545d 100644 --- a/src/NativeMixerSessionFxRestore.h +++ b/src/NativeMixerSessionFxRestore.h @@ -109,7 +109,8 @@ class NativeMixerSessionFxRestore final { ? processor->getName() : insert.name; auto owner=std::make_shared( std::move(processor),insert.catalogId,displayName, - armix::mixer::PreparedMixerBlock::hardFrameLimit); + armix::mixer::PreparedMixerBlock::hardFrameLimit, + insert.instanceId); owner->bypassRequested.store(insert.bypass,std::memory_order_release); lane.inserts.push_back(std::move(owner)); } diff --git a/tests/approved_native_gui_bundle_test.py b/tests/approved_native_gui_bundle_test.py index f3978481a..d9eac7580 100644 --- a/tests/approved_native_gui_bundle_test.py +++ b/tests/approved_native_gui_bundle_test.py @@ -50,6 +50,33 @@ def test_native_is_exact_assembled_public_pages_plus_nonvisual_native_seam(self) self.assertIn('document.addEventListener("contextmenu"', context_menu) self.assertIn("requestDeleteTrack", context_menu) self.assertIn("orbitAction", context_menu) + # H1 uses the SAME native-only /preview/ context handler. Never + # intercept vendor HWNDs or implement a JS-only global shortcut. + self.assertIn("arMixHotkeyIntent", context_menu) + self.assertIn("arMixHotkeyRegistry", context_menu) + self.assertIn("Please press Hotkey", context_menu) + self.assertIn("hotkey-add", context_menu) + # Native-only right-click for channel/rack/slot Power is real + # RegisterHotKey input, not fake demo power or a WebView click. + self.assertIn("nativeFxHotkeyTarget", context_menu) + self.assertIn("SET_FX_RACK_BYPASS", context_menu) + self.assertIn("SET_FX_SLOT_BYPASS", context_menu) + self.assertIn("Assign Hotkey", context_menu) + self.assertIn("Change Hotkey", context_menu) + self.assertIn("Remove Hotkey", context_menu) + self.assertIn('data-action="slotPower"', context_menu) + self.assertIn('data-action="fxOn"', context_menu) + native_host = (ROOT / "src/Main.cpp").read_text("utf-8") + self.assertIn("HOTKEY_FX_INSTANCE_NOT_ADMITTED", native_host) + self.assertIn('routingNativeFxInsertBypass', native_host) + self.assertIn('routingNativeFxRackBypass', native_host) + self.assertIn("hotkey-register", context_menu) + self.assertIn("requestDeleteTrack", context_menu) + self.assertIn("Orbit…", context_menu) + self.assertIn('withEventListener ("arMixHotkeyIntent"', native_host) + self.assertIn("fireNativeHotkey", native_host) + self.assertIn("handleApprovedNativeControl(request)", native_host) + self.assertIn("WM_HOTKEY", (ROOT / "src/NativeHotkeyRegistry.h").read_text("utf-8")) self.assertNotIn("approved-native-context-menu.js", approved) self.assertIn("arMixGuiReady", (out / "assets/approved-native-bridge.js").read_text("utf-8")) self.assertIn("nativeBridgeAttached:true", diff --git a/tests/native_hotkey_registry_test.cpp b/tests/native_hotkey_registry_test.cpp new file mode 100644 index 000000000..9f09ab79a --- /dev/null +++ b/tests/native_hotkey_registry_test.cpp @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#ifdef NDEBUG +#undef NDEBUG +#endif +#include +#include +#include "../src/NativeHotkeyRegistry.h" + +using armix::hotkey::Mapping; +using armix::hotkey::Registry; + +int main() { + const auto temp=juce::File::getSpecialLocation(juce::File::tempDirectory) + .getNonexistentChildFile("ArSonMixHotkeyH1","",false); + assert(temp.createDirectory().wasOk()); + const juce::String session="11111111-2222-4333-8444-555555555555"; + Mapping mute{"m5","SESSION",session,"5","SET_MUTE",0x77,6}; // Ctrl+Shift+F8 + Mapping solo{"s5","SESSION",session,"5","SET_SOLO",0x78,6}; // Ctrl+Shift+F9 + Mapping panic{"panic","APP","","","PANIC_MUTE",0x79,6}; + Mapping rack{"fx-rack","SESSION",session,"5","SET_FX_RACK_BYPASS",0x76,6}; + Mapping slot{"fx-slot","SESSION",session,"5","SET_FX_SLOT_BYPASS",0x75,6,2,"original-instance"}; + assert(Registry::valid(mute)&&Registry::valid(solo)&&Registry::valid(panic)); + assert(Registry::valid(rack)&&Registry::valid(slot)); + Mapping restoredSlot; + assert(Registry::decode(Registry::encode(slot),restoredSlot)); + assert(restoredSlot.slot==2&&restoredSlot.insertId=="original-instance"); + auto invalidSlot=slot; + invalidSlot.slot=8;assert(!Registry::valid(invalidSlot)); + invalidSlot=slot;invalidSlot.insertId.clear();assert(!Registry::valid(invalidSlot)); + invalidSlot=rack;invalidSlot.slot=1;assert(!Registry::valid(invalidSlot)); + auto brokenSlot=Registry::encode(slot); + brokenSlot.getDynamicObject()->removeProperty("insertId"); + assert(!Registry::decode(brokenSlot,restoredSlot)); + auto invalid=mute; + invalid.channelId="";assert(!Registry::valid(invalid)); + invalid=mute;invalid.modifiers=4;assert(!Registry::valid(invalid)); + invalid=mute;invalid.vk=0x7b;assert(!Registry::valid(invalid)); // F12 reserved + invalid=mute;invalid.scope="APP";assert(!Registry::valid(invalid)); + invalid=mute;invalid.operation="DELETE_CHANNEL";assert(!Registry::valid(invalid)); + invalid=mute;invalid.modifiers=10;assert(!Registry::valid(invalid)); // WIN key + Mapping roundtrip; + assert(Registry::decode(Registry::encode(mute),roundtrip)); + assert(roundtrip.channelId=="5"&&roundtrip.operation=="SET_MUTE"); + const auto bad=juce::var(new juce::DynamicObject()); + assert(!Registry::decode(bad,roundtrip)); + { + Registry registry(temp); + registry.activateSession(session); + assert(registry.snapshot().getProperty("entries",{}).getArray()->isEmpty()); +#if defined(_WIN32) + const auto window=::CreateWindowExW(0,L"STATIC",L"ArSonMixHotkeyH1CTest", + WS_POPUP,0,0,1,1,nullptr,nullptr,::GetModuleHandleW(nullptr),nullptr); + assert(window!=nullptr); + registry.attach(window); + assert(registry.attached()); + assert(registry.upsert(mute).isEmpty()); + assert(registry.upsert(panic).isEmpty()); + assert(registry.upsert(rack).isEmpty()); + assert(registry.upsert(slot).isEmpty()); + const auto rows=registry.snapshot().getProperty("entries",{}); + assert(rows.isArray()&&rows.getArray()->size()==4); + for(const auto& row:*rows.getArray()) + assert(row.getProperty("status","").toString()=="REGISTERED"); + // Duplicate chord remains unmodified. The working mapping wins. + solo.vk=mute.vk; + assert(registry.upsert(solo)=="HOTKEY_ALREADY_MAPPED"); + solo.vk=0x78; + assert(registry.upsert(solo).isEmpty()); + registry.setCaptureMode(true); + { + const auto state=registry.snapshot().getProperty("entries",{}); + for(const auto& row:*state.getArray()) + assert(row.getProperty("status","").toString()=="UNAVAILABLE"); + } + registry.setCaptureMode(false); + assert(registry.remove("m5").isEmpty()); + assert(registry.remove("m5")=="UNKNOWN_HOTKEY_MAPPING"); + registry.detach(); + ::DestroyWindow(window); +#else + assert(registry.upsert(mute)=="HOTKEY_PLATFORM_UNSUPPORTED"); + assert(registry.snapshot().getProperty("entries",{}).getArray()->isEmpty()); +#endif + } +#if defined(_WIN32) + { + Registry reloaded(temp); + reloaded.activateSession(session); + const auto entries=reloaded.snapshot().getProperty("entries",{}); + assert(entries.isArray()&&entries.getArray()->size()==4); + assert(entries.getArray()->getReference(0).getProperty("id","").toString()!="m5"); + // OS registration is currently unavailable until an HWND attaches. + for(const auto& item:*entries.getArray()) + assert(item.getProperty("status","").toString()=="UNAVAILABLE"); + } +#endif + assert(temp.deleteRecursively()); + std::cout<<"PASS: global chord validation, native registration rollback, " + "session identity and crash-safe persistence\n"; + return 0; +} diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index 926d24fcf..7ef540944 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -1001,7 +1001,148 @@ static void verifyLogicalControlTransactions() { assert(folder.deleteRecursively()); } +// H1: a saved VST3 Power mapping survives a real .smix Save/Open and the +// restored native FX lease keeps the EXACT token. A plugin replaced at that +// slot cannot inherit the shortcut. Legacy files omit instanceId completely. +static void verifyDurableNativeFxPowerIdentity() { + using FxOwner=armix::mixer::LiveChannelFxGraph::FxInstance; + auto doc=makeSession(); + auto rows=doc.roster.channels(); + for(auto& channel:rows) + if(channel.id.value==5) + channel.insertCatalogIds={"fixture.vst3.power"}; + assert(doc.roster.restoreExact(doc.acceptedRevision,rows)); + + StoredInsert saved; + saved.channel={5};saved.slot=0; + saved.catalogId="fixture.vst3.power"; + saved.name="Power Fixture"; + saved.sha256=juce::String::repeatedString("0123456789abcdef",4); + saved.bypass=true; + // An ID comes from the native control owner, NOT the .smix file name, + // catalog identity, user-facing FX label or slot ordinal. + saved.instanceId="g5c-724"; + doc.inserts.push_back(saved); + doc.hotkeys.push_back({"power-hotkey","SESSION",doc.id,"5", + "SET_FX_SLOT_BYPASS",0x76,6,0,saved.instanceId}); + + const auto durable=Codec::encode(doc); + MixerSessionDocument reopened; + assert(Codec::decode(durable,reopened)); + assert(reopened.inserts.size()==1&&reopened.hotkeys.size()==1); + assert(reopened.inserts[0].instanceId=="g5c-724"); + assert(reopened.hotkeys[0].insertId==reopened.inserts[0].instanceId); + assert(Codec::encode(reopened)==durable); + // No vendor DSP is invoked in this fixture: construction and identity + // reservation are CONTROL-thread state only. + FxOwner restored(nullptr,"fixture.vst3.power","Power Fixture",64, + reopened.inserts[0].instanceId); + assert(restored.instanceId==reopened.hotkeys[0].insertId); + FxOwner next(nullptr,"fixture.vst3.power","Next Insert",64); + assert(next.instanceId.startsWith("g5c-")); + assert(next.instanceId.substring(4).getLargeIntValue()>724); + + auto invalid=juce::JSON::parse(durable); + auto inserts=invalid.getProperty("inserts",{}); + assert(inserts.isArray()); + inserts.getArray()->getReference(0).getDynamicObject() + ->setProperty("instanceId","g5c-0"); + assert(!Codec::decode(juce::JSON::toString(invalid,false),reopened)); + invalid=juce::JSON::parse(durable); + inserts=invalid.getProperty("inserts",{}); + inserts.getArray()->getReference(0).getDynamicObject() + ->setProperty("instanceId","not-native-token"); + assert(!Codec::decode(juce::JSON::toString(invalid,false),reopened)); + invalid=juce::JSON::parse(durable); + inserts=invalid.getProperty("inserts",{}); + inserts.getArray()->getReference(0).getDynamicObject() + ->setProperty("instanceId",juce::var(24)); + assert(!Codec::decode(juce::JSON::toString(invalid,false),reopened)); + + // A second channel must not claim the same native FX instance identity. + auto duplicate=doc; + auto second=saved;second.channel={6}; + duplicate.inserts.push_back(second); + auto withSecond=duplicate.roster.channels(); + for(auto& channel:withSecond) + if(channel.id.value==6) + channel.insertCatalogIds={"fixture.vst3.power"}; + assert(duplicate.roster.restoreExact(duplicate.acceptedRevision,withSecond)); + assert(!Codec::decode(Codec::encode(duplicate),reopened)); + + // Older .smix files containing vendor blobs but no native FX token decode + // normally; adding durable identity does not force a schema bump. + auto legacy=doc; + legacy.inserts[0].instanceId.clear(); + legacy.hotkeys.clear(); + const auto old=Codec::encode(legacy); + assert(Codec::decode(old,reopened)); + assert(reopened.inserts[0].instanceId.isEmpty()); +} + +static void verifyHotkeyDocumentIdentityAndMigration() { + auto doc=makeSession(); + const auto legacy=Codec::encode(doc); + MixerSessionDocument decoded; + assert(Codec::decode(legacy,decoded) && decoded.hotkeys.empty()); + const juce::String session=doc.id; + armix::hotkey::Mapping first{"native-ch05","SESSION",session,"5","SET_MUTE",0x77,6}; + armix::hotkey::Mapping second{"native-bus","SESSION",session,"16","SET_SOLO",0x78,6}; + armix::hotkey::Mapping rack{"fx-rack-05","SESSION",session,"5", + "SET_FX_RACK_BYPASS",0x76,6}; + armix::hotkey::Mapping slot{"fx-slot-05","SESSION",session,"5", + "SET_FX_SLOT_BYPASS",0x75,6,1,"plugin-instance-original"}; + doc.hotkeys={first,second,rack,slot}; + const auto stable=Codec::encode(doc); + assert(Codec::decode(stable,decoded)); + assert(decoded.hotkeys.size()==4); + assert(decoded.hotkeys[2].operation=="SET_FX_RACK_BYPASS"); + assert(decoded.hotkeys[3].slot==1 && + decoded.hotkeys[3].insertId=="plugin-instance-original"); + assert(decoded.hotkeys[0].channelId=="5"&&decoded.hotkeys[1].channelId=="16"); + // Rename or visual channel reorder cannot retarget numeric ChannelId. + auto renamed=decoded.roster.channels(); + for(auto& row:renamed)if(row.id.value==5)row.name="New Singer Name"; + assert(decoded.roster.restoreExact(decoded.acceptedRevision,renamed)); + assert(Codec::decode(Codec::encode(decoded),doc)); + assert(doc.hotkeys[0].channelId=="5"); + auto damaged=juce::JSON::parse(stable); + auto hotkeys=damaged.getProperty("hotkeys",{}); + auto* rows=hotkeys.getArray(); + assert(rows&&rows->size()==4); + rows->getReference(0).getDynamicObject()->setProperty("channelId","999999"); + // Deleting a track does not make the entire mixer unsaveable. The + // orphan shortcut remains visible but can never fire for another ID. + assert(Codec::decode(juce::JSON::toString(damaged,false),decoded)); + assert(decoded.hotkeys[0].channelId=="999999"); + damaged=juce::JSON::parse(stable); + hotkeys=damaged.getProperty("hotkeys",{}); + rows=hotkeys.getArray(); + rows->getReference(0).getDynamicObject()->setProperty("channelId","05"); + assert(!Codec::decode(juce::JSON::toString(damaged,false),decoded)); + damaged=juce::JSON::parse(stable); + hotkeys=damaged.getProperty("hotkeys",{}); + rows=hotkeys.getArray(); + rows->getReference(1).getDynamicObject()->setProperty("vk",0x77); + assert(!Codec::decode(juce::JSON::toString(damaged,false),decoded)); + damaged=juce::JSON::parse(stable); + hotkeys=damaged.getProperty("hotkeys",{}); + rows=hotkeys.getArray(); + rows->getReference(0).getDynamicObject()->setProperty("sessionId","other"); + assert(!Codec::decode(juce::JSON::toString(damaged,false),decoded)); + damaged=juce::JSON::parse(stable); + hotkeys=damaged.getProperty("hotkeys",{}); + hotkeys.getArray()->getReference(3).getDynamicObject()->setProperty("slot",8); + assert(!Codec::decode(juce::JSON::toString(damaged,false),decoded)); + damaged=juce::JSON::parse(stable); + hotkeys=damaged.getProperty("hotkeys",{}); + hotkeys.getArray()->getReference(3).getDynamicObject()->setProperty("insertId",""); + assert(!Codec::decode(juce::JSON::toString(damaged,false),decoded)); +} + int main(){ + verifyDurableNativeFxPowerIdentity(); + verifyHotkeyDocumentIdentityAndMigration(); verifyLogicalControlTransactions(); verifyLegacyHarmoniceSessionName(); verifyOfflineLogicalSessionAndFile(); diff --git a/web/approved-native-context-menu.js b/web/approved-native-context-menu.js index 096b41c20..cf0ae12a9 100644 --- a/web/approved-native-context-menu.js +++ b/web/approved-native-context-menu.js @@ -18,6 +18,21 @@ "#armixOrbit .head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px;font-size:14px;font-weight:550;cursor:grab;touch-action:none}", "#armixOrbit .head:active{cursor:grabbing}", "#armixContext button:disabled{opacity:.35;cursor:default}", + "#armixHotkeyCard[hidden],#armixHotkeyRegister[hidden]{display:none!important}", + "#armixHotkeyCard,#armixHotkeyRegister{position:fixed;z-index:10028;box-sizing:border-box;max-width:calc(100vw - 16px);padding:12px;border:1px solid #4b7180;border-radius:7px;background:#132731;color:#dbeef4;box-shadow:0 14px 35px #000c;font:12px Inter,system-ui,sans-serif}", + "#armixHotkeyCard{width:286px}#armixHotkeyRegister{width:580px;max-height:76vh;display:flex;flex-direction:column}", + ".armix-hk-head{display:flex;justify-content:space-between;align-items:center;gap:10px;cursor:grab;touch-action:none;font-weight:550;font-size:12px;margin-bottom:10px}", + ".armix-hk-target,.armix-hk-state{color:#a9c2ca;font-size:11px;margin:6px 0;overflow-wrap:anywhere}", + ".armix-hk-chord{border:1px solid #385e70;background:#0e2029;border-radius:5px;text-align:center;padding:11px 6px;margin:10px 0;color:#b4e8f4;font-size:14px;font-weight:550}", + ".armix-hk-operations{display:flex;gap:7px;justify-content:flex-end;margin-top:11px}", + "#armixHotkeyCard button,#armixHotkeyRegister button{border:1px solid #3f6575;background:#214653;color:#e3f1f5;padding:5px 9px;border-radius:4px;font:inherit;cursor:pointer}", + "#armixHotkeyCard button:disabled,#armixHotkeyRegister button:disabled{opacity:.45;cursor:default}", + "#armixHotkeyRegister input{background:#0c2029;color:#e0f0f5;border:1px solid #395f71;border-radius:4px;height:29px;padding:4px 8px;box-sizing:border-box;width:100%}", + "#armixHotkeyRegister .hk-list{overflow-y:auto;min-height:50px;max-height:58vh;margin-top:8px}", + "#armixHotkeyRegister .hk-row{display:grid;grid-template-columns:110px 1fr 68px 86px 80px;align-items:center;gap:6px;padding:6px 3px;border-bottom:1px solid #294653;font-size:11px}", + "#armixHotkeyRegister .hk-row .hk-status{color:#8acbc4}", + "#armixHotkeyRegister .hk-row .hk-actions{display:flex;gap:3px}", + "#armixHotkeyRegister .hk-row button{padding:4px 5px}", "body,body *{-webkit-user-select:none!important;user-select:none!important}", "input,textarea,[contenteditable],[contenteditable] *{-webkit-user-select:text!important;user-select:text!important}", "#armixOrbit .sub{color:#9cb8c3;font-size:11px;margin-bottom:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}", @@ -46,6 +61,37 @@ }).observe(document.documentElement,{ subtree:true,childList:true,attributes:true,attributeFilter:["title"] }); + const hotkeyCard=document.createElement("section"); + hotkeyCard.id="armixHotkeyCard";hotkeyCard.hidden=true; + hotkeyCard.setAttribute("role","dialog"); + hotkeyCard.setAttribute("aria-label","Assign Hotkey"); + hotkeyCard.innerHTML= + '
ASSIGN HOTKEY
'+ + '
'+ + '
Please press Hotkey
'+ + '
Press Ctrl / Alt + key
'+ + '
'+ + '
'; + document.body.appendChild(hotkeyCard); + const hotkeyRegister=document.createElement("section"); + hotkeyRegister.id="armixHotkeyRegister";hotkeyRegister.hidden=true; + hotkeyRegister.setAttribute("role","dialog"); + hotkeyRegister.setAttribute("aria-label","Hotkey Register"); + hotkeyRegister.innerHTML= + '
HOTKEY REGISTER
'+ + ''+ + '
'+ + '
'+ + '
'; + document.body.appendChild(hotkeyRegister); + const moreTools=document.querySelector("#moreTools .more-tools-panel"); + if(moreTools){ + const openButton=document.createElement("button"); + openButton.type="button";openButton.className="tool"; + openButton.id="armixHotkeyRegisterOpen";openButton.textContent="Hotkeys"; + openButton.setAttribute("aria-label","Open Hotkey Register"); + moreTools.appendChild(openButton); + } const menu=document.createElement("div"); menu.id="armixContext";menu.hidden=true;menu.setAttribute("role","menu"); document.body.appendChild(menu); @@ -92,9 +138,21 @@ menu.innerHTML=''+ ''+ - (canDelete?'':'
Delete unavailable for this native strip
'); + (canDelete?'':'
Delete unavailable for this native strip
')+ + (eligibleHotkey(menuTrack,"SET_MUTE")? + ''+ + '':'')+ + ''; } - }else menu.innerHTML=''; + }else if(kind==="hotkey"){ + const existing=hotkeyEntries.find(m=>sameHotkeyTarget(m,menuTarget)); + menu.innerHTML=''+ + (existing?'':'')+ + ''; + } + else menu.innerHTML=''+ + ''; place(menu,x,y); menu.querySelector("[role=menuitem]:not(:disabled)")?.focus({preventScroll:true}); } @@ -197,10 +255,272 @@ // Give buttons identifiers without introducing a second UI renderer. orbit.querySelector("[data-orbit-start]").id="armixOrbitStart"; orbit.querySelector("[data-orbit-stop]").id="armixOrbitStop"; + + let hotkeyEntries=[],hotkeySession="",hotkeyPending=null,hotkeyEdit=null; + let hotkeyChord=null,hotkeyTarget=null,dragHotkey=null; + let hotkeySerial=0; + const nextHotkeyRequest=()=> "hotkey-ui-"+Date.now().toString(36)+"-"+(++hotkeySerial); + const activeNative=()=>hooks.state?.()?.current; + function eligibleHotkey(track,operation) { + const channelId=hooks.nativeIdFor?.(track),state=activeNative(); + const channel=state?.graph?.channels?.find(ch=>ch.id===channelId); + return state?.admitted===true && channelId && channel && + ["INPUT","GROUP","FX_RETURN"].includes(channel.role) && + ["SET_MUTE","SET_SOLO"].includes(operation) && + state.graph.capabilities.supportedOps.includes(operation)?channelId:null; + } + function nativeFxHotkeyTarget(button){ + const track=scope.findTrack(button),state=activeNative(); + const channelId=hooks.nativeIdFor?.(track); + const channel=state?.graph?.channels?.find(ch=>ch.id===channelId); + if(!state?.admitted||state?.retained||!channelId||!channel|| + !["INPUT","GROUP","FX_RETURN"].includes(channel.role))return null; + if(button.dataset.action==="fxOn" && + typeof channel.fxRackBypassed==="boolean") + return {kind:"hotkey",channelId,operation:"SET_FX_RACK_BYPASS", + scope:"SESSION",label:track.name+" · FX Rack Power"}; + const slot=Number(button.dataset.slot ?? + button.closest(".fxslot-row")?.dataset.slot); + const insert=channel.inserts?.[slot]; + if(button.dataset.action==="slotPower" && Number.isInteger(slot) && + slot>=0&&slot<8&&typeof insert?.id==="string"&&insert.id&& + typeof insert.bypassed==="boolean") + return {kind:"hotkey",channelId,operation:"SET_FX_SLOT_BYPASS", + scope:"SESSION",slot,insertId:insert.id, + label:track.name+" · FX "+(slot+1)+" · "+(insert.name||"Power")}; + return null; + } + function sameHotkeyTarget(m,target){ + return target && m.scope===target.scope && + m.operation===target.operation && + m.channelId===(target.channelId||"") && + (target.operation!=="SET_FX_SLOT_BYPASS" || + (m.slot===target.slot&&m.insertId===target.insertId)); + } + function requestHotkeyList(){ + backend.emitEvent("arMixHotkeyIntent",{operation:"LIST"}); + } + function hotkeyLabel(mapping){ + if(mapping.operation==="PANIC_MUTE")return "Emergency Output Mute"; + const name=activeNative()?.graph?.channels?.find(c=>c.id===mapping.channelId)?.name; + const suffix=mapping.operation==="SET_FX_RACK_BYPASS"?"FX Rack Power": + mapping.operation==="SET_FX_SLOT_BYPASS"? + "FX "+(Number(mapping.slot)+1)+" · Power": + mapping.operation==="SET_MUTE"?"Mute":"Solo"; + return (name||"Channel "+mapping.channelId)+" · "+suffix; + } + function shortcutLabel(vk,mods){ + const label=vk>=0x70&&vk<=0x7a?"F"+(vk-0x6f): + String.fromCharCode(vk); + return [(mods&2)?"Ctrl":null,(mods&1)?"Alt":null, + (mods&4)?"Shift":null,label].filter(Boolean).join(" + "); + } + function openHotkeyRegister(){ + hotkeyRegister.hidden=false; + place(hotkeyRegister,Math.round((innerWidth-580)/2),62); + requestHotkeyList(); + hotkeyRegister.querySelector("[data-hk-search]")?.focus({preventScroll:true}); + } + function paintHotkeyRegister(){ + const target=hotkeyRegister.querySelector("[data-hk-list]"); + const filter=hotkeyRegister.querySelector("[data-hk-search]").value.toLowerCase(); + target.replaceChildren(); + for(const mapping of hotkeyEntries){ + const title=hotkeyLabel(mapping),chord=shortcutLabel(mapping.vk,mapping.modifiers); + if(!(title+" "+chord+" "+mapping.scope).toLowerCase().includes(filter))continue; + const row=document.createElement("div");row.className="hk-row"; + for(const value of [chord,title,mapping.scope,mapping.status||"UNAVAILABLE"]){ + const cell=document.createElement("span");cell.textContent=value; + if(value===mapping.status)cell.className="hk-status"; + row.appendChild(cell); + } + const actions=document.createElement("span");actions.className="hk-actions"; + for(const action of ["Edit","Delete"]){ + const button=document.createElement("button");button.type="button"; + button.textContent=action; + button.addEventListener("click",()=>{ + if(hotkeyPending)return; + if(action==="Edit")openHotkeyCapture({ + channelId:mapping.channelId,operation:mapping.operation, + slot:mapping.slot,insertId:mapping.insertId, + label:title,scope:mapping.scope},mapping); + else { + hotkeyPending={requestId:nextHotkeyRequest(),kind:"DELETE",mapping}; + backend.emitEvent("arMixHotkeyIntent",{ + operation:"DELETE",requestId:hotkeyPending.requestId,mappingId:mapping.id}); + } + }); + actions.appendChild(button); + } + row.appendChild(actions);target.appendChild(row); + } + if(!target.childElementCount){ + const empty=document.createElement("div");empty.className="armix-hk-state"; + empty.textContent=hotkeyEntries.length?"No matching hotkeys":"No registered shortcuts"; + target.appendChild(empty); + } + } + function setHotkeyCapture(active){ + backend.emitEvent("arMixHotkeyCapture",{enabled:Boolean(active)}); + } + function closeHotkeyCapture(){ + hotkeyCard.hidden=true;hotkeyTarget=null;hotkeyEdit=null;hotkeyChord=null; + if(!hotkeyPending)setHotkeyCapture(false); + } + function openHotkeyCapture(target,editing=null){ + if(!target)return; + closeHotkeyCapture();hotkeyTarget={...target};hotkeyEdit=editing; + hotkeyCard.querySelector("[data-hk-title]").textContent= + editing?"CHANGE HOTKEY":"ASSIGN HOTKEY"; + hotkeyChord=editing?{vk:editing.vk,modifiers:editing.modifiers}:null; + $("armixHkTarget").textContent=target.label; + $("armixHkChord").textContent=hotkeyChord? + shortcutLabel(hotkeyChord.vk,hotkeyChord.modifiers):"Press Ctrl / Alt + key"; + $("armixHkError").textContent="Global shortcuts work while ArSonMix is minimized"; + hotkeyCard.querySelector("[data-hk-save]").disabled=!hotkeyChord; + hotkeyCard.hidden=false; + place(hotkeyCard,Math.round((innerWidth-286)/2),Math.round(innerHeight/3)); + setHotkeyCapture(true); + hotkeyCard.tabIndex=-1;hotkeyCard.focus({preventScroll:true}); + } + function keyToVk(code){ + if(/^Key[A-Z]$/.test(code))return code.charCodeAt(3); + if(/^Digit[0-9]$/.test(code))return code.charCodeAt(5); + if(/^F([1-9]|1[01])$/.test(code))return 0x6f+Number(code.slice(1)); + return null; + } + document.addEventListener("keydown",e=>{ + if(hotkeyCard.hidden)return; + e.preventDefault();e.stopImmediatePropagation(); + if(e.key==="Escape"){closeHotkeyCapture();return;} + if(e.key==="Enter"&&hotkeyChord){ + hotkeyCard.querySelector("[data-hk-save]").click();return; + } + if(e.repeat)return; + const vk=keyToVk(e.code),modifiers=(e.altKey?1:0)| + (e.ctrlKey?2:0)|(e.shiftKey?4:0); + if(!vk || e.metaKey || e.getModifierState?.("AltGraph") || + !(modifiers&3)){ + hotkeyChord=null;$("armixHkChord").textContent="Invalid shortcut"; + $("armixHkError").textContent="Use Ctrl or Alt + letter, digit or F1–F11; no Win/F12"; + }else{ + hotkeyChord={vk,modifiers}; + $("armixHkChord").textContent=shortcutLabel(vk,modifiers); + $("armixHkError").textContent="Ready to register with Windows"; + } + hotkeyCard.querySelector("[data-hk-save]").disabled=!hotkeyChord; + },true); + hotkeyCard.addEventListener("click",e=>{ + if(e.target.closest("[data-hk-cancel]"))return closeHotkeyCapture(); + if(!e.target.closest("[data-hk-save]")||!hotkeyTarget||!hotkeyChord|| + hotkeyPending)return; + const mapping={ + id:hotkeyEdit?.id||"hk-"+Date.now().toString(36)+"-"+(++hotkeySerial), + scope:hotkeyTarget.scope,sessionId:hotkeyTarget.scope==="APP"?"":hotkeySession, + channelId:hotkeyTarget.channelId||"",operation:hotkeyTarget.operation, + vk:hotkeyChord.vk,modifiers:hotkeyChord.modifiers, + ...(hotkeyTarget.operation==="SET_FX_SLOT_BYPASS"? + {slot:hotkeyTarget.slot,insertId:hotkeyTarget.insertId}:{}) + }; + hotkeyPending={kind:"REGISTER",requestId:nextHotkeyRequest(),mapping}; + $("armixHkError").textContent="Registering and saving in native host…"; + hotkeyCard.querySelector("[data-hk-save]").disabled=true; + backend.emitEvent("arMixHotkeyIntent",{ + operation:"REGISTER",requestId:hotkeyPending.requestId,mapping}); + }); + hotkeyRegister.addEventListener("click",e=>{ + if(e.target.closest("[data-hk-register-close]")){ + hotkeyRegister.hidden=true;return; + } + if(e.target.closest("[data-hk-refresh]"))requestHotkeyList(); + if(e.target.closest("[data-hk-panic]"))openHotkeyCapture({ + scope:"APP",operation:"PANIC_MUTE",channelId:"", + label:"Emergency · Mute Hardware Output"}); + }); + hotkeyRegister.querySelector("[data-hk-search]").addEventListener("input",paintHotkeyRegister); + $("armixHotkeyRegisterOpen")?.addEventListener("click",openHotkeyRegister); + backend.addEventListener("arMixHotkeyRegistry",state=>{ + if(state?.schema!=="arsonmix.hotkey-registry.v1"|| + !Array.isArray(state.entries))return; + hotkeySession=String(state.sessionId||""); + hotkeyEntries=state.entries; + if(hotkeyPending&&state.requestId===hotkeyPending.requestId){ + if(state.status!=="ACCEPTED"){ + $("armixHkError").textContent=state.errorCode||"Native registration rejected"; + hotkeyRegister.querySelector("[data-hk-feedback]").textContent= + state.errorCode||"Native registration rejected"; + hotkeyCard.querySelector("[data-hk-save]").disabled=!hotkeyChord; + hotkeyPending=null; + if(!hotkeyCard.hidden)setHotkeyCapture(true); + }else{ + hotkeyPending.acked=true; + requestHotkeyList(); // independent native readback, not optimistic DOM + } + }else if(hotkeyPending?.acked&&!state.requestId){ + const p=hotkeyPending; + const found=hotkeyEntries.find(m=>m.id===p.mapping?.id); + const confirmed=p.kind==="DELETE"?!hotkeyEntries.some(m=>m.id===p.mapping.id): + found&&found.vk===p.mapping.vk&& + found.modifiers===p.mapping.modifiers&&found.operation===p.mapping.operation&& + found.channelId===p.mapping.channelId&& + (found.operation!=="SET_FX_SLOT_BYPASS"|| + (found.slot===p.mapping.slot&&found.insertId===p.mapping.insertId)); + if(confirmed){ + hotkeyPending=null;if(p.kind==="REGISTER")closeHotkeyCapture(); + }else{ + hotkeyPending=null; + $("armixHkError").textContent="Native readback mismatch; refresh before retry"; + } + } + paintHotkeyRegister(); + }); + const hotkeyDragBar=hotkeyCard.querySelector(".armix-hk-head"); + hotkeyDragBar.addEventListener("pointerdown",e=>{ + if(e.button!==0||e.target.closest("button"))return; + dragHotkey={id:e.pointerId,x:e.clientX,y:e.clientY, + left:hotkeyCard.offsetLeft,top:hotkeyCard.offsetTop}; + hotkeyDragBar.setPointerCapture(e.pointerId);e.preventDefault(); + }); + hotkeyDragBar.addEventListener("pointermove",e=>{ + if(dragHotkey?.id!==e.pointerId)return; + place(hotkeyCard,dragHotkey.left+e.clientX-dragHotkey.x, + dragHotkey.top+e.clientY-dragHotkey.y); + }); + const stopHotkeyDrag=e=>{ + if(dragHotkey?.id!==e.pointerId)return;dragHotkey=null; + if(hotkeyDragBar.hasPointerCapture(e.pointerId)) + hotkeyDragBar.releasePointerCapture(e.pointerId); + }; + hotkeyDragBar.addEventListener("pointerup",stopHotkeyDrag); + hotkeyDragBar.addEventListener("pointercancel",stopHotkeyDrag); + // Right-click on an actual MUTE/SOLO command, not an entire strip. document.addEventListener("contextmenu",e=>{ // Never expose Chromium/WebView2 browser menu inside the native app. e.preventDefault(); dismissMenu(); + const power=e.target.closest?.('[data-action="slotPower"],[data-action="fxOn"]'); + if(power){ + const selected=nativeFxHotkeyTarget(power); + if(selected){ + menuTrack=scope.findTrack(power);menuSlot=selected.slot??-1; + menuTarget=selected;requestHotkeyList(); + showMenu(e.clientX,e.clientY,"hotkey"); + } + return; + } + const button=e.target.closest?.('.mx-hw-key[data-action="mute"],.mx-hw-key[data-action="solo"]'); + if(button){ + const track=scope.findTrack(button); + const operation=button.dataset.action==="mute"?"SET_MUTE":"SET_SOLO"; + const channelId=eligibleHotkey(track,operation); + if(channelId){ + menuTrack=track;menuSlot=-1; + menuTarget={kind:"hotkey",channelId,operation,scope:"SESSION", + label:track.name+" · "+button.dataset.action.toUpperCase()}; + showMenu(e.clientX,e.clientY,"hotkey"); + } + return; + } const header=e.target.closest?.(".strip-identity-top"); const row=e.target.closest?.(".fxslot-row:not(.is-empty)"); if(header){ @@ -223,6 +543,32 @@ const selected=menuTarget; // Read coordinates before dismissMenu(): hidden menu offset is zero. const originX=menu.offsetLeft,originY=menu.offsetTop+menu.offsetHeight; + if(action==="hotkey-register"){dismissMenu();openHotkeyRegister();return;} + if(action==="hotkey-add"&&selected?.kind==="hotkey"){ + const existing=hotkeyEntries.find(m=>sameHotkeyTarget(m,selected)); + dismissMenu();openHotkeyCapture(selected,existing||null);return; + } + if(action==="hotkey-remove"&&selected?.kind==="hotkey"){ + const existing=hotkeyEntries.find(m=>sameHotkeyTarget(m,selected)); + dismissMenu(); + if(existing&&!hotkeyPending){ + hotkeyPending={requestId:nextHotkeyRequest(),kind:"DELETE",mapping:existing}; + backend.emitEvent("arMixHotkeyIntent",{operation:"DELETE", + requestId:hotkeyPending.requestId,mappingId:existing.id}); + } + return; + } + if(action==="hotkey-mute"||action==="hotkey-solo"){ + const operation=action==="hotkey-mute"?"SET_MUTE":"SET_SOLO"; + const channelId=eligibleHotkey(track,operation); + dismissMenu(); + if(channelId){ + const target={channelId,operation,scope:"SESSION", + label:track.name+" · "+(operation==="SET_MUTE"?"MUTE":"SOLO")}; + openHotkeyCapture(target,hotkeyEntries.find(m=>sameHotkeyTarget(m,target))||null); + } + return; + } if(action==="delete"){ if(!hooks.canDeleteStrip?.(track))return; confirmation=true;showMenu(menu.offsetLeft,menu.offsetTop,"strip");return; @@ -278,9 +624,13 @@ document.addEventListener("keydown",e=>{ if(e.key!=="Escape")return; if(!menu.hidden){e.preventDefault();e.stopImmediatePropagation();dismissMenu();} + else if(!hotkeyRegister.hidden){e.preventDefault();hotkeyRegister.hidden=true;} else if(!orbit.hidden){e.preventDefault();e.stopImmediatePropagation();closeOrbit();} },true); - window.addEventListener("blur",dismissMenu); + window.addEventListener("blur",()=>{ + dismissMenu(); + if(!hotkeyCard.hidden && !hotkeyPending)closeHotkeyCapture(); + }); window.addEventListener("resize",dismissMenu); document.addEventListener("scroll",dismissMenu,true); }