diff --git a/.github/workflows/native-fx-owned-editor.yml b/.github/workflows/native-fx-owned-editor.yml new file mode 100644 index 000000000..81b871a83 --- /dev/null +++ b/.github/workflows/native-fx-owned-editor.yml @@ -0,0 +1,41 @@ +name: Native FX owned editor + reopen FAT (focused Windows) +on: + pull_request: + paths: + - 'src/Main.cpp' + - 'src/NativeOwnedFloatingWindow.h' + - 'src/NativeFxWin32Owner.h' + - 'tests/native_fx_win32_owner_test.cpp' + - 'tests/native_fx_window_lifecycle_contract_test.py' + - 'tests/native_fx_window_owner/**' + - '.github/workflows/native-fx-owned-editor.yml' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: owned-fx-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +jobs: + windows-owned-fx: + runs-on: windows-2022 + timeout-minutes: 9 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Fail closed on all three native editor lifetime paths + shell: pwsh + run: python -m unittest discover -s tests -p native_fx_window_lifecycle_contract_test.py -v + - name: Configure and compile only Win32 HWND host test (no JUCE or ASIO) + shell: pwsh + run: | + cmake -S tests/native_fx_window_owner -B build-owned-fx -G "Visual Studio 17 2022" -A x64 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + cmake --build build-owned-fx --config Release --parallel 2 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Verify owned z-order, hide and reopen without global TOPMOST + shell: pwsh + run: | + ctest --test-dir build-owned-fx -C Release --output-on-failure + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/CMakeLists.txt b/CMakeLists.txt index a0e8b389c..447ec67f9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -203,7 +203,7 @@ if(WIN32) # Dedicated INITGUID TU supplies PKEY_AudioEndpoint_FormFactor and # PKEY_AudioEngine_DeviceFormat to the Windows MMDevice discovery path. target_sources(ARMixConsole PRIVATE engine/device/WindowsAudioPropertyKeys.cpp) - target_link_libraries(ARMixConsole PRIVATE ole32 uuid advapi32) + target_link_libraries(ARMixConsole PRIVATE ole32 uuid advapi32 dwmapi) endif() target_link_libraries(ARMixConsole PRIVATE diff --git a/src/Main.cpp b/src/Main.cpp index 66d616a37..72b389b21 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -12,6 +12,7 @@ #include "NativeSessionToken.h" #include "ArSonMixStartupSplash.h" #include "ArSonWindowChrome.h" +#include "NativeOwnedFloatingWindow.h" #include "VstOrbitController.h" #include "../engine/core/OrbitDistanceMapping.h" #include "../engine/core/DearVrPolarPolicy.h" @@ -178,15 +179,25 @@ class Browser final : public juce::WebBrowserComponent class PluginEditorWindow final : public juce::DocumentWindow { public: - PluginEditorWindow (const juce::String& title, juce::AudioProcessorEditor* editor) + PluginEditorWindow (const juce::String& title, juce::AudioProcessorEditor* editor, + juce::Component& mixer) : DocumentWindow (title, juce::Colour (0xff14212a), allButtons) { setUsingNativeTitleBar (true); setIcon (approvedAppIcon()); setContentOwned (editor, true); - setResizable (true, true); + setResizable (editor->isResizable(), false); centreWithSize (juce::jmax (380, editor->getWidth()), juce::jmax (300, editor->getHeight())); + (void) armix::ui::attachOwnedFloatingWindow (*this, mixer); setVisible (true); + (void) armix::ui::attachOwnedFloatingWindow (*this, mixer); + present(); + } + void present() + { + if (!isVisible()) setVisible (true); + if (isMinimised()) setMinimised (false); + toFront (true); } void closeButtonPressed() override { setVisible (false); } }; @@ -195,7 +206,8 @@ class AudioSetupWindow final : public juce::DocumentWindow { public: explicit AudioSetupWindow (juce::AudioDeviceManager& manager, - std::function onClosed) + std::function onClosed, + juce::Component& mixer) : juce::DocumentWindow ("AR MIX — ASIO / WASAPI Setup", juce::Colour (0xff14212a), allButtons), onClosed_ (std::move (onClosed)) @@ -216,6 +228,7 @@ class AudioSetupWindow final : public juce::DocumentWindow selector->setSize (720, 550); setContentOwned (selector, false); centreWithSize (740, 590); + (void) armix::ui::attachOwnedFloatingWindow (*this, mixer); } void closeButtonPressed() override { setVisible (false); } void visibilityChanged() override @@ -585,6 +598,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr juce::String lastNativeThrowEpoch_,lastNativeThrowRevision_; armix::mixer::NativeMusicTempoMonitor::State lastMusicTempo_{}; std::unique_ptr editorWindow_; + juce::AudioProcessor* editorProcessor_=nullptr; // borrowed identity, UI only std::unique_ptr audioSetupWindow_; // Persistent modal lease: blocks an Apply/ASIO restart while JUCE's // device selector is open, not merely during the initial show() call. @@ -1028,8 +1042,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } void closePluginEditor() noexcept { - // JUCE destroys the editor before releasing the owner's processor. + // Destruct the editor BEFORE releasing its exact PCM instance lease. editorWindow_.reset(); + editorProcessor_=nullptr; routedEditorOwner_.reset(); routedEditorEpoch_=0; } @@ -1303,23 +1318,32 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } void openLogicalVendorEditor(const juce::var& request) { - if(logicalVendorEditor_ || mixerSessionWorker_.busy() || logicalMixer_.readOnly()) { - emitNotice("Close the current FX editor or wait for the mixer to finish saving",true); - return; - } std::uint64_t channel=0; std::size_t slot=0; if(!logicalFxTarget(request,channel,slot)) { emitNotice("The selected FX slot changed",true); return; } + if(logicalVendorEditor_) { + auto& existing=*logicalVendorEditor_; + if(existing.window) existing.window->present(); + if(existing.workspaceToken==logicalMixer_.workspace().workspaceToken() && + existing.insert.channel==channel && existing.insert.slot==slot) + return; // Reuse the same already accepted logical instance. + emitNotice("Finish the currently open FX editor first",true); + return; + } + if(mixerSessionWorker_.busy() || logicalMixer_.readOnly()) { + emitNotice("Finish the current mixer save before opening FX",true); + return; + } LogicalVendorEditor prepared; auto error=prepareLogicalFx(logicalMixer_.workspace(),{channel},slot,prepared.insert,prepared.processor); if(error.isEmpty()) { try { if(auto* editor=prepared.processor->createEditorIfNeeded()) { prepared.window=std::make_unique( - prepared.processor->getName(),editor); + prepared.processor->getName(),editor,*this); prepared.workspaceToken=logicalMixer_.workspace().workspaceToken(); logicalVendorEditor_=std::move(prepared); return; @@ -2683,8 +2707,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr : "Choose a working stereo output in Audio I/O. Input hardware is optional.", true); safe->emitApprovedNativeSnapshot(); } - }); + }, *safe); safe->audioSetupWindow_->setVisible (true); + (void) armix::ui::attachOwnedFloatingWindow ( + *safe->audioSetupWindow_, *safe); safe->audioSetupWindow_->toFront (true); // The peer now exists: perform one initial JUCE layout on the // message thread, rather than relying on a manual window drag. @@ -6450,13 +6476,23 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } } else owner=engine_.leaseRoutedFxForEditor(lane,slot,epoch,revision,token); if(owner && owner->processor) { - try { + // A second click on an exact accepted FX instance raises + // its existing visible/hidden UI; do not recreate JUCE + // AudioProcessor's active editor on every interaction. + if(editorWindow_ && routedEditorOwner_==owner && + routedEditorEpoch_==retainedEpoch && + editorProcessor_==owner->processor.get()) { + editorWindow_->present(); + opened=true; + error.clear(); + } else try { closePluginEditor(); if(auto* editor=owner->processor->createEditorIfNeeded()) { routedEditorOwner_=owner; routedEditorEpoch_=retainedEpoch; editorWindow_=std::make_unique( - owner->processor->getName(),editor); + owner->processor->getName(),editor,*this); + editorProcessor_=owner->processor.get(); opened=true; error.clear(); } else error="This VST3 has no native editor"; @@ -7317,14 +7353,31 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Never open an editor for an old graph waiting to be destroyed. if (engine_.isGraphSwitchPending()) return emitNotice ("FX recall is transitioning; open the editor after recall completes.", true); - closePluginEditor(); if (auto* processor = engine_.pluginAt (slot)) { - if (auto* editor = processor->createEditorIfNeeded()) - editorWindow_ = std::make_unique ( - processor->getName(), editor); + if (editorWindow_ && !routedEditorOwner_ && + editorProcessor_ == processor) + { + editorWindow_->present(); + } else - emitNotice ("This VST3 does not expose a graphical editor.", true); + { + closePluginEditor(); + if (auto* editor = processor->createEditorIfNeeded()) + { + editorWindow_ = std::make_unique ( + processor->getName(), editor, *this); + editorProcessor_=processor; + } + else + emitNotice ("This VST3 does not expose a graphical editor.", true); + } + } + else + { + // The requested slot no longer owns a processor. Never + // leave a floating editor bound to a retired plugin. + closePluginEditor(); } } else if (action == "monitor" && value.isBool()) diff --git a/src/NativeFxWin32Owner.h b/src/NativeFxWin32Owner.h new file mode 100644 index 000000000..acd4bd2a3 --- /dev/null +++ b/src/NativeFxWin32Owner.h @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#if defined(_WIN32) +#include +#include + +namespace armix::ui::win32 { +// Native Windows caption colour is OS-owned. Prefer its supported dark +// presentation to match the mixer; unsupported Windows versions are benign. +// The plugin remains an ordinary non-topmost document window. +inline void preferDarkTitleBar(HWND hwnd) noexcept { + if(!hwnd || !::IsWindow(hwnd))return; + const BOOL dark=TRUE; + constexpr DWORD modernAttribute=20; // DWMWA_USE_IMMERSIVE_DARK_MODE + const auto hr=::DwmSetWindowAttribute(hwnd,modernAttribute,&dark,sizeof(dark)); + if(FAILED(hr)) { + constexpr DWORD olderAttribute=19; // Earlier Windows 10 preview API + (void)::DwmSetWindowAttribute(hwnd,olderAttribute,&dark,sizeof(dark)); + } +} +// UI thread only. GWLP_HWNDPARENT means owner for top-level WS_POPUP/ +// WS_OVERLAPPED windows. Do NOT SetParent(), create WS_CHILD, or set TOPMOST. +inline bool attachOwnedPopup(HWND popup, HWND owner) noexcept { + if (popup == nullptr || owner == nullptr || popup == owner || + !::IsWindow(popup) || !::IsWindow(owner) || + (::GetWindowLongPtrW(popup,GWL_STYLE) & WS_CHILD) != 0) + return false; + if (::GetWindow(popup,GW_OWNER)==owner) return true; + ::SetLastError(0); + const auto previous=::SetWindowLongPtrW( + popup,GWLP_HWNDPARENT,reinterpret_cast(owner)); + if (previous==0 && ::GetLastError()!=0) return false; + return ::GetWindow(popup,GW_OWNER)==owner; +} +} // namespace armix::ui::win32 +#endif diff --git a/src/NativeOwnedFloatingWindow.h b/src/NativeOwnedFloatingWindow.h new file mode 100644 index 000000000..b6d89eaa2 --- /dev/null +++ b/src/NativeOwnedFloatingWindow.h @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include "NativeFxWin32Owner.h" + +namespace armix::ui { +// UI/message-thread only. An HWND owner keeps plugin windows above the mixer +// without making them system-wide topmost or child components of WebView2. +inline bool attachOwnedFloatingWindow(juce::Component& floating, + juce::Component& mixer) noexcept { +#if defined(_WIN32) + const auto* popupPeer=floating.getPeer(); + const auto* mixerPeer=mixer.getPeer(); + if(popupPeer==nullptr || mixerPeer==nullptr)return false; + const auto child=static_cast(popupPeer->getNativeHandle()); + const auto owner=static_cast(mixerPeer->getNativeHandle()); + const bool attached=win32::attachOwnedPopup(child,owner); + win32::preferDarkTitleBar(child); + return attached; +#else + (void)floating; + (void)mixer; + return true; // Native non-Windows foreground policy remains JUCE-owned. +#endif +} +} // namespace armix::ui diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 5a87e39dd..e78b476f6 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1897,8 +1897,17 @@ test("native vendor editor retention follows current PCM ownership, not inactive assert.match(main,/routedEditorEpoch_=retainedEpoch/); assert.match(main,/retainedEpoch=ep/); assert.match(lab,/nativeAccepted_\.fxOwners->retainsEditor\(owner\)/); - const editor=main.slice(main.indexOf('if(owner && owner->processor)'),main.indexOf('if(owner && owner->processor)')+700); - assert.ok(editor.indexOf('closePluginEditor();')processor)'); + assert.ok(start>=0,'routed FX editor source must exist'); + const editor=main.slice(start,main.indexOf('catch(const std::exception& ex)',start)); + assert.ok(editor.includes('routedEditorOwner_==owner'), + 'reopen only exact current accepted PCM owner'); + assert.ok(editor.includes('editorWindow_->present()'), + 'same FX instance must be focused instead of recreated'); + const fresh=editor.slice(editor.indexOf('} else try {')); + assert.ok(fresh.includes('closePluginEditor();') && + fresh.indexOf('closePluginEditor();') +#include + +int main(){ + const auto instance=::GetModuleHandleW(nullptr); + WNDCLASSW cls{}; + cls.lpfnWndProc=::DefWindowProcW; + cls.hInstance=instance; + cls.lpszClassName=L"ArSonMixOwnedFxRegression"; + assert(::RegisterClassW(&cls)!=0); + constexpr DWORD style=WS_OVERLAPPEDWINDOW; + auto mixer=::CreateWindowExW(0,cls.lpszClassName,L"Mixer",style, + 100,100,650,470,nullptr,nullptr,instance,nullptr); + auto popup=::CreateWindowExW(0,cls.lpszClassName,L"Native FX",style, + 200,180,420,300,nullptr,nullptr,instance,nullptr); + auto alternate=::CreateWindowExW(0,cls.lpszClassName,L"Unrelated",style, + 240,210,200,140,nullptr,nullptr,instance,nullptr); + assert(mixer && popup && alternate); + assert(::GetWindow(popup,GW_OWNER)==nullptr); + assert(armix::ui::win32::attachOwnedPopup(popup,mixer)); + assert(::GetWindow(popup,GW_OWNER)==mixer); + armix::ui::win32::preferDarkTitleBar(popup); // graceful if OS DWM unsupported + // Repeated open has no owner churn, even when hidden and shown again. + assert(armix::ui::win32::attachOwnedPopup(popup,mixer)); + ::ShowWindow(popup,SW_HIDE); + ::ShowWindow(popup,SW_SHOWNOACTIVATE); + assert(armix::ui::win32::attachOwnedPopup(popup,mixer)); + assert(::GetWindow(popup,GW_OWNER)==mixer); + assert((::GetWindowLongPtrW(popup,GWL_STYLE)&WS_CHILD)==0); + assert((::GetWindowLongPtrW(popup,GWL_EXSTYLE)&WS_EX_TOPMOST)==0); + assert(::GetAncestor(popup,GA_ROOT)==popup); + assert(::GetWindow(alternate,GW_OWNER)==nullptr); + assert(!armix::ui::win32::attachOwnedPopup(popup,popup)); + assert(!armix::ui::win32::attachOwnedPopup(nullptr,mixer)); + assert(::GetWindow(popup,GW_OWNER)==mixer); + ::DestroyWindow(popup); + ::DestroyWindow(alternate); + ::DestroyWindow(mixer); + ::UnregisterClassW(cls.lpszClassName,instance); + std::puts("PASS: FX HWND owned by mixer, reusable after hide, never system TOPMOST"); +} diff --git a/tests/native_fx_window_lifecycle_contract_test.py b/tests/native_fx_window_lifecycle_contract_test.py new file mode 100644 index 000000000..7d23b6de3 --- /dev/null +++ b/tests/native_fx_window_lifecycle_contract_test.py @@ -0,0 +1,40 @@ +# SPDX-License-Identifier: AGPL-3.0-only +"""Fast source contract for *all* three native editor entrypoints.""" +from pathlib import Path +import unittest +ROOT=Path(__file__).resolve().parents[1] +HOST=(ROOT/"src/Main.cpp").read_text(encoding="utf-8") +OWNER=(ROOT/"src/NativeOwnedFloatingWindow.h").read_text(encoding="utf-8") +WIN32=(ROOT/"src/NativeFxWin32Owner.h").read_text(encoding="utf-8") + +class NativeFxWindowLifecycle(unittest.TestCase): + def test_mixer_owned_not_global_topmost(self): + self.assertIn("attachOwnedFloatingWindow (*this, mixer)",HOST) + self.assertIn("attachOwnedFloatingWindow",OWNER) + self.assertIn("win32::attachOwnedPopup",OWNER) + self.assertIn("GWLP_HWNDPARENT",WIN32) + self.assertIn("GW_OWNER",WIN32) + self.assertIn("WS_CHILD",WIN32) + self.assertNotIn("WS_EX_TOPMOST",WIN32) + self.assertNotIn("::SetParent(",WIN32) + self.assertNotIn("setAlwaysOnTop (true)",HOST) + def test_exact_native_instance_reopen_is_not_recreation(self): + self.assertIn("routedEditorOwner_==owner",HOST) + self.assertIn("editorProcessor_==owner->processor.get()",HOST) + self.assertIn("editorWindow_->present()",HOST) + self.assertIn("if(logicalVendorEditor_)",HOST) + self.assertIn("existing.window->present()",HOST) + self.assertIn("editorProcessor_ == processor",HOST) + self.assertIn("if (!isVisible()) setVisible (true)",HOST) + self.assertIn("toFront (true)",HOST) + self.assertIn("editorWindow_.reset();",HOST) + self.assertIn("routedEditorOwner_.reset();",HOST) + self.assertIn("editorProcessor_=nullptr;",HOST) + def test_all_editor_paths_use_one_host(self): + self.assertEqual(HOST.count("std::make_unique"),3) + self.assertIn("prepared.processor->getName(),editor,*this)",HOST) + self.assertIn("owner->processor->getName(),editor,*this)",HOST) + self.assertIn("processor->getName(), editor, *this",HOST) + self.assertIn("std::make_unique",HOST) + self.assertIn("}, *safe);",HOST) +if __name__=="__main__":unittest.main() diff --git a/tests/native_fx_window_owner/CMakeLists.txt b/tests/native_fx_window_owner/CMakeLists.txt new file mode 100644 index 000000000..834064582 --- /dev/null +++ b/tests/native_fx_window_owner/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.20) +project(ArSonMixNativeFxWindowOwnerTests LANGUAGES CXX) +if(NOT WIN32) + message(FATAL_ERROR "This isolated HWND FAT is Windows-only") +endif() +enable_testing() +add_executable(ArSonMixOwnedFxWindowTest ../native_fx_win32_owner_test.cpp) +target_compile_features(ArSonMixOwnedFxWindowTest PRIVATE cxx_std_20) +target_link_libraries(ArSonMixOwnedFxWindowTest PRIVATE user32 dwmapi) +if(MSVC) + target_compile_options(ArSonMixOwnedFxWindowTest PRIVATE /W4 /WX) +endif() +add_test(NAME NativeFxOwnedWindowNotGlobalTopmostAndReopens + COMMAND ArSonMixOwnedFxWindowTest)