From ffab6f65b771fdaa4564ec13e6d5fdbfa47a7475 Mon Sep 17 00:00:00 2001 From: XmengMD <16805027+xmengmd@user.noreply.gitee.com> Date: Thu, 17 Sep 2026 17:15:51 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=8F=92=E4=BB=B6=E6=89=AB?= =?UTF-8?q?=E6=8F=8F=E5=8D=A1=E6=AD=BB=EF=BC=9A=E6=89=AB=E6=8F=8F=E4=B8=8E?= =?UTF-8?q?=E6=A7=BD=E4=BD=8D=E5=8A=A0=E8=BD=BD=E5=85=A8=E9=83=A8=E5=BC=82?= =?UTF-8?q?=E6=AD=A5=E5=8C=96=EF=BC=8C=E6=B6=88=E6=81=AF=E7=BA=BF=E7=A8=8B?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E9=98=BB=E5=A1=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PluginRegistry 新增后台扫描线程(ScanWorkerThread),目录枚举与逐文件扫描在后台执行,进度与结果经内部队列缓存,由消息线程周期调用 pumpScanResults() 应用,并支持取消。 PluginManagerComponent 弃用同步阻塞的 JUCE PluginListComponent 扫描,改为自建列表 UI,通过 Timer 轮询进度与结果,扫描期间界面保持可交互;PluginBlacklist 增加互斥锁,支持后台线程并发访问。 MainComponent 槽位加载改走 ThreadPool 后台初始化,结果经 processSlotLoadResults 统一在消息线程写入混音图,加载期间不再卡死界面。 --- Source/MainComponent.cpp | 334 +++++++---- Source/MainComponent.h | 23 +- Source/Plugin/PluginBlacklist.cpp | 16 + Source/Plugin/PluginBlacklist.h | 5 + Source/Plugin/PluginManagerComponent.cpp | 715 ++++++++++++++++++++--- Source/Plugin/PluginManagerComponent.h | 122 +++- Source/Plugin/PluginRegistry.cpp | 550 ++++++++++++++--- Source/Plugin/PluginRegistry.h | 95 ++- 8 files changed, 1551 insertions(+), 309 deletions(-) diff --git a/Source/MainComponent.cpp b/Source/MainComponent.cpp index 506c94d..7123ad1 100644 --- a/Source/MainComponent.cpp +++ b/Source/MainComponent.cpp @@ -1,14 +1,36 @@ #include "MainComponent.h" -#include "PluginScanner/VST3Scanner.h" #include "Plugin/PluginRegistry.h" #include "Plugin/PluginArchitecture.h" #include "Plugin/PluginBridgeNode.h" #include "Plugin/PluginSelectorComponent.h" #include "Settings/AppSettings.h" +#include + namespace minixer { +//============================================================================== +/** 单个插件槽位的异步加载结果(后台线程 → 消息线程)。 */ +struct PluginLoadOutcome +{ + uint64_t generation = 0; // 发起加载时的槽位代数 + bool ok = false; + juce::String error; + std::unique_ptr bridge; // 成功时为已初始化节点 + juce::PluginDescription description; // 完成时更新 slotStates 用 + std::optional stateToRestore; +}; + +/** 单个插件槽位的共享加载状态。 */ +struct PluginLoadSlot +{ + std::mutex mutex; + uint64_t generation = 0; // 每次新加载/取消递增,作废在途任务 + bool pending = false; + std::unique_ptr outcome; +}; + //============================================================================== MonoToStereoProcessor::MonoToStereoProcessor() : juce::AudioProcessor (juce::AudioProcessor::BusesProperties() @@ -255,6 +277,12 @@ MainComponent::MainComponent() // 启动定时器更新 UI 电平 startTimerHz (30); + // 插件后台加载线程池(少量并发,UI 线程不参与加载/校验)与共享槽位状态 + pluginLoaderPool = std::make_unique (4); + + for (auto& slot : pluginLoadSlots) + slot = std::make_shared(); + // 应用启动设置(自动加载预设等) applyStartupSettings(); @@ -280,6 +308,11 @@ MainComponent::~MainComponent() stopTimer(); + // 终止仍在进行中的后台加载任务(等 5s;极端情况下在途任务会继续运行至 + // 自身 120s 超时,进程退出时由操作系统回收,不阻塞 UI 线程)。 + if (pluginLoaderPool != nullptr) + pluginLoaderPool->removeAllJobs (true, 5000); + closeAllPluginEditors(); // 保存当前音频设备状态 @@ -382,6 +415,9 @@ void MainComponent::timerCallback() // 检测焦点外的系统全局插槽快捷键 pollGlobalSlotShortcuts(); + + // 取回后台线程完成的插件桥接加载结果(消息线程执行图操作) + processSlotLoadResults(); } //============================================================================== @@ -1171,6 +1207,10 @@ void MainComponent::refreshSlotDisplays() //============================================================================== void MainComponent::moveSlotContent (int fromIndex, int toIndex) { + // 移动期间作废两个槽位的在途加载,避免旧加载完成后写回错位槽位 + cancelSlotLoadsForSlot (fromIndex); + cancelSlotLoadsForSlot (toIndex); + auto sourceState = slotStates[fromIndex]; auto sourceNode = pluginSlotNodes[fromIndex]; @@ -1235,7 +1275,7 @@ void MainComponent::loadPluginIntoSlot (int slotIndex, const juce::PluginDescrip if (audioGraph == nullptr) return; - // 先移除该槽位已有的插件,避免重复占用 + // 先移除该槽位已有的插件,并作废该槽位一切在途加载,避免重复占用 removePluginFromSlot (slotIndex, false); statusLabel.setText (TRANS ("Loading ") + description.name + TRANS ("..."), @@ -1251,149 +1291,188 @@ void MainComponent::loadPluginIntoSlot (int slotIndex, const juce::PluginDescrip const auto arch = detectPluginArchitecture (juce::File (description.fileOrIdentifier)); - // 32-bit 插件通过独立子进程桥接加载,避免 64-bit 宿主无法直接加载 32-bit DLL。 - if (arch == PluginArchitecture::x86 && ! canHostLoadArchitectureDirectly (arch)) - { - auto bridgeNode = std::make_unique (description, arch); - juce::String error; - - if (bridgeNode->initialize (sampleRate, bufferSize, error)) - { - bridgeNode->addListener (this); - bridgeNode->prepareToPlay (sampleRate, bufferSize); - - auto node = audioGraph->addNode (std::move (bridgeNode)); - - if (node != nullptr) - { - pluginSlotNodes[slotIndex] = node; - slotStates[slotIndex].pluginIdentifier = description.createIdentifierString(); - slotStates[slotIndex].pluginName = description.name; - - if (stateToRestore.has_value() - && stateToRestore->pluginIdentifier == slotStates[slotIndex].pluginIdentifier) - { - if (stateToRestore->pluginState.getSize() > 0) - { - node->getProcessor()->setStateInformation (stateToRestore->pluginState.getData(), - static_cast (stateToRestore->pluginState.getSize())); - } - } - - applySlotBypassDefault (slotIndex); - rebuildPluginChain(); - - statusLabel.setText (TRANS ("Loaded ") + slotStates[slotIndex].pluginName + TRANS (" in slot ") + juce::String (slotIndex + 1), - juce::dontSendNotification); - } - else - { - statusLabel.setText (TRANS ("Failed to add plugin to graph"), - juce::dontSendNotification); - } - } - else - { - statusLabel.setText (TRANS ("Failed to load bridged plugin: ") + error, - juce::dontSendNotification); - } - - return; - } - - // 64-bit 插件仍按原有异步路径直接在宿主进程加载。 - // —— 加载侧修复 —— - // JUCE 的 VST3PluginFormat 在 createPluginInstance 内部先解析类索引、之后才 - // 调用 IPluginFactory3::setHostContext;外壳插件(WaveShell / IKM 等)在设置 - // 宿主上下文后会重排/追加工厂类表,导致此前解析的索引失效而“点 A 出 B”。 - // 这里先预加载模块并完成 setHostContext,使 JUCE 在“已展开”的类表上按 - // name + CID 哈希匹配到正确索引(模块句柄保留到进程退出)。预加载失败不阻塞。 - if (description.pluginFormatName == "VST3" && description.fileOrIdentifier.isNotEmpty()) - { - juce::String prewarmError; - minixer::vst3scan::VST3Scanner::prewarmForLoad (juce::File (description.fileOrIdentifier), - &prewarmError); - - if (prewarmError.isNotEmpty()) - juce::Logger::writeToLog ("VST3 preload skipped for " + description.fileOrIdentifier + ": " + prewarmError); - } - - PluginRegistry::getInstance().getFormatManager().createPluginInstanceAsync ( - description, - sampleRate, - bufferSize, - [this, slotIndex, description, stateToRestore] (std::unique_ptr instance, - const juce::String& errorMessage) - { - onPluginInstanceCreated (slotIndex, description, std::move (instance), errorMessage, stateToRestore); - }); + // 所有架构(x86 / x64 / 未知)统一通过 PluginHost 子进程桥接加载: + // 插件 DLL 的加载、实例化、license 校验全部在子进程内完成,与主进程 UI + // 完全隔离,加载期间主界面保持可交互、音频通路保持连贯。 + startSlotLoad (slotIndex, description, arch, sampleRate, bufferSize, stateToRestore); } //============================================================================== -void MainComponent::onPluginInstanceCreated (int slotIndex, - const juce::PluginDescription& description, - std::unique_ptr instance, - const juce::String& errorMessage, - const std::optional& stateToRestore) +void MainComponent::startSlotLoad (int slotIndex, const juce::PluginDescription& description, + PluginArchitecture arch, double sampleRate, int bufferSize, + const std::optional& stateToRestore) { if (slotIndex < 0 || slotIndex >= defaultNumPluginSlots) return; - if (instance == nullptr) + auto slot = pluginLoadSlots[slotIndex]; + + if (slot == nullptr || pluginLoaderPool == nullptr) { - statusLabel.setText (TRANS ("Failed to load plugin: ") + errorMessage, + statusLabel.setText (TRANS ("Failed to load plugin: internal error"), juce::dontSendNotification); return; } - // 与 JUCE AudioPluginHost 保持一致:先启用所有总线,避免插件默认总线未激活 - // 导致 graph 连接时通道数为 0。 - instance->enableAllBuses(); - - auto sampleRate = audioDeviceManager.getCurrentAudioDevice() != nullptr - ? audioDeviceManager.getCurrentAudioDevice()->getCurrentSampleRate() - : 44100.0; - - auto bufferSize = audioDeviceManager.getCurrentAudioDevice() != nullptr - ? audioDeviceManager.getCurrentAudioDevice()->getCurrentBufferSizeSamples() - : 512; - - instance->prepareToPlay (sampleRate, bufferSize); - - auto node = audioGraph->addNode (std::move (instance)); - - if (node == nullptr) + uint64_t generation = 0; { - statusLabel.setText (TRANS ("Failed to add plugin to graph"), - juce::dontSendNotification); - return; + std::lock_guard lock (slot->mutex); + + ++slot->generation; + generation = slot->generation; + + // 丢弃尚未被消息线程取走的旧结果,避免新旧加载混淆 + slot->outcome.reset(); + slot->pending = false; } - pluginSlotNodes[slotIndex] = node; - - auto* processor = node->getProcessor(); - - slotStates[slotIndex].pluginIdentifier = description.createIdentifierString(); - slotStates[slotIndex].pluginName = description.name.isEmpty() ? processor->getName() : description.name; - - // 若需要恢复预设/剪贴板状态,则先恢复插件参数 - if (stateToRestore.has_value() - && stateToRestore->pluginIdentifier == slotStates[slotIndex].pluginIdentifier) + // 后台线程执行桥接初始化(子进程启动 + 插件加载 + license 校验等耗时操作)。 + // 期间 UI 不做任何同步等待;结果写入共享槽位,由消息线程定时器取回。 + // 显式指定 JobStatus 返回类型,避免与 addJob(std::function) 重载歧义。 + auto loadTask = [slot, generation, description, arch, sampleRate, bufferSize, stateToRestore]() -> juce::ThreadPoolJob::JobStatus { - if (stateToRestore->pluginState.getSize() > 0) + auto outcome = std::make_unique(); + outcome->generation = generation; + outcome->description = description; + outcome->stateToRestore = stateToRestore; + + auto bridge = std::make_unique (description, arch); + juce::String error; + + if (! bridge->initialize (sampleRate, bufferSize, error)) { - processor->setStateInformation (stateToRestore->pluginState.getData(), - static_cast (stateToRestore->pluginState.getSize())); + outcome->error = error; + bridge->shutdown(); + bridge.reset(); } + + outcome->bridge = std::move (bridge); + outcome->ok = (outcome->bridge != nullptr); + + { + std::lock_guard lock (slot->mutex); + slot->outcome = std::move (outcome); + slot->pending = true; + } + + return juce::ThreadPoolJob::jobHasFinished; + }; + + pluginLoaderPool->addJob (std::function (std::move (loadTask))); +} + +//============================================================================== +void MainComponent::cancelSlotLoadsForSlot (int slotIndex) +{ + if (slotIndex < 0 || slotIndex >= defaultNumPluginSlots) + return; + + auto slot = pluginLoadSlots[slotIndex]; + if (slot == nullptr) + return; + + std::lock_guard lock (slot->mutex); + + // 递增代数:任何在途加载完成时与当前代数不符,将被丢弃并关闭其子进程 + ++slot->generation; + + // 丢弃尚未被消息线程取走的结果 + slot->outcome.reset(); + slot->pending = false; +} + +//============================================================================== +void MainComponent::processSlotLoadResults() +{ + for (int slotIndex = 0; slotIndex < defaultNumPluginSlots; ++slotIndex) + { + auto slot = pluginLoadSlots[slotIndex]; + if (slot == nullptr) + continue; + + std::unique_ptr outcome; + uint64_t currentGeneration = 0; + + { + std::lock_guard lock (slot->mutex); + + if (! slot->pending) + continue; + + outcome = std::move (slot->outcome); + slot->outcome.reset(); + slot->pending = false; + currentGeneration = slot->generation; + } + + if (outcome == nullptr) + continue; + + // 该槽位已发生新的加载请求或已被移除 → 作废本次结果(关闭其子进程) + if (outcome->generation != currentGeneration) + { + if (outcome->bridge != nullptr) + outcome->bridge->shutdown(); + continue; + } + + if (! outcome->ok) + { + statusLabel.setText (TRANS ("Failed to load bridged plugin: ") + outcome->error, + juce::dontSendNotification); + continue; + } + + auto* bridge = outcome->bridge.get(); + + bridge->addListener (this); + + const auto sampleRate = audioDeviceManager.getCurrentAudioDevice() != nullptr + ? audioDeviceManager.getCurrentAudioDevice()->getCurrentSampleRate() + : 44100.0; + + const auto bufferSize = audioDeviceManager.getCurrentAudioDevice() != nullptr + ? audioDeviceManager.getCurrentAudioDevice()->getCurrentBufferSizeSamples() + : 512; + + bridge->prepareToPlay (sampleRate, bufferSize); + + auto node = audioGraph->addNode (std::move (outcome->bridge)); + + if (node == nullptr) + { + statusLabel.setText (TRANS ("Failed to add plugin to graph"), + juce::dontSendNotification); + continue; + } + + pluginSlotNodes[slotIndex] = node; + + auto* processor = node->getProcessor(); + + slotStates[slotIndex].pluginIdentifier = outcome->description.createIdentifierString(); + slotStates[slotIndex].pluginName = outcome->description.name.isEmpty() ? processor->getName() + : outcome->description.name; + + // 若需要恢复预设/剪贴板状态,则先恢复插件参数 + if (outcome->stateToRestore.has_value() + && outcome->stateToRestore->pluginIdentifier == slotStates[slotIndex].pluginIdentifier) + { + if (outcome->stateToRestore->pluginState.getSize() > 0) + { + processor->setStateInformation (outcome->stateToRestore->pluginState.getData(), + static_cast (outcome->stateToRestore->pluginState.getSize())); + } + } + + // 新插件/替换/预设/粘贴加载后,统一按“全局旁通 + 槽位快捷键默认值”刷新 bypass + applySlotBypassDefault (slotIndex); + + rebuildPluginChain(); + + statusLabel.setText (TRANS ("Loaded ") + slotStates[slotIndex].pluginName + TRANS (" in slot ") + juce::String (slotIndex + 1), + juce::dontSendNotification); } - - // 新插件/替换/预设/粘贴加载后,统一按“全局旁通 + 槽位快捷键默认值”刷新 bypass - applySlotBypassDefault (slotIndex); - - rebuildPluginChain(); - - statusLabel.setText (TRANS ("Loaded ") + slotStates[slotIndex].pluginName + TRANS (" in slot ") + juce::String (slotIndex + 1), - juce::dontSendNotification); } //============================================================================== @@ -1402,6 +1481,9 @@ void MainComponent::removePluginFromSlot (int slotIndex, bool rebuildChain) if (slotIndex < 0 || slotIndex >= defaultNumPluginSlots) return; + // 作废该槽位一切在途加载(防止旧加载完成后又把节点塞回已移除的槽位) + cancelSlotLoadsForSlot (slotIndex); + if (pluginSlotNodes[slotIndex] != nullptr) { if (auto* bridge = dynamic_cast (pluginSlotNodes[slotIndex]->getProcessor())) diff --git a/Source/MainComponent.h b/Source/MainComponent.h index 015196f..f6c5fbd 100644 --- a/Source/MainComponent.h +++ b/Source/MainComponent.h @@ -122,6 +122,13 @@ private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelStripProcessor) }; +//============================================================================== +/** 插件异步加载的共享槽位状态(完整定义见 MainComponent.cpp)。 + 后台线程把结果写入槽位,消息线程的定时器统一取回应用;用 shared_ptr 保证 + 即使进程退出时仍有后台任务在途,也不会悬空访问。 +*/ +struct PluginLoadSlot; + //============================================================================== /** Minixer 主界面组件。 @@ -233,10 +240,14 @@ private: void showPluginSelectionMenu (int slotIndex); void loadPluginIntoSlot (int slotIndex, const juce::PluginDescription& description, const std::optional& stateToRestore = {}); - void onPluginInstanceCreated (int slotIndex, const juce::PluginDescription& description, - std::unique_ptr instance, - const juce::String& errorMessage, - const std::optional& stateToRestore); + + // 异步桥接加载(所有架构均通过 PluginHost 子进程,UI 不再被插件加载/校验阻塞) + void startSlotLoad (int slotIndex, const juce::PluginDescription& description, + PluginArchitecture arch, double sampleRate, int bufferSize, + const std::optional& stateToRestore); + void cancelSlotLoadsForSlot (int slotIndex); + void processSlotLoadResults(); + void removePluginFromSlot (int slotIndex, bool rebuildChain); void rebuildPluginChain(); void openPluginEditor (int slotIndex); @@ -308,6 +319,10 @@ private: // 每个槽位对应的插件节点 std::array pluginSlotNodes; + // 插件后台加载线程池(少量并发,UI 线程不参与) + std::unique_ptr pluginLoaderPool; + std::array, defaultNumPluginSlots> pluginLoadSlots; + // 每个槽位的持久化状态(用于预设保存/加载) std::array slotStates; diff --git a/Source/Plugin/PluginBlacklist.cpp b/Source/Plugin/PluginBlacklist.cpp index d64e8ea..95c99ef 100644 --- a/Source/Plugin/PluginBlacklist.cpp +++ b/Source/Plugin/PluginBlacklist.cpp @@ -133,6 +133,8 @@ void PluginBlacklist::save() const //============================================================================== void PluginBlacklist::recordCrash (const juce::String& filePath, int exitCode) { + std::lock_guard guard (lock); + BlacklistEntry entry; if (auto* existing = findEntry (filePath)) @@ -155,6 +157,8 @@ void PluginBlacklist::recordCrash (const juce::String& filePath, int exitCode) //============================================================================== void PluginBlacklist::recordScanFailure (const juce::String& filePath, const juce::String& reason) { + std::lock_guard guard (lock); + BlacklistEntry entry; if (auto* existing = findEntry (filePath)) @@ -176,6 +180,8 @@ void PluginBlacklist::recordScanFailure (const juce::String& filePath, const juc //============================================================================== void PluginBlacklist::clearEntry (const juce::String& filePath) { + std::lock_guard guard (lock); + for (int i = entries.size(); --i >= 0;) { if (entries.getReference (i).filePath == filePath) @@ -190,6 +196,8 @@ void PluginBlacklist::clearEntry (const juce::String& filePath) //============================================================================== void PluginBlacklist::clearAll() { + std::lock_guard guard (lock); + if (entries.isEmpty()) return; @@ -200,6 +208,8 @@ void PluginBlacklist::clearAll() //============================================================================== bool PluginBlacklist::isBlacklisted (const juce::String& filePath) const { + std::lock_guard guard (lock); + auto* entry = findEntry (filePath); return entry != nullptr && entry->shouldSkip(); } @@ -207,6 +217,8 @@ bool PluginBlacklist::isBlacklisted (const juce::String& filePath) const //============================================================================== bool PluginBlacklist::canRetry (const juce::String& filePath) const { + std::lock_guard guard (lock); + auto* entry = findEntry (filePath); return entry == nullptr || entry->canRetryNow(); } @@ -214,12 +226,16 @@ bool PluginBlacklist::canRetry (const juce::String& filePath) const //============================================================================== juce::Array PluginBlacklist::getEntries() const { + std::lock_guard guard (lock); + return entries; } //============================================================================== int PluginBlacklist::getNumEntries() const noexcept { + std::lock_guard guard (lock); + return entries.size(); } diff --git a/Source/Plugin/PluginBlacklist.h b/Source/Plugin/PluginBlacklist.h index 3f917ad..59f12d1 100644 --- a/Source/Plugin/PluginBlacklist.h +++ b/Source/Plugin/PluginBlacklist.h @@ -14,6 +14,8 @@ #include +#include + namespace minixer { @@ -97,6 +99,9 @@ private: //============================================================================== juce::Array entries; + /** 黑名单会被后台扫描线程(读 isBlacklisted)与消息线程(写)并发访问。 */ + mutable std::mutex lock; + JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginBlacklist) }; diff --git a/Source/Plugin/PluginManagerComponent.cpp b/Source/Plugin/PluginManagerComponent.cpp index c398f0a..3b56a41 100644 --- a/Source/Plugin/PluginManagerComponent.cpp +++ b/Source/Plugin/PluginManagerComponent.cpp @@ -11,48 +11,275 @@ #include "../Settings/AppSettings.h" #include "../LookAndFeel/MixerLookAndFeel.h" +#include + namespace minixer { +namespace +{ + +//============================================================================== +/** 比较两个 PluginDescription 以按指定列排序。 */ +struct PluginSorter +{ + int column; + bool forwards; + + bool operator() (const juce::PluginDescription& a, + const juce::PluginDescription& b) const + { + int cmp = 0; + + switch (column) + { + case PluginManagerComponent::colName: cmp = a.name.compare (b.name); break; + case PluginManagerComponent::colManufacturer: cmp = a.manufacturerName.compare (b.manufacturerName); break; + case PluginManagerComponent::colChannels: cmp = a.numInputChannels - b.numInputChannels; break; + default: cmp = a.name.compare (b.name); break; + } + + if (cmp == 0) + cmp = a.name.compare (b.name); + + return forwards ? (cmp < 0) : (cmp > 0); + } +}; + +//============================================================================== +/** 扫描目录编辑器:列出内置默认目录(只读)+ 用户自定义目录(可增删)。 */ +class ScanPathsEditorContent final : public juce::Component, + private juce::ListBoxModel +{ +public: + ScanPathsEditorContent() + { + addButton.setButtonText (TRANS ("Add folder...")); + addButton.onClick = [this] { addFolder(); }; + addAndMakeVisible (addButton); + + removeButton.setButtonText (TRANS ("Remove selected")); + removeButton.onClick = [this] { removeSelected(); }; + removeButton.setEnabled (false); + addAndMakeVisible (removeButton); + + list.setModel (this); + addAndMakeVisible (list); + + refresh(); + setSize (520, 360); + } + + void paint (juce::Graphics& g) override + { + g.fillAll (MixerLookAndFeel::getSurfaceColour()); + } + + void resized() override + { + auto bounds = getLocalBounds().reduced (8); + + auto top = bounds.removeFromTop (28); + addButton.setBounds (top.removeFromLeft (110)); + top.removeFromLeft (8); + removeButton.setBounds (top.removeFromLeft (150)); + + bounds.removeFromTop (8); + list.setBounds (bounds); + } + + //========================================================================== + // ListBoxModel + int getNumRows() override { return items.size(); } + + void paintListBoxItem (int rowNumber, juce::Graphics& g, + int width, int height, bool rowIsSelected) override + { + if (rowIsSelected) + g.fillAll (MixerLookAndFeel::getAccentColour().withAlpha (0.25f)); + + if (! juce::isPositiveAndBelow (rowNumber, items.size())) + return; + + g.setColour (MixerLookAndFeel::getTextColour()); + g.setFont (juce::Font (juce::FontOptions (13.0f))); + + juce::String text = items[rowNumber].path; + if (! items[rowNumber].removable) + text += " (" + TRANS ("default") + ")"; + + g.drawText (text, 4, 0, width - 8, height, + juce::Justification::centredLeft, true); + } + + void selectedRowsChanged (int) override { refreshRemoveButton(); } + +private: + struct Item + { + juce::String path; + bool removable; // 仅自定义目录可移除,默认目录为只读内置 + }; + + //========================================================================== + // 依据 PluginRegistry 当前的自定义目录重建显示列表。 + void refresh() + { + const auto defaultPaths = PluginRegistry::getInstance().getVST3DefaultSearchPath(); + const auto customPaths = PluginRegistry::getInstance().getCustomScanPaths(); + + items.clearQuick(); + + for (int i = 0; i < defaultPaths.getNumPaths(); ++i) + items.add ({ defaultPaths[i].getFullPathName(), false }); + + for (int i = 0; i < customPaths.getNumPaths(); ++i) + { + bool isDefault = false; + + for (int j = 0; j < defaultPaths.getNumPaths(); ++j) + if (defaultPaths[j].getFullPathName() == customPaths[i].getFullPathName()) + { isDefault = true; break; } + + if (! isDefault) + items.add ({ customPaths[i].getFullPathName(), true }); + } + + list.updateContent(); + list.deselectAllRows(); + refreshRemoveButton(); + } + + void refreshRemoveButton() + { + const int row = list.getSelectedRow(); + removeButton.setEnabled (juce::isPositiveAndBelow (row, items.size()) && items[row].removable); + } + + void addFolder() + { + chooser = std::make_shared ( + TRANS ("Add VST3 scan folder"), + juce::File::getSpecialLocation (juce::File::userHomeDirectory), + juce::String()); + + auto* rawPtr = chooser.get(); + + chooser->launchAsync ( + juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories, + [this, rawPtr] (const juce::FileChooser&) + { + const auto dir = rawPtr->getResult(); + + if (dir.isDirectory()) + { + PluginRegistry::getInstance().addScanPath (dir); + refresh(); + } + }); + } + + void removeSelected() + { + const int row = list.getSelectedRow(); + + if (juce::isPositiveAndBelow (row, items.size()) && items[row].removable) + { + PluginRegistry::getInstance().removeScanPath (juce::File (items[row].path)); + refresh(); + } + } + + //========================================================================== + juce::Array items; + juce::ListBox list; + juce::TextButton addButton; + juce::TextButton removeButton; + std::shared_ptr chooser; +}; + +//============================================================================== +/** 扫描目录编辑窗口:关闭时仅隐藏,便于再次打开。 */ +class ScanPathsEditorWindow final : public juce::DocumentWindow +{ +public: + using juce::DocumentWindow::DocumentWindow; + + void closeButtonPressed() override + { + setVisible (false); + } +}; + +} // anonymous namespace + //============================================================================== PluginManagerComponent::PluginManagerComponent() - : pluginListComponent (PluginRegistry::getInstance().getFormatManager(), - PluginRegistry::getInstance().getKnownPluginList(), - AppSettings::getInstance().getDeadMansPedalFile(), - AppSettings::getInstance().getPropertiesFile(), - false) + : table ("plugins") { - pluginListComponent.setLookAndFeel (&getLookAndFeel()); + table.onContextMenu = [this] (int row, juce::Point screenPos) + { + showRowContextMenu (row, screenPos); + }; - // 使用 JUCE 原生的扫描进度对话框,并配置同步扫描。 - // 说明:VST3 插件的实例化与总线信息查询(如 juce_VST3PluginFormat.cpp:301 - // 的 JUCE_ASSERT_MESSAGE_THREAD)必须在消息线程执行。将扫描线程数设为 0, - // PluginListComponent 会改为在消息线程上通过 Timer 轮询同步扫描;进度对话 - // 框仍会正常显示,并在每个插件扫描间隙刷新进度。 - pluginListComponent.setScanDialogText (TRANS ("Scanning for VST3 plugins"), - TRANS ("Please wait while the plugins are scanned.")); - pluginListComponent.setNumberOfThreadsForScanning (0); + // —— 工具栏 —— + optionsButton.setButtonText (TRANS ("Options")); + optionsButton.onClick = [this] { showOptionsMenu(); }; + addAndMakeVisible (optionsButton); rescanFailedPluginsButton.setButtonText (TRANS ("Rescan previously failed plugins")); - rescanFailedPluginsButton.setTooltip (TRANS ("When checked, plugins that crashed or failed in the last scan will be scanned again.")); - rescanFailedPluginsButton.onClick = [this] { onRescanFailedPluginsToggled(); }; + rescanFailedPluginsButton.setTooltip (TRANS ("When checked, plugins that crashed or failed in " + "the last scan will be scanned again.")); + rescanFailedPluginsButton.onClick = [this] + { + PluginRegistry::getInstance().setRescanFailedPlugins (rescanFailedPluginsButton.getToggleState()); + }; addAndMakeVisible (rescanFailedPluginsButton); - addAndMakeVisible (pluginListComponent); + cancelButton.setButtonText (TRANS ("Cancel")); + cancelButton.onClick = [this] { cancelScan(); }; + cancelButton.setVisible (false); + addAndMakeVisible (cancelButton); + filterLabel.setColour (juce::Label::textColourId, MixerLookAndFeel::getTextColour()); + filterLabel.setText (TRANS ("Filter:"), juce::dontSendNotification); + addAndMakeVisible (filterLabel); + + filterEditor.setTextToShowWhenEmpty (TRANS ("Search plugins..."), + MixerLookAndFeel::getTextColour().withAlpha (0.5f)); + filterEditor.onTextChange = [this] { refreshList(); }; + addAndMakeVisible (filterEditor); + + // —— 插件表格 —— + table.getHeader().setColour (juce::TableHeaderComponent::textColourId, MixerLookAndFeel::getTextColour()); + table.getHeader().setColour (juce::TableHeaderComponent::highlightColourId, MixerLookAndFeel::getAccentColour()); + + table.getHeader().addColumn (juce::String(), PluginManagerComponent::colEnabled, + 28, 24, 40, juce::TableHeaderComponent::notResizable); + table.getHeader().addColumn (TRANS ("Name"), PluginManagerComponent::colName, + 260, 120, 900, juce::TableHeaderComponent::defaultFlags); + table.getHeader().addColumn (TRANS ("Manufacturer"), PluginManagerComponent::colManufacturer, + 160, 80, 600, 0); + table.getHeader().addColumn (TRANS ("In/Out"), PluginManagerComponent::colChannels, + 80, 60, 200, juce::TableHeaderComponent::notResizable); + table.getHeader().setSortColumnId (PluginManagerComponent::colName, true); + + table.setModel (this); + table.setMultipleSelectionEnabled (true); + addAndMakeVisible (table); + + // —— 状态栏 —— scanStatusLabel.setFont (juce::Font (juce::FontOptions (12.0f))); scanStatusLabel.setColour (juce::Label::textColourId, MixerLookAndFeel::getTextColour()); scanStatusLabel.setJustificationType (juce::Justification::centredLeft); scanStatusLabel.setText (TRANS ("Ready"), juce::dontSendNotification); addAndMakeVisible (scanStatusLabel); - // 监听 KnownPluginList 变化,在扫描结束后展示扫描报告。 PluginRegistry::getInstance().getKnownPluginList().addChangeListener (this); - // 启动状态轮询定时器,用于在扫描期间更新 scanStatusLabel。 + refreshList(); startTimer (scanStatusTimerMs); - - setSize (600, 500); + setSize (760, 520); } //============================================================================== @@ -60,8 +287,6 @@ PluginManagerComponent::~PluginManagerComponent() { PluginRegistry::getInstance().getKnownPluginList().removeChangeListener (this); stopTimer(); - - // 如果用户勾选了复选框但未实际触发扫描,确保不遗留重试标志。 PluginRegistry::getInstance().setRescanFailedPlugins (false); } @@ -76,16 +301,146 @@ void PluginManagerComponent::resized() { auto bounds = getLocalBounds().reduced (8); - auto buttonHeight = 28; - auto statusHeight = 22; + auto toolbar = bounds.removeFromTop (28); + const int gap = 8; + + optionsButton.setBounds (toolbar.removeFromLeft (100)); + toolbar.removeFromLeft (gap); + cancelButton.setBounds (toolbar.removeFromLeft (80)); + toolbar.removeFromLeft (gap); + + auto rescanArea = toolbar.removeFromLeft (juce::jmin (220, toolbar.getWidth() / 2)); + rescanFailedPluginsButton.setBounds (rescanArea); + + toolbar.removeFromLeft (gap); + filterLabel.setBounds (toolbar.removeFromLeft (50)); + toolbar.removeFromLeft (4); + filterEditor.setBounds (toolbar); - rescanFailedPluginsButton.setBounds (bounds.removeFromTop (buttonHeight)); bounds.removeFromTop (8); - scanStatusLabel.setBounds (bounds.removeFromBottom (statusHeight)); + scanStatusLabel.setBounds (bounds.removeFromBottom (22)); bounds.removeFromBottom (4); - pluginListComponent.setBounds (bounds); + table.setBounds (bounds); +} + +//============================================================================== +int PluginManagerComponent::getNumRows() +{ + return cachedTypes.size(); +} + +//============================================================================== +void PluginManagerComponent::paintRowBackground (juce::Graphics& g, int rowNumber, int width, int height, + bool rowIsSelected) +{ + if (rowIsSelected) + g.fillAll (MixerLookAndFeel::getAccentColour().withAlpha (0.25f)); + else if (rowNumber % 2 == 1) + g.fillAll (MixerLookAndFeel::getBackgroundColour().brighter (0.04f)); +} + +//============================================================================== +void PluginManagerComponent::paintCell (juce::Graphics& g, int rowNumber, int columnId, + int width, int height, bool rowIsSelected) +{ + if (! juce::isPositiveAndBelow (rowNumber, cachedTypes.size())) + return; + + const auto& desc = cachedTypes.getReference (rowNumber); + const bool enabled = isPluginEnabled (rowNumber); + + g.setColour (enabled ? MixerLookAndFeel::getTextColour() + : MixerLookAndFeel::getTextColour().withAlpha (0.35f)); + g.setFont (juce::Font (juce::FontOptions (13.0f))); + + juce::String text; + + switch (columnId) + { + case PluginManagerComponent::colName: text = desc.name; break; + case PluginManagerComponent::colManufacturer: text = desc.manufacturerName; break; + case PluginManagerComponent::colChannels: text = juce::String (desc.numInputChannels) + + " -> " + + juce::String (desc.numOutputChannels); + break; + default: return; + } + + g.drawText (text, 4, 0, width - 8, height, + juce::Justification::centredLeft, true); +} + +//============================================================================== +void PluginManagerComponent::cellClicked (int rowNumber, int columnId, const juce::MouseEvent&) +{ + juce::ignoreUnused (rowNumber, columnId); +} + +//============================================================================== +juce::Component* PluginManagerComponent::refreshComponentForCell (int rowNumber, int columnId, + bool isRowSelected, + juce::Component* existingComponentToUpdate) +{ + if (columnId != PluginManagerComponent::colEnabled) + return nullptr; + + auto* toggle = dynamic_cast (existingComponentToUpdate); + + if (toggle == nullptr) + toggle = new juce::ToggleButton(); + + toggle->setToggleState (isPluginEnabled (rowNumber), juce::dontSendNotification); + toggle->setTooltip (TRANS ("Enable or disable this plugin")); + toggle->onClick = [this, rowNumber, toggle] + { + setPluginEnabled (rowNumber, toggle->getToggleState()); + }; + + return toggle; +} + +//============================================================================== +int PluginManagerComponent::getColumnAutoSizeWidth (int columnId) +{ + switch (columnId) + { + case PluginManagerComponent::colEnabled: return 28; + case PluginManagerComponent::colChannels: return 80; + case PluginManagerComponent::colManufacturer: return 160; + case PluginManagerComponent::colName: + default: + { + int widest = 120; + + for (const auto& d : cachedTypes) + { + const auto textWidth = juce::GlyphArrangement::getStringWidthInt ( + juce::Font (juce::FontOptions (13.0f)), d.name); + widest = juce::jmax (widest, textWidth + 48); + } + + return widest; + } + } +} + +//============================================================================== +void PluginManagerComponent::sortOrderChanged (int newSortColumnId, bool isForwards) +{ + currentSortColumn = newSortColumnId; + currentSortForwards = isForwards; + table.getHeader().setSortColumnId (newSortColumnId, isForwards); + + resortCachedTypes(); + table.updateContent(); +} + +//============================================================================== +void PluginManagerComponent::backgroundClicked (const juce::MouseEvent&) +{ + table.deselectAllRows(); } //============================================================================== @@ -94,60 +449,289 @@ void PluginManagerComponent::changeListenerCallback (juce::ChangeBroadcaster* so if (source != &PluginRegistry::getInstance().getKnownPluginList()) return; - // 每次列表变化都重置防抖计数器,扫描真正结束后再展示报告。 - scanReportDelayCounter = 5; + refreshList(); +} + +//============================================================================== +void PluginManagerComponent::refreshList() +{ + const auto all = PluginRegistry::getInstance().getKnownPluginList().getTypes(); + const auto filter = filterEditor.getText().trim().toLowerCase(); + + cachedTypes.clearQuick(); + + for (const auto& d : all) + { + if (filter.isNotEmpty() && ! d.name.toLowerCase().contains (filter)) + continue; + + cachedTypes.add (d); + } + + resortCachedTypes(); + table.updateContent(); +} + +//============================================================================== +void PluginManagerComponent::resortCachedTypes() +{ + if (cachedTypes.isEmpty()) + return; + + PluginSorter sorter { currentSortColumn, currentSortForwards }; + std::sort (cachedTypes.begin(), cachedTypes.end(), sorter); +} + +//============================================================================== +void PluginManagerComponent::showOptionsMenu() +{ + if (PluginRegistry::getInstance().isScanThreadRunning()) + return; + + juce::PopupMenu menu; + + menu.addItem (1, TRANS ("Edit scan directories...")); + menu.addItem (2, TRANS ("Scan")); + menu.addItem (3, TRANS ("Fully rescan")); + menu.addSeparator(); + + const bool anySelected = table.getSelectedRows().size() > 0; + const bool anyRows = cachedTypes.size() > 0; + + menu.addItem (4, TRANS ("Remove selected plug-ins"), anySelected); + menu.addItem (5, TRANS ("Remove all plug-ins"), anyRows); + menu.addSeparator(); + + bool applyPedal = true; + + if (auto* props = AppSettings::getInstance().getPropertiesFile()) + applyPedal = props->getBoolValue ("minixer_applyDeadMansPedal", true); + + menu.addItem (6, TRANS ("Apply dead-man's pedal"), true, applyPedal); + menu.addItem (7, TRANS ("Don't apply dead-man's pedal"), true, ! applyPedal); + + // 独立应用中 JUCE 关闭了模态循环,须使用异步菜单 API。 + menu.showMenuAsync (juce::PopupMenu::Options(), [this] (int chosen) + { + auto setPedal = [] (bool apply) + { + if (auto* props = AppSettings::getInstance().getPropertiesFile()) + props->setValue ("minixer_applyDeadMansPedal", apply); + }; + + switch (chosen) + { + case 1: showScanPathsEditor(); break; + case 2: PluginRegistry::getInstance().startAsyncScan (true, false); break; // 按已管理目录扫描 + case 3: startFullRescan(); break; + case 4: removeSelectedPlugins(); break; + case 5: removeAllPlugins(); break; + case 6: setPedal (true); break; + case 7: setPedal (false); break; + default: break; + } + }); +} + +//============================================================================== +void PluginManagerComponent::showScanPathsEditor() +{ + if (scanPathsWindow == nullptr) + { + auto* content = new ScanPathsEditorContent(); + + scanPathsWindow.reset (new ScanPathsEditorWindow (TRANS ("Scan directories"), + MixerLookAndFeel::getBackgroundColour(), + juce::DocumentWindow::closeButton)); + scanPathsWindow->setContentOwned (content, true); + scanPathsWindow->setUsingNativeTitleBar (true); + scanPathsWindow->setResizable (true, true); + scanPathsWindow->centreWithSize (content->getWidth(), content->getHeight()); + } + + scanPathsWindow->setVisible (true); + scanPathsWindow->toFront (true); +} + +//============================================================================== +void PluginManagerComponent::startFullRescan() +{ + PluginRegistry::getInstance().startAsyncScan (true, true); +} + +//============================================================================== +void PluginManagerComponent::cancelScan() +{ + PluginRegistry::getInstance().cancelAsyncScan(); +} + +//============================================================================== +void PluginManagerComponent::showRowContextMenu (int rowNumber, juce::Point screenPos) +{ + if (! juce::isPositiveAndBelow (rowNumber, cachedTypes.size())) + return; + + const bool enabled = isPluginEnabled (rowNumber); + + juce::PopupMenu menu; + menu.addItem (1, enabled ? TRANS ("Disable") : TRANS ("Enable")); + menu.addItem (2, TRANS ("Remove plug-in")); + menu.addItem (3, TRANS ("Show folder in file manager")); + + // 独立应用中 JUCE 关闭了模态循环,须使用异步菜单 API。 + menu.showMenuAsync (juce::PopupMenu::Options () + .withMinimumWidth (150) + .withTargetScreenArea (juce::Rectangle (screenPos, juce::Point (0, 0))), + [this, rowNumber, enabled] (int chosen) + { + if (! juce::isPositiveAndBelow (rowNumber, cachedTypes.size())) + return; + + if (chosen == 1) + { + setPluginEnabled (rowNumber, ! enabled); + } + else if (chosen == 2) + { + const auto id = cachedTypes.getReference (rowNumber).createIdentifierString(); + auto& known = PluginRegistry::getInstance().getKnownPluginList(); + + for (auto& d : known.getTypes()) + if (d.createIdentifierString() == id) + known.removeType (d); + + known.sendChangeMessage(); // 触发 refreshList + PluginRegistry::getInstance().saveList(); + } + else if (chosen == 3) + { + juce::File (cachedTypes.getReference (rowNumber).fileOrIdentifier) + .getParentDirectory() + .startAsProcess(); + } + }); +} + +//============================================================================== +void PluginManagerComponent::removeSelectedPlugins() +{ + auto& known = PluginRegistry::getInstance().getKnownPluginList(); + juce::StringArray ids; + + const auto selectedRows = table.getSelectedRows(); + + for (int i = 0; i < selectedRows.size(); ++i) + { + const int sel = selectedRows[i]; + + if (juce::isPositiveAndBelow (sel, cachedTypes.size())) + ids.add (cachedTypes.getReference (sel).createIdentifierString()); + } + + if (ids.isEmpty()) + return; + + for (auto& d : known.getTypes()) + { + if (ids.contains (d.createIdentifierString())) + known.removeType (d); + } + + known.sendChangeMessage(); + PluginRegistry::getInstance().saveList(); +} + +//============================================================================== +void PluginManagerComponent::removeAllPlugins() +{ + auto& known = PluginRegistry::getInstance().getKnownPluginList(); + known.clear(); + known.sendChangeMessage(); + PluginRegistry::getInstance().saveList(); +} + +//============================================================================== +bool PluginManagerComponent::isPluginEnabled (int rowNumber) const +{ + if (! juce::isPositiveAndBelow (rowNumber, cachedTypes.size())) + return true; + + auto* props = AppSettings::getInstance().getPropertiesFile(); + + if (props == nullptr) + return true; + + return props->getBoolValue ("minixer_pluginEnabled_" + + cachedTypes.getReference (rowNumber).createIdentifierString(), true); +} + +//============================================================================== +void PluginManagerComponent::setPluginEnabled (int rowNumber, bool enabled) +{ + if (! juce::isPositiveAndBelow (rowNumber, cachedTypes.size())) + return; + + auto* props = AppSettings::getInstance().getPropertiesFile(); + + if (props == nullptr) + return; + + props->setValue ("minixer_pluginEnabled_" + + cachedTypes.getReference (rowNumber).createIdentifierString(), enabled); + table.repaint(); } //============================================================================== void PluginManagerComponent::timerCallback() { - auto& registry = PluginRegistry::getInstance(); + auto& reg = PluginRegistry::getInstance(); - // 更新扫描状态标签:PluginListComponent 已创建 Scanner 但 PluginRegistry - // 尚未开始记录单个文件时,说明正处于 JUCE 的目录枚举阶段。 - if (pluginListComponent.isScanning()) + // 在消息线程把后台扫描结果应用到 KnownPluginList / 元数据 / 报告。 + reg.pumpScanResults(); + + const bool scanning = reg.isScanThreadRunning() || reg.isScanInProgress(); + + if (scanning) { - if (registry.isScanInProgress()) - { - auto currentFile = registry.getCurrentScanningFile(); + const int total = reg.getScanProgressTotal(); + const int done = reg.getScanProgressCompleted(); + const auto detail = reg.getScanProgressDetail(); - if (currentFile.isNotEmpty()) - { - scanStatusLabel.setText (TRANS ("Scanning: ") + juce::File (currentFile).getFileName(), - juce::dontSendNotification); - } - else - { - scanStatusLabel.setText (TRANS ("Scanning plugins"), - juce::dontSendNotification); - } - } - else - { - scanStatusLabel.setText (TRANS ("Enumerating plugin directories"), - juce::dontSendNotification); - } + juce::String text = TRANS ("Scanning"); + + if (total > 0) + text << " " << done << "/" << total; + + if (detail.isNotEmpty()) + text << ": " << detail; + + scanStatusLabel.setText (text, juce::dontSendNotification); + cancelButton.setVisible (true); } else { + cancelButton.setVisible (false); scanStatusLabel.setText (TRANS ("Ready"), juce::dontSendNotification); } - // 扫描报告防抖:每次 KnownPluginList 变化时计数器重置为 5(约 500ms)。 - // 计数器归零且扫描真正空闲时,弹出扫描报告。 + optionsButton.setEnabled (! scanning); + rescanFailedPluginsButton.setEnabled (! scanning); + filterEditor.setEnabled (! scanning); + + // 扫描刚结束时,等待短暂时间确保结果已应用,再弹出报告。 + if (wasScanning && ! reg.isScanInProgress()) + scanReportDelayCounter = 5; + + wasScanning = reg.isScanInProgress(); + if (scanReportDelayCounter > 0) { --scanReportDelayCounter; if (scanReportDelayCounter == 0) { - registry.checkAndFinishIdleScan(); - - if (! registry.isScanInProgress() && registry.getLastScanReport().hasUnshownReport) - { - rescanFailedPluginsButton.setToggleState (false, juce::dontSendNotification); + if (! reg.isScanInProgress() && reg.getLastScanReport().hasUnshownReport) showScanReportIfNeeded(); - } } } } @@ -206,6 +790,7 @@ void PluginManagerComponent::showScanReportIfNeeded() return; PluginRegistry::getInstance().markLastScanReportAsShown(); + rescanFailedPluginsButton.setToggleState (false, juce::dontSendNotification); juce::AlertWindow::showMessageBoxAsync (juce::AlertWindow::InfoIcon, TRANS ("Plugin Scan Report"), @@ -213,10 +798,4 @@ void PluginManagerComponent::showScanReportIfNeeded() TRANS ("OK")); } -//============================================================================== -void PluginManagerComponent::onRescanFailedPluginsToggled() -{ - PluginRegistry::getInstance().setRescanFailedPlugins (rescanFailedPluginsButton.getToggleState()); -} - -} // namespace minixer +} // namespace minixer \ No newline at end of file diff --git a/Source/Plugin/PluginManagerComponent.h b/Source/Plugin/PluginManagerComponent.h index 1418a72..37a461c 100644 --- a/Source/Plugin/PluginManagerComponent.h +++ b/Source/Plugin/PluginManagerComponent.h @@ -2,15 +2,16 @@ ============================================================================== PluginManagerComponent.h - 插件扫描与管理界面(基于 JUCE PluginListComponent)。 + 插件扫描与管理界面(自建 UI,替代 JUCE 原生 PluginListComponent)。 - 界面完全复用 JUCE 原生的 PluginListComponent: - - 列表展示、启用/禁用、移除已扫描插件; - - 通过 Options 菜单的 “scan for new or updated VST3 plug-ins” 选择目录并扫描。 - - 扫描配置为同步消息线程(threads == 0):VST3 插件的实例化与总线信息 - 查询必须在消息线程执行。JUCE 原生的进度对话框仍会显示,并在每个插件 - 扫描间隙刷新进度。 + 原有的 JUCE PluginListComponent 会在消息线程上同步扫描,导致扫描期间 + 整个软件界面卡死。本自建组件改为: + - 前端完全自建:插件表格(启用/名称/厂商/通道)、筛选、表头排序、 + 行右键菜单、Options 菜单、扫描状态与扫描报告。 + - 扫描由 PluginRegistry::startAsyncScan 驱动的“专用后台线程 + 逐文件 + PluginHost 子进程”完成;本组件仅通过 100ms 定时器调用 + PluginRegistry::pumpScanResults() 把结果应用到 KnownPluginList 并刷新, + 从而彻底不阻塞消息线程。 ============================================================================== */ @@ -20,11 +21,40 @@ #include #include "PluginRegistry.h" +#include + namespace minixer { +//============================================================================== +/** 支持行右键弹出菜单的插件表格(在 TableListBox 之上拦截鼠标右键)。 */ +class PluginContextMenuTable final : public juce::TableListBox +{ +public: + using juce::TableListBox::TableListBox; + + /** (右键所在行号, 屏幕坐标) 回调;点击非行空白时不会调用。 */ + std::function)> onContextMenu; + +private: + void mouseDown (const juce::MouseEvent& e) override + { + juce::TableListBox::mouseDown (e); + + if (e.mods.isPopupMenu()) + { + const int row = getRowContainingPosition (e.getPosition().getX(), + e.getPosition().getY()); + + if (row >= 0 && onContextMenu != nullptr) + onContextMenu (row, e.getScreenPosition()); + } + } +}; + //============================================================================== class PluginManagerComponent : public juce::Component, + public juce::TableListBoxModel, private juce::ChangeListener, private juce::Timer { @@ -37,24 +67,84 @@ public: void paint (juce::Graphics& g) override; void resized() override; + //============================================================================== + // 表格列 ID(公开,供排序比较器引用) + enum ColumnIds + { + colEnabled = 1, /**< 启用复选框 */ + colName = 2, /**< 插件名称 */ + colManufacturer = 3, /**< 厂商 */ + colChannels = 4 /**< 输入/输出通道 */ + }; + + //============================================================================== + // TableListBoxModel + int getNumRows() override; + void paintRowBackground (juce::Graphics&, int rowNumber, int width, int height, + bool rowIsSelected) override; + void paintCell (juce::Graphics&, int rowNumber, int columnId, int width, int height, + bool rowIsSelected) override; + void cellClicked (int rowNumber, int columnId, const juce::MouseEvent&) override; + juce::Component* refreshComponentForCell (int rowNumber, int columnId, + bool isRowSelected, + juce::Component* existingComponentToUpdate) override; + int getColumnAutoSizeWidth (int columnId) override; + void sortOrderChanged (int newSortColumnId, bool isForwards) override; + void backgroundClicked (const juce::MouseEvent&) override; + private: //============================================================================== void changeListenerCallback (juce::ChangeBroadcaster* source) override; void timerCallback() override; - /** 将最近一次扫描报告格式化为可读的报告文本。 */ + //============================================================================== + void showOptionsMenu(); + void startFullRescan(); + void cancelScan(); + void showScanPathsEditor(); + void showRowContextMenu (int rowNumber, juce::Point screenPos); + void removeSelectedPlugins(); + void removeAllPlugins(); + + bool isPluginEnabled (int rowNumber) const; + void setPluginEnabled (int rowNumber, bool enabled); + + /** 依据 KnownPluginList 重建缓存列表并刷新表格(消息线程)。 */ + void refreshList(); + + /** 依据当前表头排序设置,对 cachedTypes 重新排序。 */ + void resortCachedTypes(); + + /** 将最近一次扫描报告格式化为可读文本。 */ static juce::String formatScanReport (const PluginScanReport& report); - /** 展示最近一次扫描报告(如果有未展示的报告)。 */ + /** 展示最近一次扫描报告(若有尚未展示的报告)。 */ void showScanReportIfNeeded(); - /** 当“重新扫描上次出错的插件”复选框状态变化时调用。 */ - void onRescanFailedPluginsToggled(); + //============================================================================== + // 工具栏与状态组件 //============================================================================== - juce::ToggleButton rescanFailedPluginsButton; - juce::PluginListComponent pluginListComponent; - juce::Label scanStatusLabel; + juce::TextButton optionsButton; + juce::ToggleButton rescanFailedPluginsButton; + juce::TextButton cancelButton; + juce::Label filterLabel; + juce::TextEditor filterEditor; + PluginContextMenuTable table; + juce::Label scanStatusLabel; + + /** 扫描目录编辑窗口(复用,仅隐藏不销毁)。 */ + std::unique_ptr scanPathsWindow; + + /** KnownPluginList 的快照副本(消息线程维护,表格模型只读它)。 */ + juce::Array cachedTypes; + + /** 表头排序状态(refreshList / resortCachedTypes 共用)。 */ + int currentSortColumn = ColumnIds::colName; + bool currentSortForwards = true; + + /** 是否在扫描中(用于捕获"刚结束"这一边沿以弹出报告)。 */ + bool wasScanning = false; /** 扫描报告防抖计数器(以 timer tick 为单位,5 ticks × 100ms = 500ms)。 */ int scanReportDelayCounter = 0; @@ -65,4 +155,4 @@ private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginManagerComponent) }; -} // namespace minixer +} // namespace minixer \ No newline at end of file diff --git a/Source/Plugin/PluginRegistry.cpp b/Source/Plugin/PluginRegistry.cpp index d5e4be5..b26d80d 100644 --- a/Source/Plugin/PluginRegistry.cpp +++ b/Source/Plugin/PluginRegistry.cpp @@ -200,7 +200,8 @@ static void scanFileWithCustomScanner (const juce::File& file, */ static bool scanPluginViaHost (const juce::String& fileOrIdentifier, PluginArchitecture arch, - juce::OwnedArray& result) + juce::OwnedArray& result, + const std::atomic* cancelled = nullptr) { #if ! JUCE_WINDOWS juce::ignoreUnused (fileOrIdentifier, arch, result); @@ -236,6 +237,9 @@ static bool scanPluginViaHost (const juce::String& fileOrIdentifier, // 扫描应在 30 秒内完成 for (int attempt = 0; attempt < 300; ++attempt) { + if (cancelled != nullptr && cancelled->load (std::memory_order_relaxed)) + break; // 用户取消扫描 + if (transport->readMessage (frame, 100)) { gotResult = true; @@ -657,6 +661,189 @@ private: PluginRegistry& registry; }; +//============================================================================== +// —— 异步扫描:后台线程 + PluginHost 子进程逐文件扫描 —— +// +// 线程安全模型: +// - 后台线程(ScanWorkerThread)只做三件事:目录枚举、逐文件通过 PluginHost +// 子进程(或进程内兜底)扫描、把每个文件的结果压入 pendingResults 队列。 +// 它不直接触碰 KnownPluginList / 扫描报告。 +// - 消息线程定期调用 pumpScanResults(),从队列取出结果,在消息线程上更新 +// KnownPluginList、增量元数据与扫描报告,从而避免与被扫描插件执行相关的 +// JUCE 消息线程断言,也避免整个软件在扫描期间卡死。 +// - 进度(total / completed / detail)由 worker 写、UI 定时读取,用 progressLock 保护。 + +//============================================================================== +struct PluginRegistry::ScanFileResult +{ + enum class Type + { + Success, // 扫描成功,descriptions 有效 + Skipped, // 增量未变化,消息线程从已知列表复用描述 + Failed, // 扫描失败,errorMessage 有效 + Blacklisted // 因黑名单跳过(未勾选重试) + }; + + Type type = Type::Failed; + juce::String filePath; + juce::String errorMessage; + juce::OwnedArray descriptions; +}; + +//============================================================================== +class PluginRegistry::ScanWorkerThread final : public juce::Thread +{ +public: + ScanWorkerThread (PluginRegistry& owner, + const juce::FileSearchPath& paths, + bool recursive, + bool forceRescan) + : juce::Thread ("PluginScanThread"), + registry (owner), + extraPaths (paths), + recursiveMode (recursive), + forceRescanMode (forceRescan) {} + + std::atomic cancelled { false }; + + void run() override + { + // —— 枚举所有待扫描 .vst3(文件系统遍历,可能较慢,放在后台线程)—— + // extraPaths 已包含“内置默认目录 + 用户自定义目录”(在消息线程解析)。 + juce::StringArray files; + + for (int i = 0; i < extraPaths.getNumPaths(); ++i) + { + const juce::File dir (extraPaths[i]); + + if (! dir.isDirectory()) + continue; + + for (const auto& f : vst3scan::VST3Scanner::findVST3Files (dir, recursiveMode)) + { + const auto lib = vst3scan::VST3Scanner::resolveLibraryFile (f); + + if (lib.existsAsFile()) + files.addIfNotAlreadyThere (lib.getFullPathName()); + } + } + + { + juce::ScopedLock lock (registry.progressLock); + registry.progressTotal = files.size(); + registry.progressCompleted = 0; + } + + for (const auto& file : files) + { + if (threadShouldExit() || cancelled.load (std::memory_order_relaxed)) + break; + + scanSingleFile (file); + } + + registry.scanThreadComplete = true; + juce::Logger::writeToLog ("Plugin scan worker finished"); + } + +private: + void scanSingleFile (const juce::String& file) + { + registry.setScanProgressDetail (juce::File (file).getFileName()); + + auto result = std::make_unique(); + result->filePath = file; + + auto done = [&] + { + registry.pushScanResult (std::move (result)); + }; + + const juce::File lib (file); + + // OS / 解压残留(__MACOSX / ._* 等):直接忽略,不计入报告。 + if (vst3scan::VST3Scanner::isOsResidueFile (lib)) + { + registry.onScanFileProgressed(); + return; + } + + // bundle 目录无法解析出可加载 DLL。 + if (! lib.existsAsFile()) + { + result->type = PluginRegistry::ScanFileResult::Type::Failed; + result->errorMessage = TRANS ("No loadable .vst3 library found in bundle"); + done(); + return; + } + + // 黑名单跳过(除非本次为强制全量重扫)。 + if (! forceRescanMode && PluginBlacklist::getInstance().isBlacklisted (lib.getFullPathName())) + { + result->type = PluginRegistry::ScanFileResult::Type::Blacklisted; + done(); + return; + } + + // 增量跳过:文件未变化且上次成功 → 消息线程从已知列表复用描述。 + if (! forceRescanMode) + { + std::lock_guard metaLock (registry.metadataMutex); + + if (registry.shouldSkipFile (lib)) + { + result->type = PluginRegistry::ScanFileResult::Type::Skipped; + done(); + return; + } + } + + // 扫描:优先 PluginHost 子进程(进程隔离 + 按完整 CID 枚举,杜绝外壳错位); + // 子进程不可用(exe 缺失 / 崩溃 / 非 Windows)时回退进程内自主扫描器。 + const auto arch = detectPluginArchitecture (lib); + bool ok = false; + juce::String error; + + #if JUCE_WINDOWS + if (arch != PluginArchitecture::unknown + && PluginHostLauncher::getHostExecutableForArchitecture (arch).existsAsFile()) + { + ok = scanPluginViaHost (file, arch, result->descriptions, &cancelled); + + if (ok && result->descriptions.isEmpty()) + ok = false; + } + #else + juce::ignoreUnused (arch); + #endif + + if (! ok) + { + // 进程内兜底:自定义扫描器(先 setHostContext 再按 CID 枚举)。 + scanFileWithCustomScanner (lib, result->descriptions, error); + ok = ! result->descriptions.isEmpty(); + } + + if (ok) + { + result->type = PluginRegistry::ScanFileResult::Type::Success; + } + else + { + result->type = PluginRegistry::ScanFileResult::Type::Failed; + result->errorMessage = error.isNotEmpty() ? error + : TRANS ("No plugin descriptions found"); + } + + done(); + } + + PluginRegistry& registry; + juce::FileSearchPath extraPaths; + bool recursiveMode; + bool forceRescanMode; +}; + //============================================================================== PluginRegistry& PluginRegistry::getInstance() { @@ -673,6 +860,217 @@ PluginRegistry::PluginRegistry() formatManager.addDefaultFormats(); knownList.setCustomScanner (std::make_unique (*this)); loadList(); + loadCustomScanPaths(); +} + +//============================================================================== +// 定义在 .cpp 中,以便在 ScanWorkerThread 完整定义之后实例化其析构。 +PluginRegistry::~PluginRegistry() +{ + if (scanWorker != nullptr) + { + scanWorker->signalThreadShouldExit(); + scanWorker->stopThread (2000); + } +} + +//============================================================================== +void PluginRegistry::setScanProgressDetail (const juce::String& detail) +{ + juce::ScopedLock lock (progressLock); + progressDetail = detail; + currentScanningFile = juce::File (detail).getFullPathName(); +} + +//============================================================================== +void PluginRegistry::pushScanResult (std::unique_ptr result) +{ + { + std::lock_guard lock (resultQueueMutex); + pendingResults.emplace_back (std::move (result)); + } + + { + juce::ScopedLock plock (progressLock); + ++progressCompleted; + } +} + +//============================================================================== +void PluginRegistry::onScanFileProgressed() +{ + juce::ScopedLock plock (progressLock); + ++progressCompleted; +} + +//============================================================================== +void PluginRegistry::startAsyncScan (bool recursive, bool forceRescan) +{ + if (scanWorker != nullptr && scanWorker->isThreadRunning()) + { + juce::Logger::writeToLog ("Async scan already running; ignoring start request."); + return; + } + + // 消息线程:开启报告,预记录当前已知标识符以区分新增/更新。 + beginScanReport(); + + scanThreadComplete = false; + + { + juce::ScopedLock plock (progressLock); + progressTotal = 0; + progressCompleted = 0; + progressDetail = TRANS ("Enumerating plugin directories"); + currentScanningFile.clear(); + } + + // 在消息线程解析本次要扫描的目录集合(默认目录 + 自定义目录),避免后台线程 + // 与消息线程在读取 customScanPaths 上产生数据竞争。 + const juce::FileSearchPath pathsToScan = getScanSearchPaths(); + + scanWorker = std::make_unique (*this, pathsToScan, recursive, forceRescan); + scanWorker->startThread(); + juce::Logger::writeToLog ("Async plugin scan started"); +} + +//============================================================================== +void PluginRegistry::cancelAsyncScan() +{ + if (scanWorker == nullptr) + return; + + scanWorker->cancelled.store (true, std::memory_order_relaxed); + scanWorker->signalThreadShouldExit(); +} + +//============================================================================== +bool PluginRegistry::isScanThreadRunning() const noexcept +{ + return scanWorker != nullptr && scanWorker->isThreadRunning(); +} + +//============================================================================== +void PluginRegistry::pumpScanResults() +{ + std::deque> batch; + + { + std::lock_guard lock (resultQueueMutex); + + if (pendingResults.empty() && ! scanThreadComplete) + return; // 仍在扫描且暂无新结果 + + batch.swap (pendingResults); + } + + for (auto& r : batch) + applyScannedFile (*r); + + // 全部结果已应用且后台线程已结束 → 结束扫描报告。 + if (scanThreadComplete && scanInProgress) + { + finishScanReport(); + + { + juce::ScopedLock plock (progressLock); + progressDetail = TRANS ("Ready"); + } + } +} + +//============================================================================== +void PluginRegistry::applyScannedFile (const ScanFileResult& result) +{ + ++lastReport.totalFiles; + + const juce::File file (result.filePath); + + switch (result.type) + { + case ScanFileResult::Type::Skipped: + { + // 复用已知列表中的描述,记录为“未变化而跳过”。 + juce::OwnedArray existing; + + for (auto& d : knownList.getTypes()) + if (d.fileOrIdentifier == result.filePath) + existing.add (std::make_unique (d)); + + { + std::lock_guard metaLock (metadataMutex); + updateScanMetadataForFile (file, true, existing, {}); + } + + recordScanSuccess (file, existing, true); + break; + } + + case ScanFileResult::Type::Blacklisted: + recordScanBlacklisted (file); + break; + + case ScanFileResult::Type::Failed: + recordScanFailure (file, result.errorMessage); + { + juce::OwnedArray none; + std::lock_guard metaLock (metadataMutex); + updateScanMetadataForFile (file, false, none, result.errorMessage); + } + break; + + case ScanFileResult::Type::Success: + default: + { + { + std::lock_guard metaLock (metadataMutex); + updateScanMetadataForFile (file, true, result.descriptions, {}); + } + + recordScanSuccess (file, result.descriptions, false); + commitDescriptionsForFile (result.filePath, result.descriptions); + break; + } + } +} + +//============================================================================== +void PluginRegistry::commitDescriptionsForFile (const juce::String& file, + const juce::OwnedArray& descriptions) +{ + // 先移除该文件原有的已知条目(避免重复),再写入最新描述。 + for (auto& d : knownList.getTypes()) + { + if (d.fileOrIdentifier == file) + knownList.removeType (d); + } + + for (auto* d : descriptions) + if (d != nullptr) + knownList.addType (*d); + + knownList.sendChangeMessage(); +} + +//============================================================================== +int PluginRegistry::getScanProgressTotal() const noexcept +{ + juce::ScopedLock plock (progressLock); + return progressTotal; +} + +//============================================================================== +int PluginRegistry::getScanProgressCompleted() const noexcept +{ + juce::ScopedLock plock (progressLock); + return progressCompleted; +} + +//============================================================================== +juce::String PluginRegistry::getScanProgressDetail() const +{ + juce::ScopedLock plock (progressLock); + return progressDetail; } //============================================================================== @@ -1006,102 +1404,96 @@ juce::FileSearchPath PluginRegistry::getVST3DefaultSearchPath() const } //============================================================================== -void PluginRegistry::scanForVST3 (bool recursive) +juce::FileSearchPath PluginRegistry::getScanSearchPaths() const { - scanForVST3 (getVST3DefaultSearchPath(), recursive); -} + juce::FileSearchPath paths (getVST3DefaultSearchPath()); -//============================================================================== -void PluginRegistry::scanForVST3 (const juce::FileSearchPath& extraPaths, bool recursive) -{ - scanForVST3Internal (extraPaths, recursive, false); -} - -//============================================================================== -void PluginRegistry::rescanForVST3 (bool recursive) -{ - rescanForVST3 (getVST3DefaultSearchPath(), recursive); -} - -//============================================================================== -void PluginRegistry::rescanForVST3 (const juce::FileSearchPath& extraPaths, bool recursive) -{ - scanForVST3Internal (extraPaths, recursive, true); -} - -//============================================================================== -void PluginRegistry::scanForVST3Internal (const juce::FileSearchPath& extraPaths, - bool recursive, - bool forceRescan) -{ - juce::AudioPluginFormat* vst3Format = nullptr; - - for (int i = 0; i < formatManager.getNumFormats(); ++i) + for (int i = 0; i < customScanPaths.getNumPaths(); ++i) { - auto* format = formatManager.getFormat (i); + const juce::File dir = customScanPaths[i]; + const juce::String p = dir.getFullPathName(); - if (format != nullptr && format->getName() == juce::VST3PluginFormat::getFormatName()) + bool already = false; + + for (int j = 0; j < paths.getNumPaths(); ++j) + if (paths[j].getFullPathName() == p) { already = true; break; } + + if (! already) + paths.add (dir); + } + + return paths; +} + +//============================================================================== +juce::FileSearchPath PluginRegistry::getCustomScanPaths() const +{ + return customScanPaths; +} + +//============================================================================== +void PluginRegistry::addScanPath (const juce::File& dir) +{ + if (! dir.isDirectory()) + return; + + const juce::String path = dir.getFullPathName(); + + for (int i = 0; i < customScanPaths.getNumPaths(); ++i) + if (customScanPaths[i].getFullPathName() == path) + return; // 已存在,避免重复 + + customScanPaths.add (dir); + saveCustomScanPaths(); +} + +//============================================================================== +void PluginRegistry::removeScanPath (const juce::File& dir) +{ + const juce::String path = dir.getFullPathName(); + + for (int i = 0; i < customScanPaths.getNumPaths(); ++i) + { + if (customScanPaths[i].getFullPathName() == path) { - vst3Format = format; + customScanPaths.remove (i); break; } } - if (vst3Format == nullptr) - return; + saveCustomScanPaths(); +} - beginScanReport(); +//============================================================================== +void PluginRegistry::setCustomScanPaths (const juce::FileSearchPath& paths) +{ + customScanPaths = juce::FileSearchPath(); - // 合并默认路径与用户指定的额外路径,保持原有顺序追加。 - juce::FileSearchPath pathsToScan (getVST3DefaultSearchPath()); - - for (int i = 0; i < extraPaths.getNumPaths(); ++i) - pathsToScan.add (extraPaths[i]); - - // 自主枚举 .vst3(普通文件 + bundle 目录):主动过滤其他系统/解压残留 - // (__MACOSX、AppleDouble ._* 等),并把 bundle 目录解析为实际 DLL, - // 替代 JUCE VST3PluginFormat::searchPathsForPlugins(其不做过滤)。 - juce::StringArray files; - - for (int i = 0; i < pathsToScan.getNumPaths(); ++i) + for (int i = 0; i < paths.getNumPaths(); ++i) { - const juce::File dir (pathsToScan[i]); + const juce::File dir = paths[i]; - if (! dir.isDirectory()) - continue; - - for (const auto& f : vst3scan::VST3Scanner::findVST3Files (dir, recursive)) - { - const auto lib = vst3scan::VST3Scanner::resolveLibraryFile (f); - - if (lib.existsAsFile()) - files.addIfNotAlreadyThere (lib.getFullPathName()); - } + if (dir.isDirectory()) + customScanPaths.add (dir); } - for (auto& file : files) - { - if (forceRescan) - { - // 强制重新扫描:清除该文件的元数据成功标志,使其不会被跳过。 - if (metadataStore != nullptr) - { - ScanMetadataStore::Entry cleared; - cleared.filePath = file; - cleared.lastScanSuccess = false; - metadataStore->updateEntry (cleared); - } - } + saveCustomScanPaths(); +} - juce::OwnedArray typesFound; - knownList.scanAndAddFile (file, true, typesFound, *vst3Format); - } +//============================================================================== +void PluginRegistry::loadCustomScanPaths() +{ + customScanPaths = juce::FileSearchPath(); - knownList.scanFinished(); - finishScanReport(); + if (auto* props = AppSettings::getInstance().getPropertiesFile()) + customScanPaths = juce::FileSearchPath (props->getValue ("customVst3ScanPaths")); +} - // 本次扫描的重试标志用完即重置,避免影响后续扫描。 - rescanFailedPlugins = false; +//============================================================================== +void PluginRegistry::saveCustomScanPaths() const +{ + if (auto* props = AppSettings::getInstance().getPropertiesFile()) + props->setValue ("customVst3ScanPaths", customScanPaths.toString()); } //============================================================================== diff --git a/Source/Plugin/PluginRegistry.h b/Source/Plugin/PluginRegistry.h index e169a0e..d41a298 100644 --- a/Source/Plugin/PluginRegistry.h +++ b/Source/Plugin/PluginRegistry.h @@ -12,6 +12,11 @@ #include #include "PluginSlotState.h" +#include +#include +#include +#include + namespace minixer { @@ -71,22 +76,32 @@ public: void saveList() const; //============================================================================== - /** 扫描 VST3 默认位置与指定路径。 + /** 异步扫描 VST3(插件管理器 UI 专用入口)。 - 注意:该函数必须在 JUCE 消息线程调用,因为 VST3 插件的实例化与总线 - 信息查询要求消息线程(参见 juce_VST3PluginFormat.cpp 中的 - JUCE_ASSERT_MESSAGE_THREAD)。它在当前线程同步执行,会阻塞调用者直到 - 扫描完成。如需 UI 反馈与取消功能,请使用 PluginManagerComponent。 */ - void scanForVST3 (const juce::FileSearchPath& extraPaths, bool recursive = true); + 在专用后台线程上进行目录枚举,并对每个 .vst3 文件启动 PluginHost 子进程 + (优先)或进程内扫描兜底,结果进入内部队列;调用方必须定期(如 100ms + Timer)调用 pumpScanResults() 把结果应用到 KnownPluginList / 增量元数据 / + 扫描报告,并返回 UI 反馈。该入口不阻塞消息线程,避免扫描期间整个软件卡死。 - /** 扫描 VST3 默认位置。 */ - void scanForVST3 (bool recursive = true); + 扫描目录取 getScanSearchPaths()(内置默认目录 + 用户自定义目录)。 + */ + void startAsyncScan (bool recursive, bool forceRescan = false); - /** 强制重新扫描 VST3 默认位置与指定路径(忽略增量扫描缓存)。 */ - void rescanForVST3 (const juce::FileSearchPath& extraPaths, bool recursive = true); + /** 取消正在进行的异步扫描。在结果队列被清空且线程退出后立即结束扫描报告。 */ + void cancelAsyncScan(); - /** 强制重新扫描 VST3 默认位置。 */ - void rescanForVST3 (bool recursive = true); + /** 返回后台扫描线程是否仍在运行。 */ + bool isScanThreadRunning() const noexcept; + + /** 消息线程应定期调用(100ms 建议):把后台扫描结果队列应用到 + KnownPluginList / 元数据 / 报告,并在全部完成后结束扫描报告。 */ + void pumpScanResults(); + + //============================================================================== + /** 扫描进度(线程安全,供 UI 定时器读取)。 */ + int getScanProgressTotal() const noexcept; + int getScanProgressCompleted() const noexcept; + juce::String getScanProgressDetail() const; /**< 当前正在扫描的文件名或阶段文本。 */ //============================================================================== /** 设置下次扫描时是否重新扫描黑名单中“上次出错的插件”。 @@ -104,6 +119,22 @@ public: /** 返回 VST3 格式的默认扫描路径。 */ juce::FileSearchPath getVST3DefaultSearchPath() const; + //============================================================================== + /** 返回全部扫描目录 = 内置默认目录 + 用户自定义目录(去重)。 */ + juce::FileSearchPath getScanSearchPaths() const; + + /** 返回用户自定义的扫描目录(不含内置默认目录)。 */ + juce::FileSearchPath getCustomScanPaths() const; + + /** 新增一个用户自定义扫描目录。 */ + void addScanPath (const juce::File& dir); + + /** 移除一个用户自定义扫描目录。 */ + void removeScanPath (const juce::File& dir); + + /** 用一组新目录替换全部用户自定义扫描目录。 */ + void setCustomScanPaths (const juce::FileSearchPath& paths); + //============================================================================== /** 返回最近一次扫描报告。 */ PluginScanReport getLastScanReport() const; @@ -123,10 +154,7 @@ public: private: //============================================================================== PluginRegistry(); - ~PluginRegistry() = default; - - //============================================================================== - void scanForVST3Internal (const juce::FileSearchPath& extraPaths, bool recursive, bool forceRescan); + ~PluginRegistry(); // 定义在 .cpp(scanWorker 为不完整类型,需在完整定义后实例化) //============================================================================== /** 自定义扫描器:在真正加载 VST3 之前读取 PE 头,跳过与当前进程架构不匹配的插件, @@ -138,6 +166,41 @@ private: /** 增量扫描元数据。 */ class ScanMetadataStore; + //============================================================================== + /** 一个文件的异步扫描结果(后台线程产生 → 消息线程应用)。 */ + struct ScanFileResult; + /** 后台扫描线程(PIMPL,定义在 .cpp)。 */ + class ScanWorkerThread; + + //============================================================================== + // —— 异步扫描:进度(worker 写 / UI 定时读,由 progressLock 保护)—— + mutable juce::CriticalSection progressLock; + int progressTotal = 0; + int progressCompleted = 0; + juce::String progressDetail = "Ready"; + + // —— 异步扫描:结果队列(worker 产生、消息线程 pump 消费)—— + std::mutex resultQueueMutex; + std::deque> pendingResults; + std::unique_ptr scanWorker; + std::atomic scanThreadComplete { false }; + + // —— 增量元数据在后台线程(读取 skip 判定)与消息线程(写入结果)间共享 —— + std::mutex metadataMutex; + + // —— 用户自定义扫描目录(持久化于 PropertiesFile,仅消息线程访问)—— + juce::FileSearchPath customScanPaths; + void loadCustomScanPaths(); + void saveCustomScanPaths() const; + + //============================================================================== + void pushScanResult (std::unique_ptr result); + void onScanFileProgressed(); /**< 不产生结果时仍推进进度(残留文件)。 */ + void applyScannedFile (const ScanFileResult& result); + void commitDescriptionsForFile (const juce::String& file, + const juce::OwnedArray& descriptions); + void setScanProgressDetail (const juce::String& detail); + //============================================================================== juce::File getScanMetadataFile() const; void loadScanMetadata();