diff --git a/CMakeLists.txt b/CMakeLists.txt index b1aaf269..d470787d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -793,6 +793,16 @@ set(OPENTUNE_COMMON_SOURCES Source/Utils/NoteGeneratorTypes.h Source/Utils/PianoKeyAudition.cpp Source/Utils/PianoKeyAudition.h + Source/Utils/NoteAudition.cpp + Source/Utils/NoteAudition.h + Source/Utils/NoteSpeech.h + Source/Utils/ScreenReaderAnnouncer.cpp + Source/Utils/ScreenReaderAnnouncer.h + Source/Utils/AccessibleComboBox.h + Source/Utils/AccessibleKnob.h + Source/Utils/AccessibleToggleButton.h + Source/Utils/ContextMenuKey.cpp + Source/Utils/ContextMenuKey.h Source/Utils/AppLogger.cpp Source/Utils/AppLogger.h Source/Utils/ExternalEditSession.cpp @@ -940,6 +950,8 @@ set(OPENTUNE_STANDALONE_SOURCES set(OPENTUNE_NON_STANDALONE_SOURCES Source/Plugin/Vst3ProcessorStateCodec.cpp Source/Plugin/Vst3ProcessorStateCodec.h + Source/Plugin/ReaperHostBridge.cpp + Source/Plugin/ReaperHostBridge.h Source/Content/CaptureSegmentContent.h Source/Content/CaptureSegmentContent.cpp ) @@ -1937,6 +1949,17 @@ if(OPENTUNE_BUILD_TESTS) endif() add_test(NAME PitchLaneVisualPolicyTests COMMAND OpenTunePitchLaneVisualPolicyTests) + # Spoken note pitch text for screen readers - standard library only + add_executable(OpenTuneNoteSpeechTests + Tests/NoteSpeechTests.cpp + ) + target_include_directories(OpenTuneNoteSpeechTests + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Source) + if(MSVC) + target_compile_options(OpenTuneNoteSpeechTests PRIVATE /utf-8 /EHsc) + endif() + add_test(NAME NoteSpeechTests COMMAND OpenTuneNoteSpeechTests) + add_executable(OpenTuneHostTransportTests Tests/HostTransportTests.cpp ) diff --git a/Source/ARA/OpenTuneDocumentController.cpp b/Source/ARA/OpenTuneDocumentController.cpp index 6c1e300d..bc98769c 100644 --- a/Source/ARA/OpenTuneDocumentController.cpp +++ b/Source/ARA/OpenTuneDocumentController.cpp @@ -3,6 +3,7 @@ #include "OpenTunePlaybackRenderer.h" #include "../Audio/NotePitchAudition.h" +#include "../Utils/NoteAudition.h" #include "../Inference/F0InferenceService.h" #include "../Runtime/ProcessF0Runtime.h" @@ -1053,6 +1054,42 @@ void OpenTuneDocumentController::stopNotePitchAudition() noexcept notePitchAudition_->stop(); } +void OpenTuneDocumentController::setKeyboardAuditionSource(NoteAudition* source) noexcept +{ + while (keyboardAuditionLock_.test_and_set(std::memory_order_acquire)) {} + keyboardAuditionSource_ = source; + keyboardAuditionLock_.clear(std::memory_order_release); +} + +void OpenTuneDocumentController::mixKeyboardAudition( + juce::ARAEditorRenderer* renderer, + juce::AudioBuffer& buffer, + int numSamples, + double sampleRate) noexcept +{ + if (keyboardAuditionLock_.test_and_set(std::memory_order_acquire)) + return; + + // One mixer per document: a second one would advance the clip twice per block. + if (keyboardAuditionMixer_ == nullptr) + keyboardAuditionMixer_ = renderer; + if (keyboardAuditionMixer_ == renderer && keyboardAuditionSource_ != nullptr) + keyboardAuditionSource_->mixIntoBuffer(buffer, numSamples, sampleRate); + + keyboardAuditionLock_.clear(std::memory_order_release); +} + +void OpenTuneDocumentController::releaseKeyboardAudition( + NoteAudition* source, juce::ARAEditorRenderer* renderer) noexcept +{ + while (keyboardAuditionLock_.test_and_set(std::memory_order_acquire)) {} + if (keyboardAuditionSource_ == source) + keyboardAuditionSource_ = nullptr; + if (renderer != nullptr && keyboardAuditionMixer_ == renderer) + keyboardAuditionMixer_ = nullptr; + keyboardAuditionLock_.clear(std::memory_order_release); +} + bool OpenTuneDocumentController::PlaybackRegionProjection::isPlaybackRenderable() const noexcept { return contentKey.isValid() diff --git a/Source/ARA/OpenTuneDocumentController.h b/Source/ARA/OpenTuneDocumentController.h index d19cd33e..43b90b33 100644 --- a/Source/ARA/OpenTuneDocumentController.h +++ b/Source/ARA/OpenTuneDocumentController.h @@ -32,6 +32,7 @@ class OpenTunePlaybackRenderer; class OpenTuneAudioProcessor; class ResamplingManager; class NotePitchAudition; +class NoteAudition; struct RenderJob; class OpenTuneDocumentController : public juce::ARADocumentControllerSpecialisation { @@ -241,6 +242,16 @@ class OpenTuneDocumentController : public juce::ARADocumentControllerSpecialisat double sampleRate) noexcept; void stopNotePitchAudition() noexcept; + // Keyboard note audition. The editor view owns it, but as an item FX in REAPER that + // instance is a playback renderer and gets no audio blocks while stopped, so the + // arrows were silent. The realtime editor renderer of the document mixes it instead. + void setKeyboardAuditionSource(NoteAudition* source) noexcept; + void mixKeyboardAudition(juce::ARAEditorRenderer* renderer, + juce::AudioBuffer& buffer, + int numSamples, + double sampleRate) noexcept; + void releaseKeyboardAudition(NoteAudition* source, juce::ARAEditorRenderer* renderer) noexcept; + /** Shared PlayHeadState for all ARA roles bound to this document. The * realtime editor renderer publishes host transport here; UI binds to this. */ const PlayHeadState& getSharedPlayHeadState() const noexcept { return sharedPlayHeadState_; } @@ -296,6 +307,12 @@ class OpenTuneDocumentController : public juce::ARADocumentControllerSpecialisat std::atomic notePitchAuditionRenderer_{nullptr}; std::atomic_flag notePitchAuditionMixLock_ = ATOMIC_FLAG_INIT; + // Guarded by keyboardAuditionLock_: the audio thread only tries it, the message thread + // waits for it, so a source is never freed while it is being mixed. + NoteAudition* keyboardAuditionSource_ = nullptr; + juce::ARAEditorRenderer* keyboardAuditionMixer_ = nullptr; + std::atomic_flag keyboardAuditionLock_ = ATOMIC_FLAG_INIT; + JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(OpenTuneDocumentController) }; diff --git a/Source/Editor/AboutDialogContent.h b/Source/Editor/AboutDialogContent.h index 423f7942..a86bd3d0 100644 --- a/Source/Editor/AboutDialogContent.h +++ b/Source/Editor/AboutDialogContent.h @@ -29,7 +29,8 @@ class AboutDialogContent : public juce::Component, juce::DialogWindow::LaunchOptions options; options.content.setOwned(content); - options.dialogTitle = {}; + // The title bar is hidden, but the window name is what NVDA reads on open. + options.dialogTitle = LOC(kAbout); options.dialogBackgroundColour = UIColors::backgroundDark; options.escapeKeyTriggersCloseButton = false; options.useNativeTitleBar = false; @@ -45,12 +46,18 @@ class AboutDialogContent : public juce::Component, explicit AboutDialogContent(const juce::String& markdown) : parentSubscription_(*this) { - setWantsKeyboardFocus(true); + // Accessibility: the content itself is not a focus stop (NVDA read it as "unknown"). + // Every text line and link is, so Tab reads the page in order; keys bubble up here. + setWantsKeyboardFocus(false); buildItems(markdown); viewport_.setViewedComponent(&body_, false); viewport_.setScrollBarsShown(true, false); viewport_.setScrollBarThickness(8); + viewport_.getVerticalScrollBar().setAccessible(false); + // JUCE Viewport is a Tab stop by default; NVDA read it as "unknown" (user test). + // Tab scrolls the focused line into view, so the viewport needs no focus. + viewport_.setWantsKeyboardFocus(false); addAndMakeVisible(viewport_); closeButton_.setButtonText(LOC(kClose)); @@ -85,6 +92,17 @@ class AboutDialogContent : public juce::Component, bool keyPressed(const juce::KeyPress& key) override { + // Enter and Space press the focused link or Close, as in standard Windows dialogs; + // Enter on a text line closes the dialog as before. + if (key == juce::KeyPress::returnKey || key == juce::KeyPress::spaceKey) + { + if (auto* button = dynamic_cast(juce::Component::getCurrentlyFocusedComponent()); + button != nullptr && isParentOf(button)) + { + button->triggerClick(); + return true; + } + } if (key == juce::KeyPress::escapeKey || key == juce::KeyPress::returnKey) { closeDialog(); @@ -93,6 +111,28 @@ class AboutDialogContent : public juce::Component, return false; } + // Tab can land on a line scrolled out of view: bring it into the viewport. + void focusOfChildComponentChanged(FocusChangeType) override + { + auto* focused = juce::Component::getCurrentlyFocusedComponent(); + if (focused == nullptr || !body_.isParentOf(focused)) + return; + + const auto area = body_.getLocalArea(focused, focused->getLocalBounds()); + const int viewTop = viewport_.getViewPositionY(); + const int viewHeight = viewport_.getViewHeight(); + if (area.getY() < viewTop) + viewport_.setViewPosition(0, area.getY()); + else if (area.getBottom() > viewTop + viewHeight) + viewport_.setViewPosition(0, area.getBottom() - viewHeight); + } + + // Plain group without a name: NVDA skips it instead of saying "unknown". + std::unique_ptr createAccessibilityHandler() override + { + return std::make_unique(*this, juce::AccessibilityRole::group); + } + void parentHierarchyChanged() override { if (auto* dialog = findParentComponentOfClass(); @@ -129,6 +169,14 @@ class AboutDialogContent : public juce::Component, TextRun(const juce::String& text, Style style) : text_(text), style_(style) { setInterceptsMouseClicks(false, false); + // The text is only painted: expose it as a focusable line so NVDA reads it on Tab. + setTitle(text); + setWantsKeyboardFocus(true); + } + + std::unique_ptr createAccessibilityHandler() override + { + return std::make_unique(*this, juce::AccessibilityRole::staticText); } int preferredWidth() const @@ -216,6 +264,9 @@ class AboutDialogContent : public juce::Component, return; auto& run = texts_.emplace_back(std::make_unique(trimmed, line.style)); + // JUCE orders Tab by y then x, and centred text sits lower than a link on the + // same row, so keep the reading order explicitly. + run->setExplicitFocusOrder(nextFocusOrder_++); body_.addAndMakeVisible(*run); line.items.push_back({ run.get(), run.get(), nullptr }); } @@ -237,6 +288,7 @@ class AboutDialogContent : public juce::Component, } }; + button->setExplicitFocusOrder(nextFocusOrder_++); body_.addAndMakeVisible(*button); line.items.push_back({ button.get(), nullptr, button.get() }); } @@ -368,8 +420,17 @@ class AboutDialogContent : public juce::Component, { juce::Component::SafePointer safeThis(this); juce::MessageManager::callAsync([safeThis] { - if (safeThis != nullptr && safeThis->isShowing()) - safeThis->grabKeyboardFocus(); + if (safeThis == nullptr || !safeThis->isShowing() || safeThis->initialFocusDone_) + return; + // This runs more than once while the dialog opens; focus only the first time, + // or NVDA repeats the window name and the line. + safeThis->initialFocusDone_ = true; + + // Focus the first line (the heading): NVDA reads the window name and the line. + juce::Component* target = &safeThis->closeButton_; + if (!safeThis->lines_.empty() && !safeThis->lines_.front().items.empty()) + target = safeThis->lines_.front().items.front().component; + target->grabKeyboardFocus(); }); } @@ -380,6 +441,8 @@ class AboutDialogContent : public juce::Component, juce::Viewport viewport_; juce::TextButton closeButton_; bool closing_ = false; + bool initialFocusDone_ = false; + int nextFocusOrder_ = 1; ComponentListenerSubscription parentSubscription_; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(AboutDialogContent) diff --git a/Source/Editor/ConfirmDialogContent.h b/Source/Editor/ConfirmDialogContent.h index 38d48b3a..a90af159 100644 --- a/Source/Editor/ConfirmDialogContent.h +++ b/Source/Editor/ConfirmDialogContent.h @@ -7,6 +7,7 @@ #include "ComponentListenerSubscription.h" #include "../Standalone/UI/UIColors.h" #include "../Utils/LocalizationManager.h" +#include "../Utils/ScreenReaderAnnouncer.h" namespace OpenTune { @@ -60,7 +61,9 @@ class ConfirmDialogContent : public juce::Component, parentSubscription_(*this), dialogSubscription_(*this) { - setWantsKeyboardFocus(true); + // Accessibility: the content used to take focus itself and NVDA read it as + // "unknown". Now only the buttons take focus; keys still bubble up to keyPressed. + setWantsKeyboardFocus(false); // 创建按钮并确定默认按钮(先有按钮才能按最佳宽度决定弹窗宽度) for (size_t i = 0; i < buttonSpecs_.size(); ++i) { @@ -115,7 +118,8 @@ class ConfirmDialogContent : public juce::Component, { juce::DialogWindow::LaunchOptions options; options.content.setOwned(content); - options.dialogTitle = {}; + // The title bar is hidden, but the window name is what NVDA reads on open. + options.dialogTitle = content->title_; options.dialogBackgroundColour = UIColors::backgroundDark; options.escapeKeyTriggersCloseButton = false; // Esc 由内容处理(dismiss 路径) options.useNativeTitleBar = false; @@ -143,10 +147,15 @@ class ConfirmDialogContent : public juce::Component, const juce::String& summary, const juce::String& diagnosticText) { + juce::Component::SafePointer safeParent(parent); auto* content = new ConfirmDialogContent(title, summary, { - { LOC(kCopy), [diagnosticText] { + { LOC(kCopy), [diagnosticText, safeParent] { juce::SystemClipboard::copyTextToClipboard(diagnosticText); + // The dialog closes on Copy, so confirm it from the editor. + if (safeParent != nullptr && safeParent->isShowing()) + a11y::announce(*safeParent, LOC_RAW("Copied to clipboard"), + a11y::SpeechQueue::keepAll); } }, { LOC(kOK), nullptr, true } }); @@ -236,6 +245,15 @@ class ConfirmDialogContent : public juce::Component, dismiss(); return true; } + // Space presses the focused button, as in standard Windows dialogs. + if (key == juce::KeyPress::spaceKey) { + for (auto* btn : buttons_) { + if (btn->hasKeyboardFocus(false)) { + btn->triggerClick(); + return true; + } + } + } if (key == juce::KeyPress::returnKey) { // 按 Enter 触发默认按钮 if (defaultButtonIdx_ >= 0 && defaultButtonIdx_ < static_cast(buttons_.size())) { @@ -311,6 +329,7 @@ class ConfirmDialogContent : public juce::Component, int defaultButtonIdx_ = 0; bool closing_ = false; + bool messageAnnounced_ = false; bool verticalButtons_ = false; bool centreButtons_ = false; int messageHeight_ = 24; @@ -428,11 +447,34 @@ class ConfirmDialogContent : public juce::Component, { juce::Component::SafePointer safeThis(this); juce::MessageManager::callAsync([safeThis] { - if (safeThis != nullptr && safeThis->isShowing()) - safeThis->grabKeyboardFocus(); + if (safeThis == nullptr || !safeThis->isShowing()) + return; + + // Focus the default button: NVDA reads the window name (the title) and the button. + const int idx = safeThis->defaultButtonIdx_; + juce::Component* target = safeThis.getComponent(); + if (idx >= 0 && idx < safeThis->buttons_.size()) + target = safeThis->buttons_[idx]; + // takeKeyboardFocus runs more than once while the dialog opens; grabbing the + // already focused button again made NVDA repeat "dialog, OK button". + if (!target->hasKeyboardFocus(false)) + target->grabKeyboardFocus(); + + // The message is only painted, so speak it once. keepAll queues it after + // the focus speech instead of cutting it off. + if (!safeThis->messageAnnounced_ && safeThis->message_.isNotEmpty()) { + safeThis->messageAnnounced_ = true; + a11y::announce(*target, safeThis->message_, a11y::SpeechQueue::keepAll); + } }); } + // Plain group without a name: NVDA skips it instead of saying "unknown". + std::unique_ptr createAccessibilityHandler() override + { + return std::make_unique(*this, juce::AccessibilityRole::group); + } + JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ConfirmDialogContent) }; diff --git a/Source/Editor/PitchShiftDialogContent.h b/Source/Editor/PitchShiftDialogContent.h index bfca9eb5..439b3ddf 100644 --- a/Source/Editor/PitchShiftDialogContent.h +++ b/Source/Editor/PitchShiftDialogContent.h @@ -5,6 +5,7 @@ #include "ComponentListenerSubscription.h" #include "../Utils/PitchShiftSettings.h" #include "../Utils/LocalizationManager.h" +#include "../Utils/ScreenReaderAnnouncer.h" #include "../Standalone/UI/UIColors.h" namespace OpenTune { @@ -37,6 +38,8 @@ class PitchShiftDialogContent : public juce::Component, semitoneSlider_.setColour(juce::Slider::textBoxTextColourId, UIColors::textPrimary); semitoneSlider_.setColour(juce::Slider::textBoxBackgroundColourId, UIColors::backgroundDark); semitoneSlider_.setColour(juce::Slider::textBoxOutlineColourId, UIColors::panelBorder); + semitoneSlider_.setTitle(LOC_RAW("Semitones")); + semitoneSlider_.pageStep = 12.0; // Page Up/Down: one octave addAndMakeVisible(semitoneSlider_); // -- Semitone label -- @@ -56,8 +59,15 @@ class PitchShiftDialogContent : public juce::Component, centsSlider_.setColour(juce::Slider::textBoxTextColourId, UIColors::textPrimary); centsSlider_.setColour(juce::Slider::textBoxBackgroundColourId, UIColors::backgroundDark); centsSlider_.setColour(juce::Slider::textBoxOutlineColourId, UIColors::panelBorder); + centsSlider_.setTitle(LOC_RAW("Cents")); + centsSlider_.pageStep = 10.0; addAndMakeVisible(centsSlider_); + // The sliders carry the names; the captions would be read a second time. + semitoneLabel_.setAccessible(false); + centsLabel_.setAccessible(false); + keepValueBoxesOutOfTabOrder(); + // -- Cents label -- centsLabel_.setText(LOC_RAW("Cents"), juce::dontSendNotification); centsLabel_.setColour(juce::Label::textColourId, UIColors::textPrimary); @@ -82,6 +92,7 @@ class PitchShiftDialogContent : public juce::Component, closeParentDialog(); callback(); } + announceResult(PitchShiftSettings::identity()); }; addAndMakeVisible(resetButton_); @@ -101,6 +112,7 @@ class PitchShiftDialogContent : public juce::Component, closeParentDialog(); callback(settings); } + announceResult(settings); }; addAndMakeVisible(confirmButton_); } @@ -137,6 +149,7 @@ class PitchShiftDialogContent : public juce::Component, parentSubscription_.watch(*parent); else parentSubscription_.reset(); + dialogParent_ = parent; } // ============================================================================ @@ -194,6 +207,40 @@ class PitchShiftDialogContent : public juce::Component, dialogWindow->setContentComponentSize(contentWidth, contentHeight); } } + + // Moving into the window can recreate the value boxes (look-and-feel change), + // and launchAsync gives focus to the window first, so finish this a tick later. + juce::Component::SafePointer safeThis(this); + juce::MessageManager::callAsync([safeThis] { + if (safeThis == nullptr || !safeThis->isShowing()) + return; + safeThis->keepValueBoxesOutOfTabOrder(); + // Only the first time: parentHierarchyChanged fires more than once, and a repeated + // grab would make NVDA repeat the focus or pull focus back from another control. + if (!safeThis->initialFocusDone_) { + safeThis->initialFocusDone_ = true; + safeThis->semitoneSlider_.grabKeyboardFocus(); + } + }); + } + + bool keyPressed(const juce::KeyPress& key) override + { + // Keys bubble up here from the focused slider or button. + if (key == juce::KeyPress::spaceKey) { + for (auto* button : { &resetButton_, &confirmButton_ }) { + if (button->hasKeyboardFocus(false)) { + button->triggerClick(); + return true; + } + } + } + // Enter on a slider confirms, as the default button of a dialog. + if (key == juce::KeyPress::returnKey) { + confirmButton_.triggerClick(); + return true; + } + return false; } private: @@ -203,8 +250,52 @@ class PitchShiftDialogContent : public juce::Component, juce::Label semitoneLabel_; juce::Label centsLabel_; - juce::Slider semitoneSlider_; - juce::Slider centsSlider_; + // Keyboard slider: arrows change by 1, Page Up/Down by pageStep, Home/End go to the limits, + // Backspace to 0. Enter stays the dialog's OK, as in every dialog. + // The new value is spoken, because NVDA does not read JUCE's own value change here. + class StepSlider final : public juce::Slider + { + public: + double pageStep = 10.0; + + StepSlider() { setWantsKeyboardFocus(true); } + + bool keyPressed(const juce::KeyPress& key) override + { + if (key.getModifiers().isAnyModifierKeyDown()) + return juce::Slider::keyPressed(key); + + const int code = key.getKeyCode(); + double target = getValue(); + if (code == juce::KeyPress::upKey || code == juce::KeyPress::rightKey) target += 1.0; + else if (code == juce::KeyPress::downKey || code == juce::KeyPress::leftKey) target -= 1.0; + else if (code == juce::KeyPress::pageUpKey) target += pageStep; + else if (code == juce::KeyPress::pageDownKey) target -= pageStep; + // Home is the top and End the bottom, as in the EQ knobs (user's choice). + else if (code == juce::KeyPress::homeKey) target = getMaximum(); + else if (code == juce::KeyPress::endKey) target = getMinimum(); + else if (code == juce::KeyPress::backspaceKey) target = 0.0; + else + return juce::Slider::keyPressed(key); + + target = juce::jlimit(getMinimum(), getMaximum(), target); + // At a limit stay silent instead of repeating the same value. + if (target != getValue()) { + setValue(target, juce::sendNotificationSync); + a11y::announce(*this, signedText(getValue())); + } + return true; + } + }; + + static juce::String signedText(double value) + { + const int v = juce::roundToInt(value); + return v > 0 ? "+" + juce::String(v) : juce::String(v); + } + + StepSlider semitoneSlider_; + StepSlider centsSlider_; juce::TextButton resetButton_; juce::TextButton confirmButton_; std::function onConfirm_; @@ -212,6 +303,30 @@ class PitchShiftDialogContent : public juce::Component, bool actionTriggered_ = false; bool closing_ = false; ComponentListenerSubscription parentSubscription_{*this}; + juce::Component::SafePointer dialogParent_; + bool initialFocusDone_ = false; + + // The editable value box is a Label that takes focus and opens an unnamed text + // editor: a second Tab stop per slider. The mouse can still edit it. + void keepValueBoxesOutOfTabOrder() + { + for (auto* slider : { &semitoneSlider_, ¢sSlider_ }) + for (auto* child : slider->getChildren()) + if (auto* valueBox = dynamic_cast(child)) + valueBox->setWantsKeyboardFocus(false); + } + + // The dialog closes without a trace, so say what was applied. keepAll queues it + // after the focus speech of the editor. + void announceResult(const PitchShiftSettings& settings) + { + if (dialogParent_ == nullptr || !dialogParent_->isShowing()) + return; + a11y::announce(*dialogParent_, + LOC(kPitchShift) + ": " + LOC_RAW("Semitones") + " " + signedText(settings.semitone) + + ", " + LOC_RAW("Cents") + " " + signedText(settings.cents), + a11y::SpeechQueue::keepAll); + } void componentBeingDeleted(juce::Component& comp) override { diff --git a/Source/Editor/Preferences/SharedPreferencePages.cpp b/Source/Editor/Preferences/SharedPreferencePages.cpp index d526bd13..cf37b378 100644 --- a/Source/Editor/Preferences/SharedPreferencePages.cpp +++ b/Source/Editor/Preferences/SharedPreferencePages.cpp @@ -4,6 +4,9 @@ #include "Editor/ShortcutCaptureDialogContent.h" #include "Standalone/UI/UIColors.h" #include "Inference/ModelFactory.h" +#include "Utils/AccessibleComboBox.h" +#include "Utils/AccessibleKnob.h" +#include "Utils/AccessibleToggleButton.h" #include "Utils/KeyShortcutConfig.h" #include "Utils/LocalizationManager.h" #include "Utils/ModelPathResolver.h" @@ -161,9 +164,9 @@ class SharedGeneralPage final : public juce::Component AppPreferences& appPreferences_; std::function onPreferencesChanged_; juce::Label themeLabel_; - juce::ComboBox themeSelector_; + a11y::AccessibleComboBox themeSelector_; juce::Label languageLabel_; - juce::ComboBox languageSelector_; + a11y::AccessibleComboBox languageSelector_; }; class SharedAudioPage final : public juce::Component @@ -403,15 +406,15 @@ class SharedAudioPage final : public juce::Component int contentHeight_ = 0; std::vector vocoderWeights_; juce::Label renderingPriorityLabel_; - juce::ComboBox renderingPrioritySelector_; + a11y::AccessibleComboBox renderingPrioritySelector_; juce::TextButton replayOnboardingButton_; juce::Label vocoderWeightLabel_; - juce::ComboBox vocoderWeightSelector_; + a11y::AccessibleComboBox vocoderWeightSelector_; juce::Label f0ModelLabel_; - juce::ComboBox f0ModelSelector_; - juce::ToggleButton experimentalFeaturesToggle_; + a11y::AccessibleComboBox f0ModelSelector_; + a11y::AccessibleToggleButton experimentalFeaturesToggle_; juce::Label experimentalFeaturesHintLabel_; - juce::ToggleButton lightPitchCorrectionToggle_; + a11y::AccessibleToggleButton lightPitchCorrectionToggle_; }; class SharedEditingPage final : public juce::Component @@ -453,7 +456,10 @@ class SharedEditingPage final : public juce::Component ZoomSensitivityConfig::kMaxHorizontalZoomFactor, 0.01); horizontalSlider_.setValue(zoomSettings_.horizontalZoomFactor, juce::dontSendNotification); - horizontalSlider_.onValueChange = [this] { + // Accessibility: key steps (normal, Alt, Page) and the Backspace default, as all sliders. + horizontalSlider_.setKeySteps(0.05, 0.01, 0.2); + horizontalSlider_.setResetValue(ZoomSensitivityConfig::kDefaultHorizontalZoomFactor); + horizontalSlider_.onCommit = [this] { zoomSettings_.horizontalZoomFactor = static_cast(horizontalSlider_.getValue()); persistZoom(); }; @@ -466,7 +472,9 @@ class SharedEditingPage final : public juce::Component ZoomSensitivityConfig::kMaxVerticalZoomFactor, 0.01); verticalSlider_.setValue(zoomSettings_.verticalZoomFactor, juce::dontSendNotification); - verticalSlider_.onValueChange = [this] { + verticalSlider_.setKeySteps(0.05, 0.01, 0.2); + verticalSlider_.setResetValue(ZoomSensitivityConfig::kDefaultVerticalZoomFactor); + verticalSlider_.onCommit = [this] { zoomSettings_.verticalZoomFactor = static_cast(verticalSlider_.getValue()); persistZoom(); }; @@ -479,7 +487,9 @@ class SharedEditingPage final : public juce::Component ZoomSensitivityConfig::kMaxScrollSpeed, 1.0); scrollSlider_.setValue(zoomSettings_.scrollSpeed, juce::dontSendNotification); - scrollSlider_.onValueChange = [this] { + scrollSlider_.setKeySteps(5.0, 1.0, 30.0); + scrollSlider_.setResetValue(ZoomSensitivityConfig::kDefaultScrollSpeed); + scrollSlider_.onCommit = [this] { zoomSettings_.scrollSpeed = static_cast(scrollSlider_.getValue()); persistZoom(); }; @@ -490,7 +500,9 @@ class SharedEditingPage final : public juce::Component addAndMakeVisible(tuningLabel_); tuningSlider_.setRange(TuningConfig::kMinTuningHz, TuningConfig::kMaxTuningHz, 1.0); tuningSlider_.setValue(appPreferences_.getState().shared.tuning.tuningHz, juce::dontSendNotification); - tuningSlider_.onValueChange = [this] { + tuningSlider_.setKeySteps(1.0, 1.0, 10.0); + tuningSlider_.setResetValue(TuningConfig::kDefaultTuningHz); + tuningSlider_.onCommit = [this] { TuningConfig::TuningSettings tuning; tuning.tuningHz = static_cast(tuningSlider_.getValue()); appPreferences_.setTuning(tuning); @@ -634,21 +646,21 @@ class SharedEditingPage final : public juce::Component bool isVst3Plugin_ = false; ZoomSensitivityConfig::ZoomSensitivitySettings zoomSettings_; juce::Label schemeLabel_; - juce::ComboBox schemeSelector_; + a11y::AccessibleComboBox schemeSelector_; juce::Label horizontalLabel_; - juce::Slider horizontalSlider_; + a11y::AccessibleKnob horizontalSlider_; juce::Label verticalLabel_; - juce::Slider verticalSlider_; + a11y::AccessibleKnob verticalSlider_; juce::Label scrollLabel_; - juce::Slider scrollSlider_; + a11y::AccessibleKnob scrollSlider_; juce::Label tuningLabel_; - juce::Slider tuningSlider_; + a11y::AccessibleKnob tuningSlider_; juce::TextButton resetButton_; juce::Label gridStyleLabel_; - juce::ComboBox gridStyleSelector_; + a11y::AccessibleComboBox gridStyleSelector_; juce::Label wholeNoteMoveSnapLabel_; - juce::ComboBox wholeNoteMoveSnapSelector_; - juce::ToggleButton noteTransposePreviewToggle_; + a11y::AccessibleComboBox wholeNoteMoveSnapSelector_; + a11y::AccessibleToggleButton noteTransposePreviewToggle_; }; class SharedVisualPage final : public juce::Component @@ -778,7 +790,9 @@ class SharedVisualPage final : public juce::Component backgroundBrightnessSlider_.setRange(0.0, 2.0, 0.01); backgroundBrightnessSlider_.setValue(visualPreferences.backgroundBrightness, juce::dontSendNotification); - backgroundBrightnessSlider_.onValueChange = [this] { + backgroundBrightnessSlider_.setKeySteps(0.05, 0.01, 0.25); + backgroundBrightnessSlider_.setResetValue(1.0); + backgroundBrightnessSlider_.onCommit = [this] { appPreferences_.setBackgroundBrightness(static_cast(backgroundBrightnessSlider_.getValue())); notifyChanged(); }; @@ -910,10 +924,10 @@ class SharedVisualPage final : public juce::Component AppPreferences& appPreferences_; std::function onPreferencesChanged_; juce::Label noteNameModeLabel_; - juce::ComboBox noteNameModeSelector_; - juce::ToggleButton showUnvoicedFramesToggle_; + a11y::AccessibleComboBox noteNameModeSelector_; + a11y::AccessibleToggleButton showUnvoicedFramesToggle_; juce::Label backgroundBrightnessLabel_; - juce::Slider backgroundBrightnessSlider_; + a11y::AccessibleKnob backgroundBrightnessSlider_; juce::Label correctedF0ColourLabel_; ColourSwatchButton correctedF0ColourButton_; juce::Label originalF0ColourLabel_; diff --git a/Source/Editor/Preferences/StandalonePreferencePages.cpp b/Source/Editor/Preferences/StandalonePreferencePages.cpp index 7c27a0f2..f3ffde8c 100644 --- a/Source/Editor/Preferences/StandalonePreferencePages.cpp +++ b/Source/Editor/Preferences/StandalonePreferencePages.cpp @@ -6,6 +6,8 @@ #include "Standalone/StandaloneAudioDeviceSync.h" #include "Standalone/UI/UIColors.h" #include "Editor/Preferences/SharedPreferencePages.h" +#include "Utils/AccessibleComboBox.h" +#include "Utils/AccessibleToggleButton.h" #include "Utils/AppLogger.h" namespace OpenTune { @@ -299,7 +301,7 @@ class AudioDeviceSettingsContent final : public juce::Component, channelToggles_.removeLast(); while (channelToggles_.size() < numPairs) { - auto* toggle = channelToggles_.add(new juce::ToggleButton()); + auto* toggle = channelToggles_.add(new a11y::AccessibleToggleButton()); initialiseToggleButton(*toggle); const int pairIndex = channelToggles_.size() - 1; toggle->onClick = [this, pairIndex] { channelPairClicked(pairIndex); }; @@ -508,14 +510,14 @@ class AudioDeviceSettingsContent final : public juce::Component, juce::AudioDeviceManager& deviceManager_; juce::Label typeLabel_; - juce::ComboBox typeSelector_; + a11y::AccessibleComboBox typeSelector_; juce::Label outputLabel_; - juce::ComboBox outputDeviceSelector_; + a11y::AccessibleComboBox outputDeviceSelector_; juce::TextButton testButton_; juce::Label sampleRateLabel_; - juce::ComboBox sampleRateSelector_; + a11y::AccessibleComboBox sampleRateSelector_; juce::Label bufferSizeLabel_; - juce::ComboBox bufferSizeSelector_; + a11y::AccessibleComboBox bufferSizeSelector_; juce::Label channelsLabel_; juce::OwnedArray channelToggles_; juce::Label errorLabel_; @@ -622,7 +624,7 @@ class MouseTrailPage final : public juce::Component AppPreferences& appPreferences_; std::function onPreferencesChanged_; juce::Label themeLabel_; - juce::ComboBox themeSelector_; + a11y::AccessibleComboBox themeSelector_; }; } // namespace diff --git a/Source/Editor/Preferences/TabbedPreferencesDialog.h b/Source/Editor/Preferences/TabbedPreferencesDialog.h index b840e9a5..d2a89d7b 100644 --- a/Source/Editor/Preferences/TabbedPreferencesDialog.h +++ b/Source/Editor/Preferences/TabbedPreferencesDialog.h @@ -7,6 +7,7 @@ #include #include "Utils/LocalizationManager.h" +#include "Utils/ScreenReaderAnnouncer.h" #include "Standalone/UI/AuroraLookAndFeel.h" #include "Standalone/UI/OpenTuneLookAndFeel.h" #include "Standalone/UI/UIColors.h" @@ -20,6 +21,11 @@ class ScrollablePage : public juce::Viewport explicit ScrollablePage(std::unique_ptr content, int contentHeight) { setScrollBarThickness(8); + // Accessibility: the viewport itself took Tab focus (NVDA: "unknown") + // and the scroll bars are mouse-only. Page controls stay reachable. + setWantsKeyboardFocus(false); + getVerticalScrollBar().setAccessible(false); + getHorizontalScrollBar().setAccessible(false); // setViewedComponent 将 content 放入内部 contentHolder // content 保持自身高度,viewport 自动提供滚动 contentHeight_ = contentHeight; @@ -65,11 +71,42 @@ class TabbedPreferencesDialog : public juce::Component continue; } + nameControlsByPrecedingLabels(*page.content); + // 统一包装为可滚动:内容比视口矮时滚动条不出现,比视口高时自动出现 auto* scrollable = new ScrollablePage(std::move(page.content), page.totalHeight); tabbedComponent_.addTab(page.title, UIColors::backgroundDark, scrollable, true); } + // Accessibility: tab buttons do not take focus by default, so Tab skipped them. + // Only the current tab is a Tab stop; arrows move between tabs (see keyPressed). + auto& tabBar = tabbedComponent_.getTabbedButtonBar(); + updateTabStops(); + // The tab bar acted as a keyboard focus container: Tab cycled through the tab buttons + // only and never reached the page or the Close button. + tabBar.setFocusContainerType(juce::Component::FocusContainerType::none); + tabbedComponent_.setFocusContainerType(juce::Component::FocusContainerType::none); + // On a tab change JUCE moves focus into the new page (toFront(true)), and the tab name + // announced after that cut off NVDA reading the page's first control, so it sounded as + // if focus stayed on the tab (user test). Keep focus on the tab button instead, as in + // Windows tab dialogs: its focus speech names the tab, and Tab goes on into the page. + tabbedComponent_.onTabChanged = [this](const juce::String& name) { + updateTabStops(); + auto& bar = tabbedComponent_.getTabbedButtonBar(); + auto* tabButton = bar.getTabButton(bar.getCurrentTabIndex()); + if (tabButton == nullptr || !tabButton->isShowing()) + return; + if (tabButton->hasKeyboardFocus(false)) + a11y::announce(*this, name); // focus did not move: no focus speech to rely on + else + tabButton->grabKeyboardFocus(); + }; + + // Sliders on the pages: Tab lands in the value box editor, which has no name. + for (int i = 0; i < tabbedComponent_.getNumTabs(); ++i) + if (auto* page = tabbedComponent_.getTabContentComponent(i)) + addSliderEditorNamers(*page); + closeButton_.setButtonText(LOC(kClose)); closeButton_.setColour(juce::TextButton::buttonColourId, UIColors::accent); closeButton_.setColour(juce::TextButton::textColourOffId, UIColors::textPrimary); @@ -106,10 +143,174 @@ class TabbedPreferencesDialog : public juce::Component dialogWindow->setTitleBarHeight(0); dialogWindow->setContentComponentSize(contentWidth, contentHeight); } + + // Accessibility: on open, focus sat on the bare window rather than a control. + // Move it to the selected tab once the window is on screen. + juce::Component::SafePointer safeThis(this); + juce::Timer::callAfterDelay(100, [safeThis] { + if (safeThis == nullptr) + return; + auto& bar = safeThis->tabbedComponent_.getTabbedButtonBar(); + if (auto* tabButton = bar.getTabButton(bar.getCurrentTabIndex())) + if (tabButton->isShowing()) + tabButton->grabKeyboardFocus(); + }); + } + } + + // Ctrl+Tab / Ctrl+Shift+Tab switch to the next / previous tab, as in Windows dialogs. + bool keyPressed(const juce::KeyPress& key) override + { + const auto mods = key.getModifiers(); + // JUCE buttons react to Space through key-state polling, which does not work inside + // REAPER (NVDA user: Space did not toggle a check box, Enter did). Press the focused + // button ourselves. + if (key.getKeyCode() == juce::KeyPress::spaceKey && !mods.isAnyModifierKeyDown()) { + auto* focused = juce::Component::getCurrentlyFocusedComponent(); + if (auto* button = dynamic_cast(focused); button != nullptr && isParentOf(button)) { + button->triggerClick(); + return true; + } + } + // On a tab button: Up/Left go to the previous tab, Down/Right to the next one (Up/Down + // as in REAPER's preferences tree, which the user expects), Home/End to the first / + // last one. No wrap-around: at the ends nothing happens, as in other lists. + if (!mods.isAnyModifierKeyDown()) { + auto& bar = tabbedComponent_.getTabbedButtonBar(); + auto* focused = juce::Component::getCurrentlyFocusedComponent(); + const int keyCode = key.getKeyCode(); + const bool previousKey = keyCode == juce::KeyPress::upKey || keyCode == juce::KeyPress::leftKey; + const bool nextKey = keyCode == juce::KeyPress::downKey || keyCode == juce::KeyPress::rightKey; + if (focused != nullptr && bar.isParentOf(focused) + && (previousKey || nextKey + || keyCode == juce::KeyPress::homeKey || keyCode == juce::KeyPress::endKey)) { + const int count = tabbedComponent_.getNumTabs(); + const int current = tabbedComponent_.getCurrentTabIndex(); + int target = current; + if (previousKey) target = current - 1; + else if (nextKey) target = current + 1; + else if (keyCode == juce::KeyPress::homeKey) target = 0; + else target = count - 1; + if (target >= 0 && target < count && target != current) + tabbedComponent_.setCurrentTabIndex(target); + return true; + } + } + if (key.getKeyCode() == juce::KeyPress::tabKey && mods.isCtrlDown() && !mods.isAltDown()) { + const int count = tabbedComponent_.getNumTabs(); + if (count > 0) { + const int step = mods.isShiftDown() ? count - 1 : 1; + tabbedComponent_.setCurrentTabIndex((tabbedComponent_.getCurrentTabIndex() + step) % count); + } + return true; } + return false; } private: + // Only the current tab button takes Tab focus, so Tab goes from it straight into the page. + void updateTabStops() + { + auto& bar = tabbedComponent_.getTabbedButtonBar(); + for (int i = 0; i < bar.getNumTabs(); ++i) + if (auto* tabButton = bar.getTabButton(i)) + tabButton->setWantsKeyboardFocus(i == bar.getCurrentTabIndex()); + } + + // Reports tab changes made by the user, for the focus handling above. + class AnnouncingTabs final : public juce::TabbedComponent + { + public: + AnnouncingTabs() : juce::TabbedComponent(juce::TabbedButtonBar::TabsAtTop) {} + std::function onTabChanged; + + void currentTabChanged(int, const juce::String& newTabName) override + { + if (onTabChanged != nullptr && isShowing()) + onTabChanged(newTabName); + } + }; + + // Names the TextEditor that a slider's value box opens with the slider's title. + // The value box is recreated on look-and-feel changes (e.g. theme switch), so the hook + // is re-installed whenever the slider's children change. + class SliderEditorNamer final : private juce::ComponentListener + { + public: + explicit SliderEditorNamer(juce::Slider& slider) : slider_(&slider) + { + slider.addComponentListener(this); + hookValueBox(); + } + + ~SliderEditorNamer() override + { + if (slider_ != nullptr) + slider_->removeComponentListener(this); + } + + private: + void componentChildrenChanged(juce::Component&) override { hookValueBox(); } + + void hookValueBox() + { + if (slider_ == nullptr) + return; + for (auto* child : slider_->getChildren()) { + if (auto* valueBox = dynamic_cast(child)) { + valueBox->onEditorShow = [valueBox] { + auto* editor = valueBox->getCurrentTextEditor(); + auto* owner = valueBox->getParentComponent(); + if (editor != nullptr && owner != nullptr) + editor->setTitle(owner->getTitle()); + }; + } + } + } + + juce::Component::SafePointer slider_; + }; + + void addSliderEditorNamers(juce::Component& parent) + { + for (auto* child : parent.getChildren()) { + if (auto* slider = dynamic_cast(child)) + sliderEditorNamers_.push_back(std::make_unique(*slider)); + else + addSliderEditorNamers(*child); + } + } + + // Preference pages are laid out as "caption label, then control". JUCE exposes a label's + // text twice (as name and value), while combo boxes and sliders get no name at all. + // Move the caption into the control's title and hide the caption. Buttons with their own + // changing text (shortcut binding, colour) get the caption as description instead. + static void nameControlsByPrecedingLabels(juce::Component& page) + { + juce::Label* pendingLabel = nullptr; + for (auto* child : page.getChildren()) { + if (auto* label = dynamic_cast(child)) { + pendingLabel = label; + continue; + } + if (pendingLabel != nullptr && child->getTitle().isEmpty()) { + const auto caption = pendingLabel->getText(); + auto* button = dynamic_cast(child); + if (button != nullptr && button->getButtonText().isNotEmpty()) { + button->setDescription(caption); + pendingLabel->setAccessible(false); + } else if (button != nullptr + || dynamic_cast(child) != nullptr + || dynamic_cast(child) != nullptr + || dynamic_cast(child) != nullptr) { + child->setTitle(caption); + pendingLabel->setAccessible(false); + } + } + pendingLabel = nullptr; + } + } + void closeDialog() { if (closing_) @@ -130,7 +331,9 @@ class TabbedPreferencesDialog : public juce::Component setLookAndFeel(&openTuneLookAndFeel_); } - juce::TabbedComponent tabbedComponent_{juce::TabbedButtonBar::TabsAtTop}; + AnnouncingTabs tabbedComponent_; + // Declared after tabbedComponent_ so they are destroyed first, while the sliders still exist. + std::vector> sliderEditorNamers_; juce::TextButton closeButton_; OpenTuneLookAndFeel openTuneLookAndFeel_; AuroraLookAndFeel auroraLookAndFeel_; diff --git a/Source/Editor/RenderBadgeComponent.h b/Source/Editor/RenderBadgeComponent.h index a464d953..946c2574 100644 --- a/Source/Editor/RenderBadgeComponent.h +++ b/Source/Editor/RenderBadgeComponent.h @@ -42,6 +42,29 @@ class RenderBadgeComponent : public juce::Component #endif } + // Accessibility: readable by NVDA object navigation ("Rendering (2/5)") instead of an + // unnamed object; hidden while empty. Not spoken by itself: that was too talkative. + std::unique_ptr createAccessibilityHandler() override + { + class BadgeAccessibilityHandler final : public juce::AccessibilityHandler { + public: + explicit BadgeAccessibilityHandler(RenderBadgeComponent& owner) + : juce::AccessibilityHandler(owner, juce::AccessibilityRole::staticText), owner_(owner) {} + + juce::String getTitle() const override { return owner_.text_; } + + juce::AccessibleState getCurrentState() const override + { + auto state = juce::AccessibilityHandler::getCurrentState(); + return owner_.text_.isEmpty() ? state.withIgnored() : state; + } + + private: + RenderBadgeComponent& owner_; + }; + + return std::make_unique(*this); + } #if JUCE_IOS static constexpr int kWidth = 280; static constexpr int kHeight = 58; diff --git a/Source/Editor/ShortcutCaptureDialogContent.h b/Source/Editor/ShortcutCaptureDialogContent.h index 562f7be0..3eb71209 100644 --- a/Source/Editor/ShortcutCaptureDialogContent.h +++ b/Source/Editor/ShortcutCaptureDialogContent.h @@ -6,6 +6,7 @@ #include "../Standalone/UI/UIColors.h" #include "../Utils/KeyShortcutConfig.h" #include "../Utils/LocalizationManager.h" +#include "../Utils/ScreenReaderAnnouncer.h" namespace OpenTune { @@ -50,6 +51,8 @@ class ShortcutCaptureDialogContent final : public juce::Component, dialogSubscription_ (*this) { setWantsKeyboardFocus (true); + // The capture area must keep focus (every key is captured), so it needs a name. + setTitle (LOC (kShortcutCapturePressKey)); // 消息区按实际文案测量,至少 4 行(buildCaptureMessage 固定 4 行), // 避免俄/西语等较长译文把“当前绑定”一行挤掉。 @@ -83,7 +86,8 @@ class ShortcutCaptureDialogContent final : public juce::Component, juce::DialogWindow::LaunchOptions options; options.content.setOwned (content); - options.dialogTitle = {}; + // The title bar is hidden, but the window name is what NVDA reads on open. + options.dialogTitle = title; options.dialogBackgroundColour = UIColors::backgroundDark; options.escapeKeyTriggersCloseButton = false; // Esc 也作为绑定被内容组件捕获 options.useNativeTitleBar = false; @@ -267,11 +271,30 @@ class ShortcutCaptureDialogContent final : public juce::Component, juce::Component::SafePointer safeThis (this); juce::MessageManager::callAsync ([safeThis] { - if (safeThis != nullptr) + if (safeThis == nullptr) + return; + // Called more than once while the dialog opens: a repeated grab made NVDA repeat it. + if (! safeThis->hasKeyboardFocus (false)) safeThis->grabKeyboardFocus(); + + // The message (shortcut name and current binding) is only painted: speak it + // once, queued after the focus speech. + if (! safeThis->messageAnnounced_ && safeThis->isShowing() && safeThis->message_.isNotEmpty()) + { + safeThis->messageAnnounced_ = true; + a11y::announce (*safeThis, safeThis->message_, a11y::SpeechQueue::keepAll); + } }); } + // A named group: NVDA read the plain component as "unknown". + std::unique_ptr createAccessibilityHandler() override + { + return std::make_unique (*this, juce::AccessibilityRole::group); + } + + bool messageAnnounced_ = false; + /** 按当前字体与对话框宽度测量消息区,保证至少 4 行完整显示。 */ void measureMessage() { diff --git a/Source/Plugin/PluginEditor.cpp b/Source/Plugin/PluginEditor.cpp index 18b8606d..4fa19cb2 100644 --- a/Source/Plugin/PluginEditor.cpp +++ b/Source/Plugin/PluginEditor.cpp @@ -21,6 +21,8 @@ #include "Utils/ScaleUiMapping.h" #include "Utils/TimeCoordinate.h" #include "UI/UiAssets.h" +#include "Utils/ScreenReaderAnnouncer.h" +#include "Utils/ContextMenuKey.h" #if JucePlugin_Enable_ARA #include "ARA/OpenTuneDocumentController.h" @@ -179,50 +181,78 @@ OpenTuneAudioProcessorEditor::OpenTuneAudioProcessorEditor(OpenTuneAudioProcesso // Piano key audition pianoRoll_.setPianoKeyAudition(&processorRef_.getPianoKeyAudition()); + pianoRoll_.setNoteAudition(&processorRef_.getNoteAudition()); + pianoRoll_.setRenderCacheProvider([this](ContentKey key) { return processorRef_.getReadableRenderCache(key); }); // Menu popup callbacks — MenuBarComponent stays hidden, provides menu content // via TransportBar icon buttons (File/Edit/View) menuBar_.setVisible(false); - transportBar_.onFileMenuRequested = [this]() { + // Accessibility: when a menu closes, Esc included, focus goes back to its button; it used + // to be lost and NVDA said nothing. A dialog opened from the menu takes focus after this. + const auto showTransportMenu = [this](int menuIndex, juce::Component& button) { const auto safeEditor = juce::Component::SafePointer(this); + const juce::Component::SafePointer safeButton(&button); auto menuNames = menuBar_.getMenuBarNames(); - auto menu = menuBar_.getMenuForIndex(0, menuNames.isEmpty() ? juce::String() : menuNames[0]); - menu.showMenuAsync(juce::PopupMenu::Options() - .withTargetComponent(&transportBar_.getFileButton()) - .withParentComponent(&contentRoot_), - [safeEditor](int result) { - if (result != 0 && safeEditor != nullptr) - safeEditor->menuBar_.menuItemSelected(result, 0); + auto menu = menuBar_.getMenuForIndex(menuIndex, menuIndex < menuNames.size() ? menuNames[menuIndex] + : juce::String()); + // Accessibility: open with the first item highlighted, so the first Enter works + // (user test: NVDA read "Options" on open, but Enter did nothing until an arrow key). + auto options = juce::PopupMenu::Options() + .withTargetComponent(&button) + .withParentComponent(&contentRoot_); + if (const int firstId = a11y::firstSelectableItemId(menu); firstId != 0) + options = options.withInitiallySelectedItem(firstId); + menu.showMenuAsync(options, + [safeEditor, safeButton, menuIndex](int result) { + if (safeEditor == nullptr) + return; + // The menu lives inside contentRoot_ and is deleted after this + // callback, taking focus with it, so a focus grab here was lost + // (user test: silence after Esc). Do it a moment later. + juce::Timer::callAfterDelay(100, [safeEditor, safeButton, cancelled = result == 0] { + if (safeEditor == nullptr || safeButton == nullptr || !safeButton->isShowing()) + return; + auto* focused = juce::Component::getCurrentlyFocusedComponent(); + if (focused == safeButton.getComponent()) { + // Focus never left the button: there is no focus event, so name it. + if (cancelled) + a11y::announce(*safeButton, safeButton->getTitle().isNotEmpty() + ? safeButton->getTitle() + : safeButton->getName()); + return; + } + // A dialog opened from the menu has focus now: leave it there. + if (focused != nullptr && focused != safeEditor.getComponent() + && focused != &safeEditor->contentRoot_) + return; + safeButton->grabKeyboardFocus(); + }); + if (result != 0) + safeEditor->menuBar_.menuItemSelected(result, menuIndex); }); }; - transportBar_.onEditMenuRequested = [this]() { - const auto safeEditor = juce::Component::SafePointer(this); - auto menuNames = menuBar_.getMenuBarNames(); - auto menu = menuBar_.getMenuForIndex(1, menuNames.size() > 1 ? menuNames[1] : juce::String()); - menu.showMenuAsync(juce::PopupMenu::Options() - .withTargetComponent(&transportBar_.getEditButton()) - .withParentComponent(&contentRoot_), - [safeEditor](int result) { - if (result != 0 && safeEditor != nullptr) - safeEditor->menuBar_.menuItemSelected(result, 1); - }); + transportBar_.onFileMenuRequested = [this, showTransportMenu]() { + showTransportMenu(0, transportBar_.getFileButton()); }; - transportBar_.onViewMenuRequested = [this]() { - const auto safeEditor = juce::Component::SafePointer(this); - auto menuNames = menuBar_.getMenuBarNames(); - auto menu = menuBar_.getMenuForIndex(2, menuNames.size() > 2 ? menuNames[2] : juce::String()); - menu.showMenuAsync(juce::PopupMenu::Options() - .withTargetComponent(&transportBar_.getViewButton()) - .withParentComponent(&contentRoot_), - [safeEditor](int result) { - if (result != 0 && safeEditor != nullptr) - safeEditor->menuBar_.menuItemSelected(result, 2); - }); + transportBar_.onEditMenuRequested = [this, showTransportMenu]() { + showTransportMenu(1, transportBar_.getEditButton()); + }; + + transportBar_.onViewMenuRequested = [this, showTransportMenu]() { + showTransportMenu(2, transportBar_.getViewButton()); }; + // Accessibility: the plugin has no track panel and cannot hide the parameter panel, so the + // Tracks and Props toggles do nothing here. They stay on screen as in the original, but leave + // the Tab order and the screen reader tree, where they read as working "pressed" buttons. + topBar_.setSidePanelTogglesAccessible(false); + + // The plugin's piano roll has no use for Esc: REAPER gets it and closes the FX window. + pianoRoll_.setEscapePassesToHost(true); + // content root 是 editor 的唯一直接子组件,承载全部主 UI(§7.3)。 addAndMakeVisible(contentRoot_); contentRoot_.addAndMakeVisible(topBar_); @@ -269,6 +299,11 @@ OpenTuneAudioProcessorEditor::OpenTuneAudioProcessorEditor(OpenTuneAudioProcesso [this] { pianoRoll_.grabKeyboardFocus(); }); contentRoot_.addChildComponent(*onboardingOverlay_); + // Upstream 59387696 dropped the per-tick preference sync and left no call here, so a + // new editor stayed in the default scheme: OpenDyne users got the classic mode, F1-F6 + // went to the host and Read Audio made no notes (user test). Apply the saved state once. + syncSharedAppPreferences(); + startTimerHz(kHeartbeatHz); // Host transport metadata (BPM/time signature): applied on demand from the // heartbeat when the processor's RT-safe generation counter moves; also @@ -285,6 +320,19 @@ OpenTuneAudioProcessorEditor::OpenTuneAudioProcessorEditor(OpenTuneAudioProcesso } grabKeyboardFocus(); + + // Accessibility: focus the piano roll right away so arrow keys work without Tab. + // Deferred because the editor is not on screen yet in the constructor. The first-run + // onboarding manages focus itself. + juce::Component::SafePointer safeThis(this); + juce::Timer::callAfterDelay(150, [safeThis] { + if (safeThis == nullptr) + return; + if (safeThis->onboardingOverlay_ != nullptr && safeThis->onboardingOverlay_->isActive()) + return; + if (safeThis->pianoRoll_.isShowing()) + safeThis->pianoRoll_.grabKeyboardFocus(); + }); } OpenTuneAudioProcessorEditor::~OpenTuneAudioProcessorEditor() @@ -544,6 +592,13 @@ void OpenTuneAudioProcessorEditor::timerCallback() // 外部编辑会话;损坏曲线的一次性提示也由 Processor 发出(无父组件依赖, // 窗口关闭后仍可见)。 + // Accessibility: the notes change without any other sign; say so. The check itself lives + // in the processor now, so watch its counter (-1: first tick, nothing to say yet). + const int externalEditApplied = processorRef_.getExternalEditAppliedCount(); + if (lastExternalEditAppliedCount_ >= 0 && externalEditApplied != lastExternalEditAppliedCount_) + a11y::announce(pianoRoll_, LOC_RAW("External edit applied"), a11y::SpeechQueue::keepAll); + lastExternalEditAppliedCount_ = externalEditApplied; + syncParameterPanelFromSelection(); // Heartbeat ticks first — match Standalone pattern: overview/camera @@ -754,6 +809,21 @@ void OpenTuneAudioProcessorEditor::timerCallback() } } if (allDone) { + // Accessibility: sighted users see the "Processing audio" overlay disappear and notes + // appear. Announce the result: how many notes were found or that analysis failed. + int noteCount = 0; + bool failed = false; + for (const auto& key : originalF0OverlayTargetContentKeys_) { + if (auto snap = processorRef_.getContentSnapshot(key)) { + failed = failed || snap->originalF0State == OriginalF0State::Failed; + noteCount += static_cast(snap->notes.size()); + } + } + a11y::announce(pianoRoll_, + failed ? LOC_RAW("Audio analysis failed") + : Loc::format(LOC_RAW("Audio read, notes: {0}"), juce::String(noteCount)), + a11y::SpeechQueue::keepAll); + originalF0OverlayLatched_ = false; originalF0OverlayTargetContentKeys_.clear(); // F0 overlay no longer blocks onboarding; modal windows may still be @@ -776,6 +846,17 @@ void OpenTuneAudioProcessorEditor::timerCallback() shouldShowOverlay = true; } + // Accessibility: sighted users see the "Rendering" badge go away. Say when a render that took + // a while is done, so it is clear playback now has the correction. Short renders stay silent + // so this does not talk over the note speech after every key press. + if (shouldShowBadge && !renderBadgeWasShown_) { + renderStartedMs_ = juce::Time::getMillisecondCounter(); + } else if (!shouldShowBadge && renderBadgeWasShown_ && !shouldShowOverlay + && juce::Time::getMillisecondCounter() - renderStartedMs_ >= kRenderDoneSpeechMinMs) { + a11y::announce(pianoRoll_, LOC_RAW("Rendering done"), a11y::SpeechQueue::keepAll); + } + renderBadgeWasShown_ = shouldShowBadge; + if (renderBadge_.isVisible() != shouldShowBadge) renderBadge_.setVisible(shouldShowBadge); if (autoRenderOverlay_.isVisible() != shouldShowOverlay) @@ -1070,6 +1151,7 @@ void OpenTuneAudioProcessorEditor::retuneSpeedChanged(float speed) if (result.status == AudioEditingScheme::ParameterEditStatus::NoTarget) { pianoRoll_.setCreationDefault(AudioEditingScheme::ParameterId::RetuneSpeed, normalized); } + announceParameterEdit(AudioEditingScheme::ParameterId::RetuneSpeed, result); } void OpenTuneAudioProcessorEditor::vibratoDepthChanged(float value) @@ -1078,6 +1160,7 @@ void OpenTuneAudioProcessorEditor::vibratoDepthChanged(float value) if (result.status == AudioEditingScheme::ParameterEditStatus::NoTarget) { pianoRoll_.setCreationDefault(AudioEditingScheme::ParameterId::VibratoDepth, value); } + announceParameterEdit(AudioEditingScheme::ParameterId::VibratoDepth, result); } void OpenTuneAudioProcessorEditor::vibratoRateChanged(float value) @@ -1086,12 +1169,27 @@ void OpenTuneAudioProcessorEditor::vibratoRateChanged(float value) if (result.status == AudioEditingScheme::ParameterEditStatus::NoTarget) { pianoRoll_.setCreationDefault(AudioEditingScheme::ParameterId::VibratoRate, value); } + announceParameterEdit(AudioEditingScheme::ParameterId::VibratoRate, result); } void OpenTuneAudioProcessorEditor::noteSplitChanged(float value) { // NoTarget 时 editParameter 内部已回落更新创建默认值 - pianoRoll_.editParameter(AudioEditingScheme::ParameterId::NoteSplit, value); + const auto result = pianoRoll_.editParameter(AudioEditingScheme::ParameterId::NoteSplit, value); + announceParameterEdit(AudioEditingScheme::ParameterId::NoteSplit, result); +} + +void OpenTuneAudioProcessorEditor::announceParameterEdit(AudioEditingScheme::ParameterId id, + const AudioEditingScheme::ParameterEditResult& result) +{ + // Only while a panel control has focus (keyboard use). Arrow changes arrive here once the + // keys stop (AccessibleKnob), typed values and Backspace at once. + auto* focused = juce::Component::getCurrentlyFocusedComponent(); + if (focused == nullptr || !parameterPanel_.isParentOf(focused)) + return; + const auto text = pianoRoll_.describeParameterEdit(id, result); + if (text.isNotEmpty()) + a11y::announce(*focused, text, a11y::SpeechQueue::keepAll); } void OpenTuneAudioProcessorEditor::toolSelected(int toolId) @@ -1331,14 +1429,23 @@ void OpenTuneAudioProcessorEditor::applyThemeToEditor(ThemeId themeId) void OpenTuneAudioProcessorEditor::undoRequested() { - if (processorRef_.getUndoManager().undo() != nullptr) + // Accessibility: sighted users see what came back; tell screen readers which action was undone. + if (auto* action = processorRef_.getUndoManager().undo()) { syncContentProjectionToPianoRoll(); + a11y::announce(pianoRoll_, Loc::format(LOC_RAW("Undone: {0}"), action->getDescription())); + } else { + a11y::announce(pianoRoll_, LOC_RAW("Nothing to undo")); + } } void OpenTuneAudioProcessorEditor::redoRequested() { - if (processorRef_.getUndoManager().redo() != nullptr) + if (auto* action = processorRef_.getUndoManager().redo()) { syncContentProjectionToPianoRoll(); + a11y::announce(pianoRoll_, Loc::format(LOC_RAW("Redone: {0}"), action->getDescription())); + } else { + a11y::announce(pianoRoll_, LOC_RAW("Nothing to redo")); + } } void OpenTuneAudioProcessorEditor::mouseTrailThemeChanged(MouseTrailConfig::TrailTheme theme) @@ -1496,8 +1603,31 @@ void OpenTuneAudioProcessorEditor::recordRequested() return; } - if (refreshed == 0) + if (refreshed == 0) { + // The audio is read but OpenDyne has no notes (the auto read ran in the wrong + // scheme, or its notes were removed): pressing Read again was a dead end + // (user test), so make the notes from the existing pitch, as the first read does. + const auto projections = dc->getPlaybackRegionProjectionsFor( + std::vector{targetPlaybackRegion}); + if (pianoRoll_.isOpenDyne() && !projections.empty() + && projections.front().contentKey.isValid()) { + const auto key = projections.front().contentKey; + const auto snap = processorRef_.getContentSnapshot(key); + if (snap != nullptr && snap->originalF0State == OriginalF0State::Ready + && snap->notes.empty() + && contentCommands_->generateNotesOnly(key, pianoRoll_.getCurrentAutoTuneParams())) { + syncContentProjectionToPianoRoll(); + const auto after = processorRef_.getContentSnapshot(key); + a11y::announce(pianoRoll_, Loc::format(LOC_RAW("Notes made: {0}"), + juce::String(after != nullptr ? static_cast(after->notes.size()) : 0))); + return; + } + } + // This audio was already read and is unchanged: nothing visible happens, and without + // a message it is unclear whether the button worked. + a11y::announce(pianoRoll_, LOC_RAW("Audio already read")); return; + } AppLogger::log("ReadAudio: refreshed " + juce::String(refreshed) + " AudioModification(s) for scoped playback region"); @@ -1522,6 +1652,7 @@ void OpenTuneAudioProcessorEditor::recordRequested() else pendingNoteGenerationOnReady_.erase(targetKey); originalF0OverlayLatched_ = true; + a11y::announce(pianoRoll_, LOC_RAW("Processing audio"), a11y::SpeechQueue::keepAll); }); #endif } @@ -1636,9 +1767,13 @@ void OpenTuneAudioProcessorEditor::autoTuneRequested() &contentRoot_, LOC(kAutoDialog), result.message()); + } else { + // No dialog by design, but without sight the button seemed to do nothing. + a11y::announce(pianoRoll_, LOC_RAW("Already corrected")); } return; } + a11y::announce(pianoRoll_, LOC_RAW("AUTO correction applied")); } diff --git a/Source/Plugin/PluginEditor.h b/Source/Plugin/PluginEditor.h index 24cae7ee..e59ac217 100644 --- a/Source/Plugin/PluginEditor.h +++ b/Source/Plugin/PluginEditor.h @@ -70,6 +70,9 @@ class OpenTuneAudioProcessorEditor : public juce::AudioProcessorEditor, void vibratoDepthChanged(float value) override; void vibratoRateChanged(float value) override; void noteSplitChanged(float value) override; + // Accessibility: say what a knob change did, when it came from the keyboard. + void announceParameterEdit(AudioEditingScheme::ParameterId id, + const AudioEditingScheme::ParameterEditResult& result); void toolSelected(int toolId) override; void importAudioRequested() override; @@ -213,6 +216,11 @@ class OpenTuneAudioProcessorEditor : public juce::AudioProcessorEditor, // 读取音频后 latch:F0 提取 + note 生成全部完成前保持"正在处理音频"遮罩 bool originalF0OverlayLatched_ = false; std::vector originalF0OverlayTargetContentKeys_; + // Accessibility: "Rendering done" is spoken only for renders at least this long. + static constexpr juce::uint32 kRenderDoneSpeechMinMs = 1000; + bool renderBadgeWasShown_ = false; + int lastExternalEditAppliedCount_ = -1; + juce::uint32 renderStartedMs_ = 0; // Tracks last-seen notesRevision per active content so the timer // can pull fresh notes when an async note generator commits late. // Tracks last-seen ContentKey for revision baseline only (not session last-active). diff --git a/Source/Plugin/ReaperHostBridge.cpp b/Source/Plugin/ReaperHostBridge.cpp new file mode 100644 index 00000000..7e36c551 --- /dev/null +++ b/Source/Plugin/ReaperHostBridge.cpp @@ -0,0 +1,73 @@ +#include "ReaperHostBridge.h" + +#include + +namespace OpenTune { + +namespace { + +#if JUCE_WINDOWS +// Minimal COM-style view of the two VST3 interfaces involved, so no REAPER SDK or VST3 SDK +// header is needed. On Windows VST3 interfaces use the COM layout: FUnknown is +// queryInterface / addRef / release, IReaperHostApplication adds getReaperApi first +// (reaper_vst3_interfaces.h in the REAPER SDK). +struct FUnknownAbi +{ + virtual std::int32_t __stdcall queryInterface(const char* iid, void** object) = 0; + virtual std::uint32_t __stdcall addRef() = 0; + virtual std::uint32_t __stdcall release() = 0; +}; + +struct ReaperHostApplicationAbi : FUnknownAbi +{ + virtual void* __stdcall getReaperApi(const char* functionName) = 0; +}; + +// IID 79655E36-77EE-4267-A573-FEF74912C27C in the COM byte order VST3 uses on Windows: +// the first three groups little-endian, the rest as written. +constexpr char kReaperHostApplicationIid[16] = { + '\x36', '\x5E', '\x65', '\x79', '\xEE', '\x77', '\x67', '\x42', + '\xA5', '\x73', '\xFE', '\xF7', '\x49', '\x12', '\xC2', '\x7C' +}; +#endif + +} // namespace + +void ReaperHostBridge::setIHostApplication(Steinberg::FUnknown* host) +{ + getCursorPosition_ = nullptr; + getPlayPosition_ = nullptr; + getPlayState_ = nullptr; +#if JUCE_WINDOWS + if (host == nullptr) + return; + + void* found = nullptr; + auto* unknown = reinterpret_cast(host); + if (unknown->queryInterface(kReaperHostApplicationIid, &found) != 0 || found == nullptr) + return; // not REAPER + + auto* reaper = static_cast(found); + // REAPER API functions are plain C functions that live as long as REAPER, + // so the interface itself can be released right away. + getCursorPosition_ = reinterpret_cast(reaper->getReaperApi("GetCursorPosition")); + getPlayPosition_ = reinterpret_cast(reaper->getReaperApi("GetPlayPosition")); + getPlayState_ = reinterpret_cast(reaper->getReaperApi("GetPlayState")); + reaper->release(); +#else + juce::ignoreUnused(host); +#endif +} + +std::optional ReaperHostBridge::getTransport() const +{ + if (getCursorPosition_ == nullptr || getPlayPosition_ == nullptr || getPlayState_ == nullptr) + return std::nullopt; + Transport transport; + transport.playState = getPlayState_(); + transport.editCursor = getCursorPosition_(); + transport.playPosition = getPlayPosition_(); + return transport; +} + +} // namespace OpenTune diff --git a/Source/Plugin/ReaperHostBridge.h b/Source/Plugin/ReaperHostBridge.h new file mode 100644 index 00000000..eba1d6af --- /dev/null +++ b/Source/Plugin/ReaperHostBridge.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +namespace OpenTune { + +// REAPER gives VST3 plugins its own API (IReaperHostApplication). OpenTune uses it to know +// where the user is in the song: while the transport is stopped or paused REAPER does not +// report the position to the plugin, so keyboard paste, arrows and Shift+X would act at +// the place where playback last ran. In other hosts nothing is found and nothing changes. +class ReaperHostBridge final : public juce::VST3ClientExtensions +{ +public: + struct Transport + { + int playState = 0; // GetPlayState: bit 1 playing, 2 paused, 4 recording + double editCursor = 0.0; // project seconds + double playPosition = 0.0; // project seconds, the audible position + bool isRunning() const noexcept { return (playState & (1 | 4)) != 0; } + bool isPaused() const noexcept { return !isRunning() && (playState & 2) != 0; } + }; + + void setIHostApplication(Steinberg::FUnknown* host) override; + + // Empty in other hosts. + std::optional getTransport() const; + +private: + double (*getCursorPosition_)() = nullptr; + double (*getPlayPosition_)() = nullptr; + int (*getPlayState_)() = nullptr; +}; + +} // namespace OpenTune diff --git a/Source/PluginProcessor.cpp b/Source/PluginProcessor.cpp index fd604065..9ead9f97 100644 --- a/Source/PluginProcessor.cpp +++ b/Source/PluginProcessor.cpp @@ -1128,6 +1128,13 @@ OpenTuneAudioProcessor::~OpenTuneAudioProcessor() { stopTimer(); #endif +#if JucePlugin_Enable_ARA + // Before noteAudition_ goes away: the editor renderer may be another instance. + if (isBoundToARA()) + if (auto* dc = getDocumentController()) + dc->releaseKeyboardAudition(¬eAudition_, getEditorRenderer()); +#endif + // 析构最前段生命周期动作(此后再无异步任务访问裸 this): // 1) 关闭 completion gate:与持锁进入的 F0 commit / chunkSettled / 模型切换 // completion 回调互斥。已进入者完成后才置 closed;此后进入者持锁见 @@ -1600,6 +1607,9 @@ void OpenTuneAudioProcessor::didBindToARA() noexcept // override the DC's lease and break the ARA2 render path. With a local // CRS torn down above, the processor owns no render state at all when bound. + if (isEditorView()) + dc->setKeyboardAuditionSource(¬eAudition_); + AppLogger::logNoThrow("ARA: didBindToARA - DC owns its CRS lease; processor=" + juce::String::toHexString(reinterpret_cast(this)) + " dc=" + juce::String::toHexString(reinterpret_cast(dc)) @@ -3075,6 +3085,7 @@ void OpenTuneAudioProcessor::pollReturnedExternalEdit() externalEditSessionDir_ = juce::File(); externalEditContentKey_ = {}; externalEditCorruptCurveShown_ = false; + ++externalEditAppliedCount_; AppLogger::log("External edit returned and applied " + completedPath); } @@ -3200,10 +3211,14 @@ void OpenTuneAudioProcessor::mixAuditions(juce::AudioBuffer& buffer, int auto* dc = getDocumentController(); auto* editorRenderer = getEditorRenderer(); if (dc != nullptr && editorRenderer != nullptr && !isNonRealtime()) + { dc->mixNotePitchAuditionIfOwner(editorRenderer, buffer, numSamples, sampleRate); + dc->mixKeyboardAudition(editorRenderer, buffer, numSamples, sampleRate); + } return; } #endif + noteAudition_.mixIntoBuffer(buffer, numSamples, sampleRate); // 音符移调预览仅在实时处理时混入;离线(宿主 bounce/export)渲染静音。 if (!isNonRealtime()) notePitchAudition_.mixIntoBuffer(buffer, numSamples, sampleRate); diff --git a/Source/PluginProcessor.h b/Source/PluginProcessor.h index ad5c88fa..dfefa1d7 100644 --- a/Source/PluginProcessor.h +++ b/Source/PluginProcessor.h @@ -49,8 +49,10 @@ #include "Utils/SilentGapDetector.h" #include "Utils/TimeCoordinate.h" #include "Utils/UndoManager.h" +#include "Plugin/ReaperHostBridge.h" // declarations only; the .cpp is built for the plugin #include "Utils/VocoderModelWeight.h" #include "Utils/PianoKeyAudition.h" +#include "Utils/NoteAudition.h" #include "Audio/NotePitchAudition.h" #include "Utils/AppPreferences.h" #include "Utils/PlayHeadState.h" @@ -433,6 +435,7 @@ class OpenTuneAudioProcessor : public juce::AudioProcessor juce::File externalEditSessionDir_; ContentKey externalEditContentKey_; bool externalEditCorruptCurveShown_ = false; + int externalEditAppliedCount_ = 0; #endif @@ -625,6 +628,8 @@ class OpenTuneAudioProcessor : public juce::AudioProcessor { return externalEditSessionDir_.getFullPathName().isNotEmpty(); } + // Accessibility: grows on every applied external edit, so an open editor can speak it. + int getExternalEditAppliedCount() const noexcept { return externalEditAppliedCount_; } // 启动(或重新拉起)外部编辑会话;成功时处理器接管会话状态。 bool externalEditLaunchRequested(ContentKey key, const EditableContentSnapshot& snapshot); @@ -1003,6 +1008,21 @@ class OpenTuneAudioProcessor : public juce::AudioProcessor UndoManager& getUndoManager() { return undoManager_; } PianoKeyAudition& getPianoKeyAudition() { return pianoKeyAudition_; } + NoteAudition& getNoteAudition() { return noteAudition_; } +#if !JucePlugin_Build_Standalone + // Accessibility: REAPER's transport state and positions (see ReaperHostBridge). + juce::VST3ClientExtensions* getVST3ClientExtensions() override { return &reaperHost_; } + std::optional getReaperTransport() const { return reaperHost_.getTransport(); } +#else + std::optional getReaperTransport() const { return std::nullopt; } +#endif + // Rendered (corrected) audio of a content. In ARA it is owned by the DocumentController, + // not by this plugin instance, so resolve it through the shared service lookup. + std::shared_ptr getReadableRenderCache(ContentKey key) const + { + const auto* renderService = resolveReadableContentRenderService(key); + return renderService != nullptr ? renderService->getRenderCache(key) : nullptr; + } /** * 音符移调试听(UI 线程调用):按给定时间窗与目标频率请求一次 @@ -1015,7 +1035,11 @@ class OpenTuneAudioProcessor : public juce::AudioProcessor private: UndoManager undoManager_; PianoKeyAudition pianoKeyAudition_; + NoteAudition noteAudition_; NotePitchAudition notePitchAudition_; +#if !JucePlugin_Build_Standalone + ReaperHostBridge reaperHost_; +#endif #if JucePlugin_Enable_ARA juce::ARAPlaybackRegion* notePitchAuditionTargetRegion_ = nullptr; #endif diff --git a/Source/Standalone/PluginEditor.cpp b/Source/Standalone/PluginEditor.cpp index b5673185..7c2f2b01 100644 --- a/Source/Standalone/PluginEditor.cpp +++ b/Source/Standalone/PluginEditor.cpp @@ -799,6 +799,8 @@ OpenTuneAudioProcessorEditor::OpenTuneAudioProcessorEditor(OpenTuneAudioProcesso pianoRoll_.setProcessor(&processorRef_); pianoRoll_.setContentCommands(processorRef_.getContentCommands()); pianoRoll_.setPianoKeyAudition(&processorRef_.getPianoKeyAudition()); + pianoRoll_.setNoteAudition(&processorRef_.getNoteAudition()); + pianoRoll_.setRenderCacheProvider([this](ContentKey key) { return processorRef_.getReadableRenderCache(key); }); { const int activeTrack = getStandaloneActiveTrack(processorRef_); const int placementIndex = getStandaloneSelectedPlacementIndex(processorRef_, activeTrack); diff --git a/Source/Standalone/UI/ParameterPanel.cpp b/Source/Standalone/UI/ParameterPanel.cpp index cb343786..bdefd1f2 100644 --- a/Source/Standalone/UI/ParameterPanel.cpp +++ b/Source/Standalone/UI/ParameterPanel.cpp @@ -440,7 +440,9 @@ ParameterPanel::ParameterPanel() setupLargeKnob(retuneSpeedSlider_, 0.0, 100.0, PitchControlConfig::kDefaultRetuneSpeedPercent, "%"); retuneSpeedSlider_.getProperties().set("minimalKnob", true); - retuneSpeedSlider_.onValueChange = [this] { onRetuneSpeedChanged(); }; + // Accessibility: key steps (normal, Alt, Page). onCommit waits until the keys stop. + retuneSpeedSlider_.setKeySteps(1.0, 0.1, 10.0); + retuneSpeedSlider_.onCommit = [this] { onRetuneSpeedChanged(); }; contentComponent_.addAndMakeVisible(retuneSpeedSlider_); retuneSpeedSlider_.setTooltip(LOC(kTooltipRetuneSpeed)); @@ -450,7 +452,8 @@ ParameterPanel::ParameterPanel() setupLargeKnob(vibratoDepthSlider_, 0.0, 100.0, PitchControlConfig::kDefaultVibratoDepth, "%"); vibratoDepthSlider_.getProperties().set("minimalKnob", true); - vibratoDepthSlider_.onValueChange = [this] { onVibratoDepthChanged(); }; + vibratoDepthSlider_.setKeySteps(1.0, 0.1, 10.0); + vibratoDepthSlider_.onCommit = [this] { onVibratoDepthChanged(); }; contentComponent_.addAndMakeVisible(vibratoDepthSlider_); vibratoDepthSlider_.setTooltip(LOC(kTooltipVibratoDepth)); @@ -460,7 +463,8 @@ ParameterPanel::ParameterPanel() setupLargeKnob(vibratoRateSlider_, 3.0, 12.0, PitchControlConfig::kDefaultVibratoRateHz, " Hz"); vibratoRateSlider_.getProperties().set("minimalKnob", true); - vibratoRateSlider_.onValueChange = [this] { onVibratoRateChanged(); }; + vibratoRateSlider_.setKeySteps(0.1, 0.01, 1.0); + vibratoRateSlider_.onCommit = [this] { onVibratoRateChanged(); }; contentComponent_.addAndMakeVisible(vibratoRateSlider_); vibratoRateSlider_.setTooltip(LOC(kTooltipVibratoRate)); @@ -477,7 +481,8 @@ ParameterPanel::ParameterPanel() // NoteSplit 触发范围重分割(拓扑重建+undo 事务),代价远高于其他参数旋钮: // 拖动期间不逐格提交,释放时才通知一次(滚轮/键盘无拖拽语义,逐次提交,频率低可接受)。 noteSplitSlider_.setChangeNotificationOnlyOnRelease(true); - noteSplitSlider_.onValueChange = [this] { onNoteSplitChanged(); }; + noteSplitSlider_.setKeySteps(5.0, 1.0, 20.0); + noteSplitSlider_.onCommit = [this] { onNoteSplitChanged(); }; contentComponent_.addAndMakeVisible(noteSplitSlider_); noteSplitSlider_.setTooltip(LOC(kTooltipNoteSplit)); @@ -526,7 +531,7 @@ ParameterPanel::ParameterPanel() // Pitch Shift action button pitchShiftButton_ = std::make_unique(LOC(kPitchShift) + "..."); - pitchShiftButton_->setTooltip(LOC(kPitchShift)); + // No tooltip: it repeated the button text, and NVDA read "Pitch Shift..., Pitch Shift". pitchShiftButton_->getProperties().set(UIColors::auroraChromeIntensityProperty, kAuroraSidebarChromeIntensity); pitchShiftButton_->onClick = [this] { @@ -603,10 +608,54 @@ ParameterPanel::ParameterPanel() // 滚轮调参:ComboBox 在 JUCE 中默认关闭,此处显式开启;鼠标在控件上时事件被其消费,Viewport 不滚 pitchGridSelector_.setScrollWheelEnabled(true); contentComponent_.addChildComponent(pitchGridSelector_); + + // Accessibility: the viewport itself took Tab focus and NVDA read it + // as "unknown". Controls inside it remain reachable with Tab. + viewport_.setWantsKeyboardFocus(false); + // Scroll bars are mouse-only and NVDA read them as "scroll bar 0". + viewport_.getVerticalScrollBar().setAccessible(false); + viewport_.getHorizontalScrollBar().setAccessible(false); + // Knob captions and section headers: JUCE exposes a label's text both as name and as + // value, so NVDA read them twice. The knobs now carry the names themselves. + for (auto* caption : { &pitchCorrectionHeader_, &retuneSpeedLabel_, &vibratoDepthLabel_, + &vibratoRateLabel_, ¬eSplitLabel_, &toolsHeader_ }) + caption->setAccessible(false); + applyAccessibilityTitles(); + juce::Desktop::getInstance().addFocusChangeListener(this); +} + +// Screen reader names: knob captions are separate Labels, so the value boxes +// and tool buttons (internal names like PitchModulation) were read without a proper name. +void ParameterPanel::applyAccessibilityTitles() +{ + // The value editor picks up the knob name too (see LargeKnobLookAndFeel::createSliderTextBox). + retuneSpeedSlider_.setTitle(LOC(kRetuneSpeed)); + vibratoDepthSlider_.setTitle(LOC(kVibratoDepth)); + vibratoRateSlider_.setTitle(LOC(kVibratoRate)); + noteSplitSlider_.setTitle(LOC(kNoteSplit)); + + const auto titleButton = [](const std::unique_ptr& button, const juce::String& title) { + if (button != nullptr) + button->setTitle(title); + }; + titleButton(selectToolButton_, LOC(kToolODSelect)); + titleButton(drawNoteToolButton_, LOC(kTooltipDrawNote)); + titleButton(lineAnchorToolButton_, LOC(kTooltipLineAnchor)); + titleButton(handDrawToolButton_, LOC(kTooltipHandDraw)); + titleButton(eraserToolButton_, LOC(kEraser)); + titleButton(timeToolButton_, LOC_RAW("Time tool")); + titleButton(pitchToolButton_, LOC(kToolODPitch)); + titleButton(pitchModulationToolButton_, LOC(kToolODPitchModulation)); + titleButton(pitchDriftToolButton_, LOC(kToolODPitchDrift)); + titleButton(volumeEnvelopeToolButton_, LOC(kToolODVolumeEnvelope)); + titleButton(scissorsToolButton_, LOC(kToolODScissors)); + + pitchGridSelector_.setTitle(LOC_RAW("Pitch snap")); } ParameterPanel::~ParameterPanel() { + juce::Desktop::getInstance().removeFocusChangeListener(this); retuneSpeedSlider_.setLookAndFeel(nullptr); vibratoDepthSlider_.setLookAndFeel(nullptr); vibratoRateSlider_.setLookAndFeel(nullptr); @@ -938,6 +987,8 @@ void ParameterPanel::applyTheme() void ParameterPanel::refreshLocalizedText() { + applyAccessibilityTitles(); + // 更新 Pitch Correction 部分 pitchCorrectionHeader_.setText(LOC(kPitchCorrection), juce::dontSendNotification); retuneSpeedLabel_.setText(LOC(kRetuneSpeed), juce::dontSendNotification); @@ -948,7 +999,6 @@ void ParameterPanel::refreshLocalizedText() // 更新 Tools 部分 toolsHeader_.setText(LOC(kTools), juce::dontSendNotification); if (pitchShiftButton_) { - pitchShiftButton_->setTooltip(LOC(kPitchShift)); setPitchShiftIndicator(pitchShiftSemitone_, pitchShiftCents_); } pitchGridSelector_.changeItemText(1, LOC(kNoSnap)); @@ -1190,6 +1240,18 @@ void ParameterPanel::revealControl(juce::Component& control) viewport_.setViewPosition(viewport_.getViewPositionX(), targetY); } +void ParameterPanel::globalFocusChanged(juce::Component* focusedComponent) +{ + // revealControl works with direct children of the content, so climb up from + // inner parts such as a knob value editor. + for (auto* c = focusedComponent; c != nullptr; c = c->getParentComponent()) { + if (c->getParentComponent() == &contentComponent_) { + revealControl(*c); + return; + } + } +} + int ParameterPanel::getContentScrollY() const { return viewport_.getViewPositionY(); } void ParameterPanel::setContentScrollY(int y) diff --git a/Source/Standalone/UI/ParameterPanel.h b/Source/Standalone/UI/ParameterPanel.h index d3ec689d..75cc4ce8 100644 --- a/Source/Standalone/UI/ParameterPanel.h +++ b/Source/Standalone/UI/ParameterPanel.h @@ -16,6 +16,8 @@ #include "OpenTuneLookAndFeel.h" #include "UIColors.h" #include "ToolIds.h" +#include "../../Utils/AccessibleComboBox.h" +#include "../../Utils/AccessibleKnob.h" namespace OpenTune { @@ -38,6 +40,13 @@ class LargeKnobLookAndFeel : public OpenTuneLookAndFeel { auto* label = OpenTuneLookAndFeel::createSliderTextBox(slider); label->setFont(UIColors::getLabelFont(14.0f)); + // Tab focuses the TextEditor that the Label opens, and it has no name + // (NVDA: "edit selected 15.00%"). Give it the knob name when it opens. + juce::Component::SafePointer safeSlider(&slider); + label->onEditorShow = [label, safeSlider] { + if (auto* editor = label->getCurrentTextEditor()) + editor->setTitle(safeSlider != nullptr ? safeSlider->getTitle() : juce::String()); + }; return label; } @@ -46,7 +55,8 @@ class LargeKnobLookAndFeel : public OpenTuneLookAndFeel float rotaryEndAngle, juce::Slider& slider) override; }; -class ParameterPanel : public juce::Component +class ParameterPanel : public juce::Component, + private juce::FocusChangeListener { public: struct AutoButtonPresentation { @@ -152,6 +162,7 @@ class ParameterPanel : public juce::Component void setupHeader(juce::Label& label, const juce::String& text); void setupLabel(juce::Label& label, const juce::String& text); void setupLargeKnob(juce::Slider& slider, double min, double max, double defaultVal, const juce::String& suffix); + void applyAccessibilityTitles(); /** 以内容组件本地坐标排布全部控件;返回由实际布局 bottom + 底部内边距得出的内容高度。 */ int layoutContent(int width); @@ -179,17 +190,21 @@ class ParameterPanel : public juce::Component FadingViewport viewport_; ContentComponent contentComponent_; + // Tab can land on a control scrolled out of the panel (NVDA reported Pitch snap as + // "offscreen"): scroll it into view. + void globalFocusChanged(juce::Component* focusedComponent) override; + // Pitch Correction Section juce::Label pitchCorrectionHeader_; juce::Label retuneSpeedLabel_; - juce::Slider retuneSpeedSlider_; + a11y::AccessibleKnob retuneSpeedSlider_; juce::Label vibratoDepthLabel_; - juce::Slider vibratoDepthSlider_; + a11y::AccessibleKnob vibratoDepthSlider_; juce::Label vibratoRateLabel_; - juce::Slider vibratoRateSlider_; + a11y::AccessibleKnob vibratoRateSlider_; juce::Label noteSplitLabel_; - juce::Slider noteSplitSlider_; + a11y::AccessibleKnob noteSplitSlider_; // Tools Section juce::Label toolsHeader_; @@ -211,7 +226,7 @@ class ParameterPanel : public juce::Component AutoButtonPresentation autoButtonPresentation_; std::unique_ptr pitchShiftButton_; // OpenDyne Pitch Grid 全局开关(No Snap / Chromatic / Key Scale) - juce::ComboBox pitchGridSelector_; + a11y::AccessibleComboBox pitchGridSelector_; int pitchShiftSemitone_ = 0; int pitchShiftCents_ = 0; diff --git a/Source/Standalone/UI/PianoRoll/EqPopupComponent.cpp b/Source/Standalone/UI/PianoRoll/EqPopupComponent.cpp index 14df0f47..a2bd033b 100644 --- a/Source/Standalone/UI/PianoRoll/EqPopupComponent.cpp +++ b/Source/Standalone/UI/PianoRoll/EqPopupComponent.cpp @@ -10,7 +10,9 @@ #include "../UIColors.h" #include "../../../Utils/LocalizationManager.h" #include "../../../Utils/EqFilterEditOps.h" +#include "../../../Utils/ScreenReaderAnnouncer.h" #include +#include namespace OpenTune { @@ -67,6 +69,64 @@ EqPopupComponent::EqPopupComponent() qSlider_.onValueChange = [this] { cardSliderChanged(2); }; addAndMakeVisible(qSlider_); qSlider_.setVisible(false); + + // Accessibility: the window itself is the keyboard grid. A mouse click must not take + // focus from the notes, so mouse users keep their piano roll keys. + setWantsKeyboardFocus(true); + setMouseClickGrabsKeyboardFocus(false); + + frequencySlider_.setTitle(LOC_RAW("Frequency")); + gainSlider_.setTitle(LOC_RAW("Gain")); + qSlider_.setTitle("Q"); + for (auto* knob : { &frequencySlider_, &gainSlider_, &qSlider_ }) + { + knob->setWantsKeyboardFocus(true); + knob->setMouseClickGrabsKeyboardFocus(false); + knob->onKey = [this, knob](const juce::KeyPress& key) { return handleKnobKey(*knob, key); }; + } + + // Type list over the painted type buttons: invisible and click-through, the painted + // buttons keep working for the mouse. + for (int i = 0; i <= static_cast(EqSettings::kMaxFilterType); ++i) + typeBox_.addItem(filterTypeName(static_cast(i)), i + 1); + typeBox_.setTitle(LOC_RAW("Type")); + typeBox_.setWantsKeyboardFocus(true); + typeBox_.setAlpha(0.0f); + typeBox_.setInterceptsMouseClicks(false, false); + typeBox_.onKey = [this](const juce::KeyPress& key) { return handleTypeKey(key); }; + typeBox_.onChange = [this] { + if (!updatingCardControls_ && typeBox_.getSelectedId() > 0) + setFilterType(cardBand_, static_cast(typeBox_.getSelectedId() - 1)); + }; + addChildComponent(typeBox_); + + // Remove confirmation: real buttons for the screen reader over the painted dialog. + confirmPanel_.setTitle(LOC_RAW("Remove EQ?")); + confirmPanel_.setAlpha(0.0f); + confirmPanel_.setInterceptsMouseClicks(false, false); + confirmPanel_.onKey = [this](const juce::KeyPress& key) { return handleConfirmKey(key); }; + confirmButton_.setButtonText(LOC_RAW("Confirm")); + // The question goes first in the button's name ("Remove EQ? Confirm, button"): NVDA skips + // the group name, and an announcement after the focus came after "Confirm button". + confirmButton_.setTitle(LOC_RAW("Remove EQ?") + " " + LOC_RAW("Confirm")); + cancelButton_.setButtonText(LOC(kCancel)); + dontShowToggle_.setButtonText(LOC_RAW("Don't show again")); + confirmButton_.onClick = [this] { requestRemoveEq(); }; + cancelButton_.onClick = [this] { + dismissRemoveConfirmation(); + keyRow_ = KeyRow::RemoveEq; + focusGrid(); + }; + dontShowToggle_.onClick = [this] { + suppressRemoveConfirmation_ = dontShowToggle_.getToggleState(); + if (onRemoveConfirmationSuppressed) + onRemoveConfirmationSuppressed(suppressRemoveConfirmation_); + repaint(); + }; + confirmPanel_.addAndMakeVisible(confirmButton_); + confirmPanel_.addAndMakeVisible(cancelButton_); + confirmPanel_.addAndMakeVisible(dontShowToggle_); + addChildComponent(confirmPanel_); } EqPopupComponent::~EqPopupComponent() @@ -304,6 +364,7 @@ void EqPopupComponent::configureCardControls(int filterIndex) gainSlider_.setEnabled(hasGain); gainSlider_.setAlpha(hasGain ? 1.0f : 0.3f); gainSlider_.setValue(f.gainDb, juce::dontSendNotification); + typeBox_.setSelectedId(static_cast(f.type) + 1, juce::dontSendNotification); // Q 始终显示 qSlider_.setValue(f.q, juce::dontSendNotification); @@ -320,6 +381,7 @@ void EqPopupComponent::configureCardControls(int filterIndex) frequencySlider_.setVisible(true); gainSlider_.setVisible(true); qSlider_.setVisible(true); + typeBox_.setVisible(true); layoutCardControls(); } @@ -329,6 +391,7 @@ void EqPopupComponent::hideCardControls() frequencySlider_.setVisible(false); gainSlider_.setVisible(false); qSlider_.setVisible(false); + typeBox_.setVisible(false); } void EqPopupComponent::layoutCardControls() @@ -346,6 +409,11 @@ void EqPopupComponent::layoutCardControls() slider->setBounds(static_cast(x), static_cast(sliderY), static_cast(kCardColumnWidth), static_cast(kCardSliderHeight)); } + + // The type list covers the whole painted row of type buttons. + const auto firstType = cardFilterTypeButtonBounds(card, 0); + const auto lastType = cardFilterTypeButtonBounds(card, static_cast(EqSettings::kMaxFilterType)); + typeBox_.setBounds(firstType.getUnion(lastType).getSmallestIntegerContainer()); } void EqPopupComponent::cardSliderChanged(int parameterIndex) @@ -372,7 +440,12 @@ void EqPopupComponent::cardSliderChanged(int parameterIndex) renderer_.setSettings(settings_); layoutCardControls(); - commitSettings(); + // Arrow keys change the knob many times a second: commit once they stop, + // so a held key is one undo step and one render. + if (keyboardAdjusting_) + scheduleCommit(); + else + commitSettings(); repaint(); } @@ -875,6 +948,7 @@ void EqPopupComponent::mouseDown(const juce::MouseEvent& event) if (event.mods.isRightButtonDown()) return; + flushPendingCommit(); const auto pos = event.position; // Remove 确认弹窗交互 @@ -897,6 +971,7 @@ void EqPopupComponent::mouseDown(const juce::MouseEvent& event) if (checkRect.contains(pos)) { suppressRemoveConfirmation_ = !suppressRemoveConfirmation_; + dontShowToggle_.setToggleState(suppressRemoveConfirmation_, juce::dontSendNotification); if (onRemoveConfirmationSuppressed) onRemoveConfirmationSuppressed(suppressRemoveConfirmation_); repaint(); @@ -956,16 +1031,7 @@ void EqPopupComponent::mouseDown(const juce::MouseEvent& event) if (typeIdx >= 0 && typeIdx < 5 && cardBand_ >= 0 && cardBand_ < static_cast(settings_.filters.size())) { - auto& f = settings_.filters[cardBand_]; - const auto newType = static_cast(typeIdx); - if (f.type != newType) - { - setEqFilterType(f, newType); - renderer_.setSettings(settings_); - configureCardControls(cardBand_); - commitSettings(); - repaint(); - } + setFilterType(cardBand_, static_cast(typeIdx)); return; } @@ -996,9 +1062,7 @@ void EqPopupComponent::mouseDown(const juce::MouseEvent& event) } else { - showingRemoveConfirmation_ = true; - hideCardControls(); - repaint(); + showRemoveConfirmation(); } return; case ButtonId::Minimize: @@ -1277,6 +1341,9 @@ void EqPopupComponent::timerCallback() renderer_.advanceSpectrumColorCycle(dt); updateHoverBandFade(dt); + if (commitPending_ && juce::Time::getMillisecondCounterHiRes() >= commitDeadlineMs_) + flushPendingCommit(); + // 频谱动画每帧刷新(60fps 流畅动画) repaint(); } @@ -1401,8 +1468,693 @@ bool EqPopupComponent::removeFilterAt(int index) void EqPopupComponent::dismissRemoveConfirmation() { showingRemoveConfirmation_ = false; + confirmPanel_.setVisible(false); + updateCardState(); + repaint(); +} + +void EqPopupComponent::showRemoveConfirmation() +{ + showingRemoveConfirmation_ = true; + hideCardControls(); + dontShowToggle_.setToggleState(suppressRemoveConfirmation_, juce::dontSendNotification); + // Same rectangles as the painted dialog in paint() and the clicks in mouseDown(). + const auto dialog = removeDialogBounds(); + confirmPanel_.setBounds(dialog.getSmallestIntegerContainer()); + const float w = dialog.getWidth(); + const float h = dialog.getHeight(); + dontShowToggle_.setBounds(juce::Rectangle(10.0f, 28.0f, w - 20.0f, 14.0f).getSmallestIntegerContainer()); + confirmButton_.setBounds(juce::Rectangle(10.0f, h - 24.0f, 80.0f, 18.0f).getSmallestIntegerContainer()); + cancelButton_.setBounds(juce::Rectangle(w - 90.0f, h - 24.0f, 80.0f, 18.0f).getSmallestIntegerContainer()); + confirmPanel_.setVisible(true); + repaint(); +} + +juce::Rectangle EqPopupComponent::removeDialogBounds() const +{ + const auto area = getLocalBounds().toFloat(); + const float dialogW = 200.0f; + const float dialogH = 70.0f; + return { (area.getWidth() - dialogW) * 0.5f, (area.getHeight() - dialogH) * 0.5f, dialogW, dialogH }; +} + +void EqPopupComponent::setFilterType(int filterIndex, EqFilterType newType) +{ + if (filterIndex < 0 || filterIndex >= static_cast(settings_.filters.size())) + return; + + auto& f = settings_.filters[filterIndex]; + if (f.type == newType) + return; + + setEqFilterType(f, newType); + renderer_.setSettings(settings_); + configureCardControls(filterIndex); + commitSettings(); + repaint(); +} + +// ============================================================================ +// Accessibility: keyboard model +// ============================================================================ + +namespace { + +// Keys with Ctrl or Alt that the window does not use go on to the host (Alt+F4, Ctrl+S). +// Navigation and edit keys stay here: in the piano roll they would change the notes +// behind the window, and undo would leave the window showing stale values. +bool passesToHost(const juce::KeyPress& key) +{ + const auto mods = key.getModifiers(); + if (!mods.isCtrlDown() && !mods.isAltDown() && !mods.isCommandDown()) + return false; + + const int code = key.getKeyCode(); + for (int kept : { juce::KeyPress::upKey, juce::KeyPress::downKey, juce::KeyPress::leftKey, + juce::KeyPress::rightKey, juce::KeyPress::homeKey, juce::KeyPress::endKey, + juce::KeyPress::pageUpKey, juce::KeyPress::pageDownKey, juce::KeyPress::deleteKey, + juce::KeyPress::insertKey, juce::KeyPress::returnKey, juce::KeyPress::backspaceKey, + juce::KeyPress::tabKey }) + if (code == kept) + return false; + + if (mods.isCtrlDown() || mods.isCommandDown()) + { + const auto letter = juce::CharacterFunctions::toUpperCase(static_cast(code)); + for (juce::juce_wchar kept : { 'Z', 'Y', 'A', 'C', 'V', 'X', 'D' }) + if (letter == kept) + return false; + } + return true; +} + +bool isPlainKey(const juce::KeyPress& key, int code) +{ + return key.getKeyCode() == code && !key.getModifiers().isAnyModifierKeyDown(); +} + +} // namespace + +juce::String EqPopupComponent::filterTypeName(EqFilterType type) +{ + switch (type) + { + case EqFilterType::LowCut: return LOC_RAW("Low cut"); + case EqFilterType::LowShelf: return LOC_RAW("Low shelf"); + case EqFilterType::Peak: return LOC_RAW("Peak"); + case EqFilterType::HighShelf: return LOC_RAW("High shelf"); + case EqFilterType::HighCut: return LOC_RAW("High cut"); + } + return {}; +} + +std::unique_ptr EqPopupComponent::createAccessibilityHandler() +{ + // The title is computed on request, so NVDA+Up Arrow reads the current band and row. + class EqAccessibilityHandler final : public juce::AccessibilityHandler { + public: + explicit EqAccessibilityHandler(EqPopupComponent& owner) + : juce::AccessibilityHandler(owner, juce::AccessibilityRole::list), owner_(owner) {} + + juce::String getTitle() const override + { + juce::String title = "EQ"; + if (!owner_.settings_.active) + title << ", " << LOC_RAW("bypassed"); + const auto line = owner_.describeBandAndRow(); + if (line.isNotEmpty()) + title << ", " << line; + return title; + } + + private: + EqPopupComponent& owner_; + }; + + return std::make_unique(*this); +} + +void EqPopupComponent::startKeyboardEditing() +{ + keyRow_ = KeyRow::Type; + ensureKeyBand(); + focusGrid(); +} + +int EqPopupComponent::keyBand() const +{ + const int count = static_cast(settings_.filters.size()); + if (count == 0) + return -1; + return juce::jlimit(0, count - 1, selectedFilterIndex_); +} + +void EqPopupComponent::ensureKeyBand() +{ + // The small preview has no band card; the keyboard always works in the full editor. + if (isPreview_) + toggleMaximize(); + if (showingRemoveConfirmation_) + return; + + const int band = keyBand(); + if (band >= 0 && (selectedFilterIndex_ != band || cardBand_ != band)) + { + selectedFilterIndex_ = band; + updateCardState(); + repaint(); + } +} + +void EqPopupComponent::selectKeyBand(int index) +{ + selectedFilterIndex_ = index; + updateCardState(); + repaint(); + a11y::announce(*this, describeBandAndRow()); +} + +void EqPopupComponent::focusGrid() +{ + // Grabbing focus that is already here makes NVDA repeat the whole title. + if (!hasKeyboardFocus(false)) + grabKeyboardFocus(); +} + +juce::String EqPopupComponent::describeRow(KeyRow row) const +{ + const int band = keyBand(); + if (band < 0) + return {}; + + const auto& f = settings_.filters[static_cast(band)]; + const auto onOff = [](bool on) { return on ? LOC_RAW("On") : LOC(kOff); }; + switch (row) + { + case KeyRow::Type: + return LOC_RAW("Type") + ", " + filterTypeName(f.type); + case KeyRow::Frequency: + return LOC_RAW("Frequency") + ", " + juce::String(juce::roundToInt(f.frequencyHz)) + " Hz"; + case KeyRow::Gain: + { + if (f.type == EqFilterType::LowCut || f.type == EqFilterType::HighCut) + return Loc::format(LOC_RAW("Gain, not used by {0}"), filterTypeName(f.type)); + // Round first so a tiny negative value is not read as "minus 0.0". + float gain = std::round(f.gainDb * 10.0f) / 10.0f; + if (std::abs(gain) < 0.05f) + gain = 0.0f; + const juce::String number = juce::String(gain > 0.0f ? "+" : "") + juce::String(gain, 1); + return LOC_RAW("Gain") + ", " + Loc::format(LOC_RAW("{0} dB"), number); + } + case KeyRow::Q: + return "Q, " + juce::String(f.q, 2); + case KeyRow::BypassBand: + return LOC_RAW("Bypass band") + ", " + onOff(f.bypassed); + case KeyRow::RemoveBand: + return LOC_RAW("Remove band"); + case KeyRow::AddBand: + return LOC_RAW("Add band"); + case KeyRow::BypassEq: + return LOC_RAW("Bypass EQ") + ", " + onOff(!settings_.active); + case KeyRow::RemoveEq: + return LOC_RAW("Remove EQ"); + case KeyRow::Count: + break; + } + return {}; +} + +juce::String EqPopupComponent::describeAllBands() const +{ + juce::String text = Loc::format(LOC_RAW("Bands: {0}"), juce::String(static_cast(settings_.filters.size()))); + if (!settings_.active) + text << ", " << LOC_RAW("EQ bypassed"); + for (size_t i = 0; i < settings_.filters.size(); ++i) + { + const auto& f = settings_.filters[i]; + text << ". " << juce::String(static_cast(i) + 1) << ": " << filterTypeName(f.type) + << ", " << juce::String(juce::roundToInt(f.frequencyHz)) << " Hz"; + if (f.type != EqFilterType::LowCut && f.type != EqFilterType::HighCut) + { + const float gain = std::abs(f.gainDb) < 0.05f ? 0.0f : f.gainDb; + text << ", " << Loc::format(LOC_RAW("{0} dB"), juce::String(gain > 0.0f ? "+" : "") + juce::String(gain, 1)); + } + text << ", Q " << juce::String(f.q, 2); + if (f.bypassed) + text << ", " << LOC_RAW("bypassed"); + } + return text; +} + +juce::String EqPopupComponent::describeBandAndRow() const +{ + const int band = keyBand(); + if (band < 0) + return {}; + + const auto& f = settings_.filters[static_cast(band)]; + juce::String text = Loc::format(LOC_RAW("Band {0} of {1}"), juce::String(band + 1), + juce::String(static_cast(settings_.filters.size()))); + // The Type row says the type itself. + if (keyRow_ != KeyRow::Type) + text << ", " << filterTypeName(f.type); + if (f.bypassed) + text << ", " << LOC_RAW("bypassed"); + text << ", " << describeRow(keyRow_); + return text; +} + +bool EqPopupComponent::keyPressed(const juce::KeyPress& key) +{ + flushPendingCommit(); + if (passesToHost(key)) + return false; + // While the confirmation is open its buttons own the keys. + if (showingRemoveConfirmation_) + return true; + + const int code = key.getKeyCode(); + const auto mods = key.getModifiers(); + const bool isButtonRow = keyRow_ >= KeyRow::BypassBand; + + if (code == juce::KeyPress::escapeKey) + { + requestClose(); + return true; + } + if (code == juce::KeyPress::spaceKey) + { + if (isButtonRow && !mods.isAnyModifierKeyDown()) + { + activateKeyRow(); + return true; + } + return false; // play/stop in the piano roll, to hear the result + } + + ensureKeyBand(); + const int count = static_cast(settings_.filters.size()); + const int band = keyBand(); + + if (isPlainKey(key, juce::KeyPress::leftKey) || isPlainKey(key, juce::KeyPress::rightKey) + || isPlainKey(key, juce::KeyPress::homeKey) || isPlainKey(key, juce::KeyPress::endKey)) + { + const int target = code == juce::KeyPress::leftKey ? band - 1 + : code == juce::KeyPress::rightKey ? band + 1 + : code == juce::KeyPress::homeKey ? 0 + : count - 1; + // At the edge nothing changes and nothing is said. + if (target >= 0 && target < count && target != band) + selectKeyBand(target); + return true; + } + if (isPlainKey(key, juce::KeyPress::upKey) || isPlainKey(key, juce::KeyPress::downKey)) + { + const int row = static_cast(keyRow_) + (code == juce::KeyPress::upKey ? -1 : 1); + if (row >= 0 && row < static_cast(KeyRow::Count)) + { + keyRow_ = static_cast(row); + a11y::announce(*this, describeRow(keyRow_)); + } + return true; + } + if (code == juce::KeyPress::tabKey && !mods.isShiftDown()) + { + enterKeyRow(); + return true; + } + if (isPlainKey(key, juce::KeyPress::returnKey)) + { + if (isButtonRow) + activateKeyRow(); + else + enterKeyRow(); + return true; + } + if (isPlainKey(key, juce::KeyPress::insertKey)) + { + addBandFromKeyboard(); + return true; + } + if (isPlainKey(key, juce::KeyPress::deleteKey)) + { + removeBandFromKeyboard(); + return true; + } + // I: all bands at once, like I on a note reads all its details. + if ((code == 'I' || code == 'i') && !mods.isAnyModifierKeyDown()) + { + a11y::announce(*this, describeAllBands()); + return true; + } + // Everything else stays in the window, so it cannot edit the notes behind it. + return true; +} + +void EqPopupComponent::enterKeyRow() +{ + ensureKeyBand(); + switch (keyRow_) + { + case KeyRow::Type: + typeBox_.grabKeyboardFocus(); + break; + case KeyRow::Frequency: + frequencySlider_.grabKeyboardFocus(); + break; + case KeyRow::Gain: + if (gainSlider_.isEnabled()) + gainSlider_.grabKeyboardFocus(); + else + a11y::announce(*this, describeRow(KeyRow::Gain)); + break; + case KeyRow::Q: + qSlider_.grabKeyboardFocus(); + break; + default: + break; // buttons have nothing to adjust; Enter or Space presses them + } +} + +void EqPopupComponent::activateKeyRow() +{ + ensureKeyBand(); + const int band = keyBand(); + if (band < 0) + return; + + switch (keyRow_) + { + case KeyRow::BypassBand: + { + toggleEqFilterBypass(settings_.filters[static_cast(band)]); + renderer_.setSettings(settings_); + commitSettings(); + repaint(); + a11y::announce(*this, describeRow(keyRow_)); + break; + } + case KeyRow::RemoveBand: + removeBandFromKeyboard(); + break; + case KeyRow::AddBand: + addBandFromKeyboard(); + break; + case KeyRow::BypassEq: + toggleEqActive(settings_); + renderer_.setSettings(settings_); + commitSettings(); + repaint(); + a11y::announce(*this, describeRow(keyRow_)); + break; + case KeyRow::RemoveEq: + if (suppressRemoveConfirmation_) + { + requestRemoveEq(); + } + else + { + showRemoveConfirmation(); + confirmButton_.grabKeyboardFocus(); + } + break; + default: + break; + } +} + +void EqPopupComponent::addBandFromKeyboard() +{ + if (static_cast(settings_.filters.size()) >= EqSettings::kMaxFilters) + { + a11y::announce(*this, Loc::format(LOC_RAW("Maximum {0} bands"), juce::String(EqSettings::kMaxFilters))); + return; + } + + // Same as a double click in the middle of the graph: a Peak at 1000 Hz, 0 dB, Q 1. + settings_.filters.push_back(makeEqFilter(1000.0, 0.0)); + EqGraphRenderer::assignPaletteSlots(settings_); + selectedFilterIndex_ = static_cast(settings_.filters.size()) - 1; + keyRow_ = KeyRow::Type; + + renderer_.setSettings(settings_); + commitSettings(); updateCardState(); repaint(); + a11y::announce(*this, Loc::format(LOC_RAW("Band {0} added"), juce::String(selectedFilterIndex_ + 1)) + + ", " + describeRow(keyRow_)); +} + +void EqPopupComponent::removeBandFromKeyboard() +{ + ensureKeyBand(); + const int band = keyBand(); + if (band < 0) + return; + + // As with the mouse, removing the last band removes the whole EQ. + if (settings_.filters.size() <= 1) + { + requestRemoveEq(); + return; + } + + if (removeFilterAt(band)) + return; + selectedFilterIndex_ = juce::jmin(band, static_cast(settings_.filters.size()) - 1); + updateCardState(); + repaint(); + a11y::announce(*this, Loc::format(LOC_RAW("Band {0} removed"), juce::String(band + 1)) + + ", " + describeBandAndRow()); +} + +void EqPopupComponent::requestClose() +{ + flushPendingCommit(); + // The owner deletes this window, so not from inside its own key handler. + juce::Component::SafePointer safeThis(this); + juce::MessageManager::callAsync([safeThis] { + if (safeThis != nullptr && safeThis->onClose) + safeThis->onClose(); + }); +} + +void EqPopupComponent::requestRemoveEq() +{ + flushPendingCommit(); + juce::Component::SafePointer safeThis(this); + juce::MessageManager::callAsync([safeThis] { + if (safeThis != nullptr && safeThis->onRemoveEq) + safeThis->onRemoveEq(); + }); +} + +double EqPopupComponent::steppedKnobValue(const EqKnob& knob, const juce::KeyPress& key) const +{ + const int code = key.getKeyCode(); + const bool fine = key.getModifiers().isAltDown(); + const double value = knob.getValue(); + const double lo = knob.getMinimum(); + const double hi = knob.getMaximum(); + + int direction = 0; + bool big = false; + if (code == juce::KeyPress::upKey || code == juce::KeyPress::rightKey) + direction = 1; + else if (code == juce::KeyPress::downKey || code == juce::KeyPress::leftKey) + direction = -1; + else if (code == juce::KeyPress::pageUpKey) + direction = 1, big = true; + else if (code == juce::KeyPress::pageDownKey) + direction = -1, big = true; + // Home is the top and End the bottom, as the user expects from REAPER faders. + else if (code == juce::KeyPress::homeKey) + return hi; + else if (code == juce::KeyPress::endKey) + return lo; + else + return value; + + double next = value; + if (&knob == &frequencySlider_) + { + // A semitone sounds like the same step at any frequency; Alt is 1 Hz, Page keys an octave. + next = fine ? value + direction + : std::round(value * std::pow(2.0, direction * (big ? 1.0 : 1.0 / 12.0))); + if (next == value) + next = value + direction; + } + else if (&knob == &gainSlider_) + { + next = value + direction * (big ? 3.0 : fine ? 0.1 : 0.5); + } + else + { + next = value + direction * (big ? 1.0 : fine ? 0.01 : 0.1); + } + return juce::jlimit(lo, hi, next); +} + +bool EqPopupComponent::handleKnobKey(EqKnob& knob, const juce::KeyPress& key) +{ + if (passesToHost(key)) + return false; + + const int code = key.getKeyCode(); + const auto mods = key.getModifiers(); + + // The key that closed the number field bubbles up here as well; it is done already. + if (editorJustClosed_) + return true; + + juce::Label* valueBox = nullptr; + for (auto* child : knob.getChildren()) + if (auto* label = dynamic_cast(child)) + valueBox = label; + + if (valueBox != nullptr && valueBox->isBeingEdited()) + { + // The field takes the other keys itself. Tab keeps the number and closes the + // circle grid -> knob -> field -> grid; Shift+Tab keeps it and goes back to the knob; + // Esc drops it. + if (code == juce::KeyPress::tabKey) + { + gridAfterEditor_ = !mods.isShiftDown(); + valueBox->hideEditor(false); + } + else if (code == juce::KeyPress::escapeKey) + valueBox->hideEditor(true); + return true; + } + + if (isPlainKey(key, juce::KeyPress::spaceKey)) + return false; // play/stop + + if (code == juce::KeyPress::escapeKey || (code == juce::KeyPress::tabKey && mods.isShiftDown())) + { + flushPendingCommit(); + focusGrid(); + return true; + } + + if (code == juce::KeyPress::tabKey || code == juce::KeyPress::returnKey) + { + flushPendingCommit(); + if (valueBox != nullptr) + { + juce::Component::SafePointer safeThis(this); + juce::Component::SafePointer safeKnob(&knob); + valueBox->onEditorHide = [safeThis, safeKnob] { + if (safeThis == nullptr) + return; + safeThis->editorJustClosed_ = true; + juce::MessageManager::callAsync([safeThis, safeKnob] { + if (safeThis == nullptr) + return; + safeThis->editorJustClosed_ = false; + const bool toGrid = std::exchange(safeThis->gridAfterEditor_, false); + if (safeKnob == nullptr || !safeKnob->isShowing()) + return; + // Back to the knob for more arrows (or to the grid after Tab), + // unless a click took focus elsewhere. + auto* focused = juce::Component::getCurrentlyFocusedComponent(); + const bool focusIsFree = focused == nullptr || focused == safeKnob.getComponent() + || safeKnob->isParentOf(focused); + if (!focusIsFree) + return; + if (toGrid) + safeThis->focusGrid(); + else if (!safeKnob->hasKeyboardFocus(false)) + safeKnob->grabKeyboardFocus(); + }); + }; + } + knob.showTextBox(); + return true; + } + + // Backspace: the default, the same value as a double click (1000 Hz, 0 dB, Q 1). + double next = isPlainKey(key, juce::KeyPress::backspaceKey) && knob.isDoubleClickReturnEnabled() + ? juce::jlimit(knob.getMinimum(), knob.getMaximum(), knob.getDoubleClickReturnValue()) + : steppedKnobValue(knob, key); + // At the edge the value does not change and NVDA says nothing. + if (next != knob.getValue()) + { + keyboardAdjusting_ = true; + // NVDA speaks the new value of the focused slider itself. + knob.setValue(next, juce::sendNotificationSync); + keyboardAdjusting_ = false; + } + return true; +} + +bool EqPopupComponent::handleTypeKey(const juce::KeyPress& key) +{ + if (passesToHost(key)) + return false; + + const int code = key.getKeyCode(); + if (isPlainKey(key, juce::KeyPress::spaceKey)) + return false; // play/stop + + // The type has no number to type in, so Tab goes back to the grid like Esc. + if (code == juce::KeyPress::escapeKey || code == juce::KeyPress::tabKey || code == juce::KeyPress::returnKey) + { + focusGrid(); + return true; + } + + // Arrows, Home and End choose the type (NVDA speaks it). Alt+Down would open the + // drop-down menu, so keys with modifiers are only eaten. + if (!key.getModifiers().isAnyModifierKeyDown()) + typeBox_.listKeyPressed(key); + return true; +} + +bool EqPopupComponent::handleConfirmKey(const juce::KeyPress& key) +{ + if (passesToHost(key)) + return false; + + const int code = key.getKeyCode(); + if (code == juce::KeyPress::escapeKey) + { + cancelButton_.onClick(); + return true; + } + + juce::Button* const order[] = { &confirmButton_, &cancelButton_, &dontShowToggle_ }; + int current = 0; + for (int i = 0; i < 3; ++i) + if (order[i]->hasKeyboardFocus(false)) + current = i; + + // Tab and Shift+Tab go round the three controls of the dialog only. + if (code == juce::KeyPress::tabKey) + { + order[(current + (key.getModifiers().isShiftDown() ? 2 : 1)) % 3]->grabKeyboardFocus(); + return true; + } + if (code == juce::KeyPress::spaceKey || code == juce::KeyPress::returnKey) + { + order[current]->triggerClick(); + return true; + } + return true; +} + +void EqPopupComponent::scheduleCommit() +{ + commitPending_ = true; + commitDeadlineMs_ = juce::Time::getMillisecondCounterHiRes() + 400.0; +} + +void EqPopupComponent::flushPendingCommit() +{ + if (!commitPending_) + return; + commitPending_ = false; + commitSettings(); } } // namespace OpenTune diff --git a/Source/Standalone/UI/PianoRoll/EqPopupComponent.h b/Source/Standalone/UI/PianoRoll/EqPopupComponent.h index e2fbbcd7..c9b0d0f3 100644 --- a/Source/Standalone/UI/PianoRoll/EqPopupComponent.h +++ b/Source/Standalone/UI/PianoRoll/EqPopupComponent.h @@ -12,12 +12,58 @@ #include "Utils/SpectrumDisplayData.h" #include "EqGraphRenderer.h" #include "EqBandInteraction.h" +#include "Utils/AccessibleComboBox.h" +#include "Utils/AccessibleToggleButton.h" #include namespace OpenTune { class LargeKnobLookAndFeel; +// Accessibility: the knob, type list and confirmation below hand their keys to the EQ +// window first, so one keyboard model runs the whole window and nothing leaks to the notes. +class EqKnob : public juce::Slider +{ +public: + std::function onKey; + + bool keyPressed(const juce::KeyPress& key) override + { + return onKey != nullptr ? onKey(key) : juce::Slider::keyPressed(key); + } +}; + +class EqTypeBox : public a11y::AccessibleComboBox +{ +public: + std::function onKey; + + bool keyPressed(const juce::KeyPress& key) override + { + return onKey != nullptr ? onKey(key) : a11y::AccessibleComboBox::keyPressed(key); + } + + // The stock list keys, for the window to call when it wants them. + bool listKeyPressed(const juce::KeyPress& key) { return a11y::AccessibleComboBox::keyPressed(key); } +}; + +class EqConfirmPanel : public juce::Component +{ +public: + std::function onKey; + + bool keyPressed(const juce::KeyPress& key) override + { + return onKey != nullptr && onKey(key); + } + + // A named group: NVDA says "Remove EQ?" when focus enters it. + std::unique_ptr createAccessibilityHandler() override + { + return std::make_unique(*this, juce::AccessibilityRole::group); + } +}; + class EqPopupComponent : public juce::Component, public juce::Timer { public: @@ -50,6 +96,13 @@ class EqPopupComponent : public juce::Component, bool isPreviewMode() const { return isPreview_; } void toggleMaximize(); + // Accessibility: opened from the keyboard. Shows the full editor and focuses the window. + void startKeyboardEditing(); + bool keyPressed(const juce::KeyPress& key) override; + std::unique_ptr createAccessibilityHandler() override; + // Commits a knob change from the arrow keys that is still waiting (see scheduleCommit). + void flushPendingCommit(); + private: enum class ButtonId { None = -1, Maximize = 0, Bypass, Remove, Minimize }; void paintButton(juce::Graphics& g, ButtonId id, juce::Rectangle bounds, bool hovered) const; @@ -79,6 +132,32 @@ class EqPopupComponent : public juce::Component, int hitTestFilterTypeButton(juce::Point pos) const; void dismissRemoveConfirmation(); + void showRemoveConfirmation(); + juce::Rectangle removeDialogBounds() const; + void setFilterType(int filterIndex, EqFilterType newType); + + // Keyboard model. Grid: Left/Right pick the band, Up/Down pick the row, + // Tab adjusts the row with arrows, a second Tab types a number. + enum class KeyRow { Type, Frequency, Gain, Q, BypassBand, RemoveBand, AddBand, BypassEq, RemoveEq, Count }; + int keyBand() const; + void ensureKeyBand(); + void selectKeyBand(int index); + void focusGrid(); + void enterKeyRow(); + void activateKeyRow(); + void addBandFromKeyboard(); + void removeBandFromKeyboard(); + void requestClose(); + void requestRemoveEq(); + bool handleKnobKey(EqKnob& knob, const juce::KeyPress& key); + bool handleTypeKey(const juce::KeyPress& key); + bool handleConfirmKey(const juce::KeyPress& key); + double steppedKnobValue(const EqKnob& knob, const juce::KeyPress& key) const; + juce::String describeRow(KeyRow row) const; + juce::String describeBandAndRow() const; + juce::String describeAllBands() const; + static juce::String filterTypeName(EqFilterType type); + void scheduleCommit(); void paintBypassIcon(juce::Graphics& g, juce::Rectangle bounds, juce::Colour color) const; void paintRemoveIcon(juce::Graphics& g, juce::Rectangle bounds, juce::Colour color) const; @@ -107,11 +186,26 @@ class EqPopupComponent : public juce::Component, // 卡片内旋钮控件 std::unique_ptr cardKnobLookAndFeel_; - juce::Slider frequencySlider_; - juce::Slider gainSlider_; - juce::Slider qSlider_; + EqKnob frequencySlider_; + EqKnob gainSlider_; + EqKnob qSlider_; bool updatingCardControls_ = false; + // Accessibility: invisible real controls over the painted type row and confirmation, + // so the screen reader sees them; the mouse still works on the painting below. + EqTypeBox typeBox_; + EqConfirmPanel confirmPanel_; + juce::TextButton confirmButton_; + juce::TextButton cancelButton_; + a11y::AccessibleToggleButton dontShowToggle_; + + KeyRow keyRow_ = KeyRow::Type; + bool keyboardAdjusting_ = false; // knob changes from arrows wait before the commit + bool commitPending_ = false; + double commitDeadlineMs_ = 0.0; + bool editorJustClosed_ = false; // the key that closed the number field must not act again + bool gridAfterEditor_ = false; // Tab in the number field: keep it and go back to the grid + std::vector hoverBandAmounts_ = std::vector(EqSettings::kMaxFilters, 0.0); static constexpr double kHoverFadeInTime = 0.50; static constexpr double kHoverFadeOutTime = 0.50; diff --git a/Source/Standalone/UI/PianoRoll/PianoRollToolHandler.cpp b/Source/Standalone/UI/PianoRoll/PianoRollToolHandler.cpp index 57c9ee08..5279f772 100644 --- a/Source/Standalone/UI/PianoRoll/PianoRollToolHandler.cpp +++ b/Source/Standalone/UI/PianoRoll/PianoRollToolHandler.cpp @@ -613,27 +613,27 @@ bool PianoRollToolHandler::keyPressed(const juce::KeyPress& key, const bool isOpenDyne = AudioEditingScheme::usesNotesPrimaryScheme(ctx_.getAudioEditingScheme()); if (isOpenDyne) { if (matches(KeyShortcutConfig::ShortcutId::ToolODSelect)) { - ctx_.setCurrentTool(ToolId::Select); + switchToolFromKeyboard(ToolId::Select); return true; } if (matches(KeyShortcutConfig::ShortcutId::ToolODPitch)) { - ctx_.setCurrentTool(ToolId::Pitch); + switchToolFromKeyboard(ToolId::Pitch); return true; } if (matches(KeyShortcutConfig::ShortcutId::ToolODPitchModulation)) { - ctx_.setCurrentTool(ToolId::PitchModulation); + switchToolFromKeyboard(ToolId::PitchModulation); return true; } if (matches(KeyShortcutConfig::ShortcutId::ToolODPitchDrift)) { - ctx_.setCurrentTool(ToolId::PitchDrift); + switchToolFromKeyboard(ToolId::PitchDrift); return true; } if (matches(KeyShortcutConfig::ShortcutId::ToolODVolumeEnvelope)) { - ctx_.setCurrentTool(ToolId::VolumeEnvelope); + switchToolFromKeyboard(ToolId::VolumeEnvelope); return true; } if (matches(KeyShortcutConfig::ShortcutId::ToolODScissors)) { - ctx_.setCurrentTool(ToolId::Scissors); + switchToolFromKeyboard(ToolId::Scissors); return true; } } @@ -647,15 +647,18 @@ bool PianoRollToolHandler::keyPressed(const juce::KeyPress& key, && !contentSnapshot->pitchCurve->isEmpty(); if (!hasNotes && !hasCurve) { + notifyKeyboardNote(KeyboardNoteEvent::NoNotes, notes, -1); return true; } - + if (hasNotes) { selectAllNotes(notes); } - + // F0 范围从 noteSelection 按需派生,无需同步。 if (ctx_.invalidateSelectionFeedback) ctx_.invalidateSelectionFeedback(); + // Accessibility: without this, selecting all from the keyboard gives no feedback. + notifyKeyboardNote(hasNotes ? KeyboardNoteEvent::AllSelected : KeyboardNoteEvent::NoNotes, notes, -1); return true; } @@ -666,35 +669,35 @@ bool PianoRollToolHandler::keyPressed(const juce::KeyPress& key, // ToolTimeTool/ToolAutoTune 与通用 SelectAll/Delete/CancelSelection 两 scheme 共用。 if (!isOpenDyne) { if (matches(KeyShortcutConfig::ShortcutId::ToolDrawNote)) { - ctx_.setCurrentTool(ToolId::DrawNote); + switchToolFromKeyboard(ToolId::DrawNote); return true; } if (matches(KeyShortcutConfig::ShortcutId::ToolSelect)) { - ctx_.setCurrentTool(ToolId::Select); + switchToolFromKeyboard(ToolId::Select); return true; } if (matches(KeyShortcutConfig::ShortcutId::ToolLineAnchor)) { - ctx_.setCurrentTool(ToolId::LineAnchor); + switchToolFromKeyboard(ToolId::LineAnchor); return true; } } // EQ 工具两种模式共用(ShortcutId::Eq 可配置,默认 E) if (matches(KeyShortcutConfig::ShortcutId::Eq)) { - ctx_.setCurrentTool(ToolId::Eq); + switchToolFromKeyboard(ToolId::Eq); return true; } // HandDraw 两种模式共用 if (matches(KeyShortcutConfig::ShortcutId::ToolHandDraw)) { - ctx_.setCurrentTool(ToolId::HandDraw); + switchToolFromKeyboard(ToolId::HandDraw); return true; } if (matches(KeyShortcutConfig::ShortcutId::ToolTimeTool)) { - ctx_.setCurrentTool(ToolId::TimeTool); + switchToolFromKeyboard(ToolId::TimeTool); return true; } @@ -727,33 +730,203 @@ bool PianoRollToolHandler::keyPressed(const juce::KeyPress& key, return true; } - if (matches(KeyShortcutConfig::ShortcutId::CancelSelection)) { - ctx_.notifyEscapeKey(); - return true; - } + if (matches(KeyShortcutConfig::ShortcutId::CancelSelection)) + return ctx_.notifyEscapeKey == nullptr || ctx_.notifyEscapeKey(); return false; } bool PianoRollToolHandler::handleNoteArrowKey(const juce::KeyPress& key) { - if (key.getModifiers().isAnyModifierKeyDown()) + const auto mods = key.getModifiers(); + const int keyCode = key.getKeyCode(); + const bool plain = !mods.isAnyModifierKeyDown(); + const bool shiftOnly = mods.isShiftDown() && !mods.isCtrlDown() && !mods.isAltDown() && !mods.isCommandDown(); + const bool altOnly = mods.isAltDown() && !mods.isShiftDown() && !mods.isCtrlDown() && !mods.isCommandDown(); + // Values change with Ctrl+Up/Down (as in Melodyne), Ctrl+Shift for a fine step, so a plain + // arrow pressed while exploring changes nothing. Ctrl+Alt+Up/Down stays the vertical zoom. + const bool ctrlOnly = (mods.isCtrlDown() || mods.isCommandDown()) && !mods.isShiftDown() && !mods.isAltDown(); + const bool ctrlShift = (mods.isCtrlDown() || mods.isCommandDown()) && mods.isShiftDown() && !mods.isAltDown(); + const bool upOrDown = keyCode == juce::KeyPress::upKey || keyCode == juce::KeyPress::downKey; + const bool isInfoKey = keyCode == 'I' || keyCode == 'i'; + const bool isResetKey = keyCode == 'R' || keyCode == 'r'; + const bool isSplitKey = keyCode == 'X' || keyCode == 'x'; + const bool isMergeKey = keyCode == 'J' || keyCode == 'j'; + const bool isHomeOrEnd = keyCode == juce::KeyPress::homeKey || keyCode == juce::KeyPress::endKey; + const bool openDyne = AudioEditingScheme::usesNotesPrimaryScheme(ctx_.getAudioEditingScheme()); + + // Enter mirrors the OpenDyne double-click on a note: with the modulation or drift tool + // it toggles 100% / 0%, otherwise it snaps the note to the pitch grid. Without a selected + // note Enter stays "Stop" as documented, so it is not consumed here. + if (plain && keyCode == juce::KeyPress::returnKey && openDyne) + return applyNoteDefaultActionByKeyboard(); + + // Extra mouse-free keys (Ctrl/Alt+Up/Down, Home, End, I, R, X, J) do not override a binding + // the user assigned to something else in the shortcut settings. + const bool leftOrRight = keyCode == juce::KeyPress::leftKey || keyCode == juce::KeyPress::rightKey; + // Ctrl+Left/Right move the end of the note, Ctrl+Shift+Left/Right its start. + const bool resizeKey = leftOrRight && mods.isCtrlDown() && !mods.isAltDown(); + const bool extraKey = ((altOnly || ctrlOnly || ctrlShift) && upOrDown) || (shiftOnly && leftOrRight) || resizeKey + || (shiftOnly && (isSplitKey || isInfoKey)) + || (plain && (isInfoKey || isResetKey || isSplitKey || isMergeKey || isHomeOrEnd)); + if (extraKey + && KeyShortcutConfig::findShortcutForBinding(ctx_.getShortcutSettings(), + KeyShortcutConfig::KeyBinding(keyCode, mods), + openDyne ? KeyShortcutConfig::kPianoRollOpenDyneScope + : KeyShortcutConfig::kPianoRollOpenTuneScope) + != KeyShortcutConfig::ShortcutId::Count) return false; - const int keyCode = key.getKeyCode(); - if (keyCode == juce::KeyPress::upKey || keyCode == juce::KeyPress::downKey) { - moveSelectedNotesPitchByKeyboard(keyCode == juce::KeyPress::upKey ? 1 : -1); + if (upOrDown && (plain || altOnly || ctrlOnly || ctrlShift)) { + const int direction = keyCode == juce::KeyPress::upKey ? 1 : -1; + const bool modDrift = openDyne && (currentTool_ == ToolId::PitchModulation || currentTool_ == ToolId::PitchDrift); + const bool volume = openDyne && currentTool_ == ToolId::VolumeEnvelope; + // A plain arrow, or Alt where there are no semitones, only says which keys edit. + if (plain || (altOnly && (modDrift || volume))) { + notifyKeyboardNote(KeyboardNoteEvent::ArrowHint, committedNotes(ctx_), -1); + return true; + } + // Like mouse dragging: the arrows change whatever the current tool edits. + if (modDrift) + adjustSelectedNotesModDriftByKeyboard(direction, ctrlShift); // 5%, fine 1% + else if (volume) + adjustSelectedNotesVolumeByKeyboard(direction, ctrlShift); // 1 dB, fine 0.1 dB + else if (altOnly) + // Alt: a semitone even when the key/scale grid would skip notes outside the scale. + moveSelectedNotesPitchByKeyboard(direction, false, false, true); + else + // Ctrl: next step of the pitch grid; Ctrl+Shift: 1 cent without the grid. + moveSelectedNotesPitchByKeyboard(direction, ctrlShift); + return true; + } + if (resizeKey) { + resizeSelectedNoteByKeyboard(mods.isShiftDown(), keyCode == juce::KeyPress::rightKey ? 1 : -1); + return true; + } + if (shiftOnly && isSplitKey) { + splitSelectedNoteByKeyboard(true); + return true; + } + if (shiftOnly && isInfoKey) { + notifyKeyboardNote(KeyboardNoteEvent::PositionInfo, committedNotes(ctx_), -1); + return true; + } + // Shift+Left/Right extend the selection, like Shift+click on a note. + if (shiftOnly && leftOrRight) { + extendSelectionByKeyboard(keyCode == juce::KeyPress::rightKey); return true; } - if (keyCode != juce::KeyPress::leftKey && keyCode != juce::KeyPress::rightKey) + if (!plain) return false; + if (isSplitKey) { + splitSelectedNoteByKeyboard(); + return true; + } + if (isMergeKey) { + mergeSelectedNoteWithNext(); + return true; + } + const auto& notes = committedNotes(ctx_); + const int noteCount = static_cast(notes.size()); + + if (isInfoKey) { + const auto selected = collectSelectedNoteIndices(notes); + if (noteCount == 0) + notifyKeyboardNote(KeyboardNoteEvent::NoNotes, notes, -1); + else if (selected.empty()) + notifyKeyboardNote(KeyboardNoteEvent::NoSelection, notes, -1); + else + notifyKeyboardNote(KeyboardNoteEvent::Info, notes, selected.front()); + return true; + } + + // R: back to the sung pitch. Ctrl+Z only goes back step by step, so after many edits + // there was no quick way to return one note to how it was sung. + if (isResetKey) { + moveSelectedNotesPitchByKeyboard(0, false, true); + return true; + } + + if (!isHomeOrEnd && keyCode != juce::KeyPress::leftKey && keyCode != juce::KeyPress::rightKey) + return false; + + if (noteCount == 0) { + notifyKeyboardNote(KeyboardNoteEvent::NoNotes, notes, -1); + return true; + } + + // First / last note by start time; array order is not treated as time order. + const auto edgeNote = [¬es, noteCount](bool last) { + int edge = 0; + for (int index = 1; index < noteCount; ++index) { + const double startTime = notes[static_cast(index)].startTime; + const double edgeTime = notes[static_cast(edge)].startTime; + if (last ? startTime > edgeTime : startTime < edgeTime) + edge = index; + } + return edge; + }; + + if (isHomeOrEnd) { + selectNoteFromKeyboard(notes, edgeNote(keyCode == juce::KeyPress::endKey)); + return true; + } + const auto selectedIndices = collectSelectedNoteIndices(notes); - if (selectedIndices.empty()) + // The place in the song moved since the last arrow (playback paused somewhere else, or the + // edit cursor was moved in REAPER): start from there, as without a selection. Unknown + // positions (during playback) are not remembered, so a pause after them still counts. + const auto cursor = ctx_.getEditCursorSourceTime ? ctx_.getEditCursorSourceTime() : std::nullopt; + // Nothing remembered yet (the window was just opened): follow the cursor too. + const bool cursorMoved = cursor && (!lastArrowCursor_ || std::abs(*cursor - *lastArrowCursor_) > 1.0e-6); + if (cursor) + lastArrowCursor_ = cursor; + // The note at the cursor is already the selected one: move on to its neighbour as usual, + // otherwise the arrow would only repeat the same note and seem to do nothing. + const auto cursorIsInSelection = [&] { + for (int index : selectedIndices) { + const auto& note = notes[static_cast(index)]; + if (note.startTime <= *cursor && *cursor < note.endTime) + return true; + } + return false; + }; + if (selectedIndices.empty() || (cursorMoved && !cursorIsInSelection())) { + // Start from REAPER's edit cursor when it is known, so the user lands where they are + // in the song: Right takes the note under the cursor or the next one, Left the note + // under the cursor or the previous one. Past the last or before the first note, the + // nearest note. Without a cursor: the first note. + if (cursor) { + const bool right = keyCode == juce::KeyPress::rightKey; + int target = -1; + for (int index = 0; index < noteCount; ++index) { + const auto& note = notes[static_cast(index)]; + const bool candidate = right ? note.endTime > *cursor : note.startTime < *cursor; + if (!candidate) + continue; + const double startTime = note.startTime; + if (target < 0 || (right ? startTime < notes[static_cast(target)].startTime + : startTime > notes[static_cast(target)].startTime)) + target = index; + } + selectNoteFromKeyboard(notes, target >= 0 ? target : edgeNote(right)); + return true; + } + // Without a selection the arrows used to do nothing, and there was no mouse-free way to select. + selectNoteFromKeyboard(notes, edgeNote(false)); return true; + } const bool moveRight = keyCode == juce::KeyPress::rightKey; + // All notes selected (Ctrl+A): the selection has no neighbours, so the arrows would be silent. + // Right goes to the first note, Left to the last one. + if (noteCount > 1 && static_cast(selectedIndices.size()) == noteCount) { + selectNoteFromKeyboard(notes, edgeNote(!moveRight)); + return true; + } + double boundaryTime = notes[static_cast(selectedIndices.front())].startTime; for (int index : selectedIndices) { const double startTime = notes[static_cast(index)].startTime; @@ -773,20 +946,518 @@ bool PianoRollToolHandler::handleNoteArrowKey(const juce::KeyPress& key) } } - if (adjacentIndex >= 0) { - ctx_.getState().noteSelection.setSingle(adjacentIndex, static_cast(notes.size())); - if (ctx_.invalidateSelectionFeedback) - ctx_.invalidateSelectionFeedback(); + // Stay silent at the ends of the list. + if (adjacentIndex >= 0) + selectNoteFromKeyboard(notes, adjacentIndex); + return true; +} + +// Keyboard version of dragging a note edge with the Select tool (handleSelectDrag/Up): +// 10 ms per press, the same minimum length and the same rule for the touching neighbour, +// which yields its boundary but keeps its own minimum length. +void PianoRollToolHandler::resizeSelectedNoteByKeyboard(bool startEdge, int direction) +{ + const auto& notes = committedNotes(ctx_); + const auto selected = collectSelectedNoteIndices(notes); + if (selected.empty()) { + notifyKeyboardNote(notes.empty() ? KeyboardNoteEvent::NoNotes : KeyboardNoteEvent::NoSelection, notes, -1); + return; + } + if (selected.size() != 1) { + notifyKeyboardNote(KeyboardNoteEvent::SingleNoteNeeded, notes, -1); + return; + } + + constexpr double step = 0.01; + const int idx = selected.front(); + const auto beforeNotes = notes; + const auto& old = beforeNotes[static_cast(idx)]; + const auto editRange = sourceEditRange(); + const auto edge = startEdge ? NoteResizeEdge::Left : NoteResizeEdge::Right; + const double clampedTime = juce::jlimit(editRange.startSeconds, editRange.endSeconds, + (startEdge ? old.startTime : old.endTime) + direction * step); + + // The same planner as the mouse: minimum length, the neighbour yields down to its own minimum. + const auto plan = planNoteResizeEdit(beforeNotes, idx, edge, clampedTime, kNoteResizeMinDuration); + const auto& changed = plan.afterNotes[static_cast(idx)]; + // Limit reached (minimum length, neighbour or clip edge): stay silent, as at list ends. + if (changed.startTime == old.startTime && changed.endTime == old.endTime) + return; + + // Same transaction as a mouse resize (revision check, one undo step). + const auto expectedRevision = ctx_.getNotesRevision ? ctx_.getNotesRevision() : 0; + const auto commitResize = [this, expectedRevision, idx, edge, clampedTime] + (const std::vector& segments, F0FrameRange affectedRange) { + return ctx_.commitNoteResize + && ctx_.commitNoteResize(expectedRevision, idx, edge, clampedTime, kNoteResizeMinDuration, + segments, affectedRange, LOC_RAW("Resize note")); + }; + const auto contentSnapshot = ctx_.getEditableContentSnapshot(); + const F0FrameRange f0Range = ctx_.getF0Timeline().rangeForTimes(plan.dirtyStartTime, plan.dirtyEndTime); + const bool committed = (contentSnapshot != nullptr && contentSnapshot->pitchCurve != nullptr && !f0Range.isEmpty()) + ? commitNoteBasedCorrection(ctx_, plan.afterNotes, f0Range, commitResize) + : commitResize({}, {}); + if (!committed) { + notifyKeyboardNote(KeyboardNoteEvent::EditFailed, committedNotes(ctx_), -1); + return; + } + if (ctx_.invalidateLiveNotes) ctx_.invalidateLiveNotes(beforeNotes, committedNotes(ctx_)); + notifyKeyboardNote(KeyboardNoteEvent::NoteResized, committedNotes(ctx_), idx); +} + +// Shift+Left/Right, as in Windows lists: the anchor stays, the other end moves one note. +// Moving back towards the anchor shrinks the range. +void PianoRollToolHandler::extendSelectionByKeyboard(bool moveRight) +{ + const auto& notes = committedNotes(ctx_); + const int noteCount = static_cast(notes.size()); + if (noteCount == 0) { + notifyKeyboardNote(KeyboardNoteEvent::NoNotes, notes, -1); + return; + } + + // Time order: array order is not treated as time order. + std::vector order(static_cast(noteCount)); + for (int i = 0; i < noteCount; ++i) + order[static_cast(i)] = i; + std::stable_sort(order.begin(), order.end(), [¬es](int a, int b) { + return notes[static_cast(a)].startTime < notes[static_cast(b)].startTime; + }); + std::vector position(static_cast(noteCount)); + for (int i = 0; i < noteCount; ++i) + position[static_cast(order[static_cast(i)])] = i; + const auto posOf = [&position](int index) { return position[static_cast(index)]; }; + + const auto selected = collectSelectedNoteIndices(notes); + if (selected.empty()) { + const int first = order[static_cast(moveRight ? 0 : noteCount - 1)]; + keyboardRangeAnchor_ = keyboardRangeActive_ = first; + selectNoteFromKeyboard(notes, first); + return; + } + + // Keep the anchor only while the selection is still exactly the range made with Shift; + // after a click, an edit or plain arrows start again from the current selection. + bool rangeStillValid = keyboardRangeAnchor_ >= 0 && keyboardRangeAnchor_ < noteCount + && keyboardRangeActive_ >= 0 && keyboardRangeActive_ < noteCount; + if (rangeStillValid) { + const int lo = std::min(posOf(keyboardRangeAnchor_), posOf(keyboardRangeActive_)); + const int hi = std::max(posOf(keyboardRangeAnchor_), posOf(keyboardRangeActive_)); + rangeStillValid = static_cast(selected.size()) == hi - lo + 1; + for (int index : selected) + rangeStillValid = rangeStillValid && posOf(index) >= lo && posOf(index) <= hi; + } + if (!rangeStillValid) { + int minPos = noteCount, maxPos = -1; + for (int index : selected) { + minPos = std::min(minPos, posOf(index)); + maxPos = std::max(maxPos, posOf(index)); + } + keyboardRangeAnchor_ = order[static_cast(moveRight ? minPos : maxPos)]; + keyboardRangeActive_ = order[static_cast(moveRight ? maxPos : minPos)]; + } + + // Stay silent at the ends of the list. + const int next = posOf(keyboardRangeActive_) + (moveRight ? 1 : -1); + if (next < 0 || next >= noteCount) + return; + keyboardRangeActive_ = order[static_cast(next)]; + + const int lo = std::min(posOf(keyboardRangeAnchor_), next); + const int hi = std::max(posOf(keyboardRangeAnchor_), next); + std::vector range; + for (int p = lo; p <= hi; ++p) + range.push_back(order[static_cast(p)]); + ctx_.getState().noteSelection.setFromIndices(std::move(range), noteCount); + if (ctx_.invalidateSelectionFeedback) + ctx_.invalidateSelectionFeedback(); + notifyKeyboardNote(KeyboardNoteEvent::RangeSelected, notes, keyboardRangeActive_); +} + +void PianoRollToolHandler::selectNoteFromKeyboard(const std::vector& notes, int index) +{ + ctx_.getState().noteSelection.setSingle(index, static_cast(notes.size())); + if (ctx_.invalidateSelectionFeedback) + ctx_.invalidateSelectionFeedback(); + notifyKeyboardNote(KeyboardNoteEvent::Selected, notes, index); +} + +void PianoRollToolHandler::notifyKeyboardNote(KeyboardNoteEvent event, const std::vector& notes, int index) +{ + if (ctx_.notifyKeyboardNote) + ctx_.notifyKeyboardNote(event, notes, index); +} + +// X: split the selected note where its sung pitch changes the most - usually where two sung +// notes were merged into one. Without a clear pitch change the note is split in half. +// Shift+X splits at REAPER's edit cursor instead, when it is inside the note (the cursor +// is read from REAPER while stopped, see ReaperHostBridge). The split itself uses the +// scissors planner (planScissorsSplit). +void PianoRollToolHandler::splitSelectedNoteByKeyboard(bool atEditCursor) +{ + const auto beforeNotes = committedNotes(ctx_); + if (beforeNotes.empty()) { + notifyKeyboardNote(KeyboardNoteEvent::NoNotes, beforeNotes, -1); + return; + } + const auto selected = collectSelectedNoteIndices(beforeNotes); + if (selected.empty()) { + notifyKeyboardNote(KeyboardNoteEvent::NoSelection, beforeNotes, -1); + return; + } + + const int index = selected.front(); + const Note& original = beforeNotes[static_cast(index)]; + + // Parts shorter than 20 ms are useless. + static constexpr double kMinPartSeconds = 0.02; + if (original.getDuration() < 2.0 * kMinPartSeconds) { + notifyKeyboardNote(KeyboardNoteEvent::NoteTooShort, beforeNotes, index); + return; + } + + double splitTime = 0.5 * (original.startTime + original.endTime); + bool foundPitchChange = false; + const auto f0tl = ctx_.getF0Timeline(); + const auto originalF0 = ctx_.getOriginalF0 ? ctx_.getOriginalF0() : std::vector{}; + if (atEditCursor) { + const auto cursor = ctx_.getEditCursorSourceTime ? ctx_.getEditCursorSourceTime() : std::nullopt; + if (!cursor) { + notifyKeyboardNote(KeyboardNoteEvent::CursorUnknown, beforeNotes, index); + return; + } + if (*cursor <= original.startTime + kMinPartSeconds || *cursor >= original.endTime - kMinPartSeconds) { + notifyKeyboardNote(KeyboardNoteEvent::CursorOutsideNote, beforeNotes, index); + return; + } + splitTime = *cursor; + } else if (!originalF0.empty() && !f0tl.isEmpty()) { + const auto range = f0tl.rangeForTimes(original.startTime, original.endTime); + const int frameCount = static_cast(originalF0.size()); + // Mean sung pitch (MIDI) of the voiced frames in [from, to) inside the note. + const auto meanMidi = [&](int from, int to) -> std::optional { + float sum = 0.0f; + int count = 0; + for (int frame = std::max(from, range.startFrame); + frame < std::min({ to, range.endFrameExclusive, frameCount }); ++frame) { + const float hz = originalF0[static_cast(frame)]; + if (hz > 0.0f) { + sum += PitchUtils::freqToMidi(hz); + ++count; + } + } + if (count < 2) + return std::nullopt; + return sum / static_cast(count); + }; + + // Compare the mean pitch just before and just after each frame (~45 ms each side + // at the usual hop) and pick the frame with the largest jump. + constexpr int kWindowFrames = 4; + float bestJump = 0.0f; + int bestFrame = -1; + for (int frame = range.startFrame + 1; frame < range.endFrameExclusive; ++frame) { + const double time = f0tl.timeAtFrame(frame); + if (time <= original.startTime + kMinPartSeconds || time >= original.endTime - kMinPartSeconds) + continue; + const auto before = meanMidi(frame - kWindowFrames, frame); + const auto after = meanMidi(frame, frame + kWindowFrames); + if (!before || !after) + continue; + const float jump = std::abs(*after - *before); + if (jump > bestJump) { + bestJump = jump; + bestFrame = frame; + } + } + // Less than half a semitone is vibrato or drift, not a second note. + if (bestFrame >= 0 && bestJump >= 0.5f) { + splitTime = f0tl.timeAtFrame(bestFrame); + foundPitchChange = true; + } + } + + // The parts and their pitch centres come from the scissors planner, applied to the + // selected note only (the scissors cut every note under the line). + const auto plan = planScissorsSplit({ original }, splitTime, loadEffectiveF0(), f0tl); + if (plan.cutCount == 0 || plan.afterNotes.size() != 2) { + notifyKeyboardNote(KeyboardNoteEvent::EditFailed, beforeNotes, -1); + return; + } + + std::vector newNotes; + newNotes.reserve(beforeNotes.size() + 1); + for (int i = 0; i < static_cast(beforeNotes.size()); ++i) { + if (i == index) + newNotes.insert(newNotes.end(), plan.afterNotes.begin(), plan.afterNotes.end()); + else + newNotes.push_back(beforeNotes[static_cast(i)]); + } + + // Same transaction as the scissors: revision check, notes replaced, one undo step. + if (!ctx_.commitScissorsNotes || !ctx_.commitScissorsNotes(newNotes, LOC_RAW("Split note"))) { + notifyKeyboardNote(KeyboardNoteEvent::EditFailed, committedNotes(ctx_), -1); + return; + } + + // Select the left part so Right arrow leads straight to the right part. + ctx_.getState().noteSelection.setSingle(index, static_cast(newNotes.size())); + if (ctx_.invalidateSelectionFeedback) + ctx_.invalidateSelectionFeedback(); + notifyKeyboardNote(atEditCursor ? KeyboardNoteEvent::SplitAtCursor + : foundPitchChange ? KeyboardNoteEvent::Split + : KeyboardNoteEvent::SplitInHalf, + newNotes, index); +} + +// J: merge the selected note with the next one if they touch. Same as double-clicking +// the boundary with the scissors (handleScissorsToolMerge). +void PianoRollToolHandler::mergeSelectedNoteWithNext() +{ + const auto beforeNotes = committedNotes(ctx_); + if (beforeNotes.empty()) { + notifyKeyboardNote(KeyboardNoteEvent::NoNotes, beforeNotes, -1); + return; + } + const auto selected = collectSelectedNoteIndices(beforeNotes); + if (selected.empty()) { + notifyKeyboardNote(KeyboardNoteEvent::NoSelection, beforeNotes, -1); + return; + } + + const int index = selected.front(); + const Note& left = beforeNotes[static_cast(index)]; + int nextIndex = -1; + for (int i = 0; i < static_cast(beforeNotes.size()); ++i) { + const double startTime = beforeNotes[static_cast(i)].startTime; + if (startTime > left.startTime + && (nextIndex < 0 || startTime < beforeNotes[static_cast(nextIndex)].startTime)) + nextIndex = i; + } + + // "Touching" means a gap of at most 20 ms; notes across a pause are not merged, as with the mouse. + constexpr double kTouchToleranceSeconds = 0.02; + if (nextIndex < 0 + || beforeNotes[static_cast(nextIndex)].startTime - left.endTime > kTouchToleranceSeconds) { + notifyKeyboardNote(KeyboardNoteEvent::NoAdjacentNote, beforeNotes, index); + return; + } + + const Note& right = beforeNotes[static_cast(nextIndex)]; + // The scissors planner merges at a boundary. The gap may be up to the touch tolerance, + // so the boundary is its middle and the planner's tolerance covers both note edges. + const double boundary = 0.5 * (left.endTime + right.startTime); + const double tolerance = 0.5 * std::abs(right.startTime - left.endTime) + 1.0e-6; + const auto plan = planScissorsMerge({ left, right }, boundary, tolerance, + loadEffectiveF0(), ctx_.getF0Timeline()); + if (plan.mergeCount == 0 || plan.afterNotes.size() != 1) { + notifyKeyboardNote(KeyboardNoteEvent::NoAdjacentNote, beforeNotes, index); + return; + } + + std::vector newNotes; + newNotes.reserve(beforeNotes.size()); + int mergedIndex = -1; + for (int i = 0; i < static_cast(beforeNotes.size()); ++i) { + if (i == nextIndex) + continue; + if (i == index) { + mergedIndex = static_cast(newNotes.size()); + newNotes.push_back(plan.afterNotes.front()); + } else { + newNotes.push_back(beforeNotes[static_cast(i)]); + } + } + + // Same transaction as the scissors: revision check, notes replaced, one undo step. + if (!ctx_.commitScissorsNotes || !ctx_.commitScissorsNotes(newNotes, LOC_RAW("Merge notes"))) { + notifyKeyboardNote(KeyboardNoteEvent::EditFailed, committedNotes(ctx_), -1); + return; + } + + ctx_.getState().noteSelection.setSingle(mergedIndex, static_cast(newNotes.size())); + if (ctx_.invalidateSelectionFeedback) + ctx_.invalidateSelectionFeedback(); + notifyKeyboardNote(KeyboardNoteEvent::Merged, newNotes, mergedIndex); +} + +// Shared commit path for keyboard note edits: the same commitNoteBasedCorrection +// as the mouse, over the range of the changed notes. +bool PianoRollToolHandler::commitKeyboardNoteEdit(const std::vector& work, + const std::vector& changedIndices, + const juce::String& undoDescription) +{ + double rangeStart = std::numeric_limits::max(); + double rangeEnd = std::numeric_limits::lowest(); + for (int index : changedIndices) { + rangeStart = std::min(rangeStart, work[static_cast(index)].startTime); + rangeEnd = std::max(rangeEnd, work[static_cast(index)].endTime); } + + const F0FrameRange editRange = ctx_.getF0Timeline().rangeForTimes(rangeStart, rangeEnd); + const auto contentSnapshot = ctx_.getEditableContentSnapshot(); + if (changedIndices.empty() || editRange.isEmpty() + || contentSnapshot == nullptr || contentSnapshot->pitchCurve == nullptr) { + notifyKeyboardNote(KeyboardNoteEvent::EditFailed, committedNotes(ctx_), -1); + return false; + } + + ctx_.beginNoteDraft(); + auto& draft = ctx_.getNoteDraft(); + draft.contentDirty = true; + draft.workingNotes = work; + ctx_.setUndoDescription(undoDescription); + const bool committed = commitNoteBasedCorrection(ctx_, work, editRange); + ctx_.clearNoteDraft(); + if (!committed) { + ctx_.setUndoDescription({}); + // Every caller is a keyboard edit, so the failure is said here once. + notifyKeyboardNote(KeyboardNoteEvent::EditFailed, committedNotes(ctx_), -1); + } + return committed; +} + +// Up/Down with the Pitch Modulation or Pitch Drift tool: 5% steps, 1% with Alt. +// Values and their meaning match mouse dragging (dragNotePitch). +void PianoRollToolHandler::adjustSelectedNotesModDriftByKeyboard(int direction, bool fine) +{ + const auto& notes = committedNotes(ctx_); + const auto selected = collectSelectedNoteIndices(notes); + if (selected.empty()) { + notifyKeyboardNote(notes.empty() ? KeyboardNoteEvent::NoNotes : KeyboardNoteEvent::NoSelection, + notes, -1); + return; + } + + const bool modulation = currentTool_ == ToolId::PitchModulation; + const auto event = modulation ? KeyboardNoteEvent::ModulationChanged : KeyboardNoteEvent::DriftChanged; + const float step = static_cast(direction) * (fine ? 0.01f : 0.05f); + + std::vector work = notes; + std::vector changed; + for (int index : selected) { + auto& note = work[static_cast(index)]; + if (modulation) { + // A negative value means "follow the global Retune Speed knob". + const float effective = note.retuneSpeed >= 0.0f ? note.retuneSpeed : ctx_.getRetuneSpeed(); + const float target = juce::jlimit(0.0f, 1.0f, effective + step); + if (std::abs(target - effective) <= 0.001f) + continue; + note.retuneSpeed = target; + } else { + // Drift is not clamped to +/-100%, as with the mouse (Melodyne allows 224%, -112%, etc.). + // Up increases the number that the screen reader announces. + note.pitchDriftScale += step; + } + note.dirty = true; + changed.push_back(index); + } + + if (changed.empty()) { + // At the end of the range (0% or 100% modulation) just announce the current value. + notifyKeyboardNote(event, notes, selected.front()); + return; + } + if (commitKeyboardNoteEdit(work, changed, + modulation ? LOC_RAW("Modulation depth") : LOC_RAW("Drift correction"))) + notifyKeyboardNote(event, work, changed.front()); +} + +// Enter: like double-clicking a note (handlePitchToolDoubleClick) but for the selected notes. +// Returns false when nothing is selected so Enter keeps working as "Stop". +bool PianoRollToolHandler::applyNoteDefaultActionByKeyboard() +{ + const auto& notes = committedNotes(ctx_); + const auto selected = collectSelectedNoteIndices(notes); + if (selected.empty()) + return false; + + // EQ: a click on a note opens the EQ window, so Enter does the same instead of snapping the pitch. + if (currentTool_ == ToolId::Eq) { + const int anchor = ctx_.getState().noteSelection.anchorIndex; + const bool anchorSelected = std::find(selected.begin(), selected.end(), anchor) != selected.end(); + if (ctx_.openEqFromKeyboard) + ctx_.openEqFromKeyboard(anchorSelected ? anchor : selected.front()); + return true; + } + + // Volume Envelope: the double-click resets the note to 0 dB. + if (currentTool_ == ToolId::VolumeEnvelope) { + resetSelectedNotesVolumeByKeyboard(); + return true; + } + + std::vector work = notes; + std::vector changed; + + if (currentTool_ == ToolId::PitchModulation || currentTool_ == ToolId::PitchDrift) { + const bool modulation = currentTool_ == ToolId::PitchModulation; + for (int index : selected) { + auto& note = work[static_cast(index)]; + float& value = modulation ? note.retuneSpeed : note.pitchDriftScale; + value = value > 0.5f ? 0.0f : 1.0f; // toggle 100% / 0%, as the double-click does + note.dirty = true; + changed.push_back(index); + } + const auto event = modulation ? KeyboardNoteEvent::ModulationChanged : KeyboardNoteEvent::DriftChanged; + if (commitKeyboardNoteEdit(work, changed, + modulation ? LOC_RAW("Modulation depth") : LOC_RAW("Drift correction"))) + notifyKeyboardNote(event, work, changed.front()); + return true; + } + + // Other tools: snap the note to the pitch grid (Pitch Snap). As with the double-click, + // snapping starts from the note's base pitch, ignoring the current offset. + const auto scaleSnap = ctx_.getActiveScaleSnap ? ctx_.getActiveScaleSnap() : std::nullopt; + for (int index : selected) { + auto& note = work[static_cast(index)]; + const float baseMidi = PitchUtils::freqToMidi(note.pitch); + float snappedMidi = baseMidi; + switch (pitchGridMode_) { + case PitchGridMode::NoSnap: + continue; // nothing to snap to without a grid + case PitchGridMode::Chromatic: + snappedMidi = std::round(baseMidi); + break; + case PitchGridMode::KeyScale: + snappedMidi = scaleSnap.value_or(ScaleSnapConfig{}).quantizeMidiToActiveScale(baseMidi); + break; + } + const float snappedOffset = snappedMidi - baseMidi; + if (std::abs(snappedOffset - note.pitchOffset) < 0.001f) + continue; + note.pitchOffset = snappedOffset; + note.dirty = true; + changed.push_back(index); + } + + if (changed.empty()) { + // Already on the grid (or snapping is off): announce the current pitch. + notifyKeyboardNote(KeyboardNoteEvent::PitchMoved, notes, selected.front()); + return true; + } + if (commitKeyboardNoteEdit(work, changed, LOC_RAW("Pitch snap"))) + notifyKeyboardNote(KeyboardNoteEvent::PitchMoved, work, changed.front()); return true; } -void PianoRollToolHandler::moveSelectedNotesPitchByKeyboard(int direction) +void PianoRollToolHandler::switchToolFromKeyboard(ToolId tool) +{ + ctx_.setCurrentTool(tool); + if (ctx_.notifyToolChangedFromKeyboard) + ctx_.notifyToolChangedFromKeyboard(tool); +} + +void PianoRollToolHandler::moveSelectedNotesPitchByKeyboard(int direction, bool fineCents, bool resetToSung, + bool semitoneIgnoringScale) { const auto& notes = committedNotes(ctx_); const auto selectedIndices = collectSelectedNoteIndices(notes); - if (selectedIndices.empty()) + if (selectedIndices.empty()) { + notifyKeyboardNote(notes.empty() ? KeyboardNoteEvent::NoNotes : KeyboardNoteEvent::NoSelection, + notes, -1); return; + } const bool openDyne = AudioEditingScheme::usesNotesPrimaryScheme(ctx_.getAudioEditingScheme()); const bool standardPitch = !openDyne @@ -810,7 +1481,18 @@ void PianoRollToolHandler::moveSelectedNotesPitchByKeyboard(int direction) const float initialOffset = note.pitchOffset; const float currentMidi = baseMidi + initialOffset; float targetMidi = currentMidi; - if (noSnap) { + if (resetToSung) { + // originalPitch is the sung pitch; notes without it have nothing to return to. + if (note.originalPitch > 0.0f) + targetMidi = PitchUtils::freqToMidi(note.originalPitch); + } else if (fineCents) { + targetMidi += static_cast(direction) * 0.01f; + } else if (semitoneIgnoringScale) { + // To the next whole semitone, whatever the grid mode. + targetMidi = direction > 0 + ? std::floor(currentMidi) + 1.0f + : std::ceil(currentMidi) - 1.0f; + } else if (noSnap) { targetMidi += static_cast(direction) * 0.01f; } else if (scaleSnapEnabled) { const float firstCandidate = direction > 0 @@ -838,13 +1520,19 @@ void PianoRollToolHandler::moveSelectedNotesPitchByKeyboard(int direction) rangeStart = std::min(rangeStart, note.startTime); rangeEnd = std::max(rangeEnd, note.endTime); } - if (changedOffsets.empty()) + if (changedOffsets.empty()) { + // Resetting a note that is already at its sung pitch: still say the pitch, so R is not silent. + if (resetToSung) + notifyKeyboardNote(KeyboardNoteEvent::PitchMoved, notes, selectedIndices.front()); return; + } const F0FrameRange editRange = ctx_.getF0Timeline().rangeForTimes(rangeStart, rangeEnd); const auto contentSnapshot = ctx_.getEditableContentSnapshot(); - if (editRange.isEmpty() || contentSnapshot == nullptr || contentSnapshot->pitchCurve == nullptr) + if (editRange.isEmpty() || contentSnapshot == nullptr || contentSnapshot->pitchCurve == nullptr) { + notifyKeyboardNote(KeyboardNoteEvent::EditFailed, notes, -1); return; + } ctx_.beginNoteDraft(); auto& draft = ctx_.getNoteDraft(); @@ -855,6 +1543,7 @@ void PianoRollToolHandler::moveSelectedNotesPitchByKeyboard(int direction) ctx_.clearNoteDraft(); if (!committed) { ctx_.setUndoDescription({}); + notifyKeyboardNote(KeyboardNoteEvent::EditFailed, committedNotes(ctx_), -1); return; } @@ -862,6 +1551,8 @@ void PianoRollToolHandler::moveSelectedNotesPitchByKeyboard(int direction) ctx_.notifyNoteOffsetChanged(static_cast(noteIndex), oldOffset, workingNotes[static_cast(noteIndex)].pitchOffset); } + // workingNotes rather than committedNotes: it is guaranteed to hold the new pitch. + notifyKeyboardNote(KeyboardNoteEvent::PitchMoved, workingNotes, changedOffsets.front().first); } bool PianoRollToolHandler::isEmptySpaceMouseDown(const juce::MouseEvent& e) @@ -1042,15 +1733,20 @@ void PianoRollToolHandler::handleDeleteKey() { const auto& notes = committedNotes(ctx_); const auto selectedIndices = collectSelectedNoteIndices(notes); - if (selectedIndices.empty()) + if (selectedIndices.empty()) { + // Otherwise Delete did nothing and said nothing. + notifyKeyboardNote(notes.empty() ? KeyboardNoteEvent::NoNotes : KeyboardNoteEvent::NoSelection, + notes, -1); return; + } auto result = ctx_.deleteSelectedPianoRollNotes( selectedIndices, ctx_.getNotesRevision(), LOC_RAW("Delete note")); - if (result.status == SelectedNoteDeleteStatus::StaleRevision) - return; - if (result.status != SelectedNoteDeleteStatus::Applied) + if (result.status != SelectedNoteDeleteStatus::Applied) { + // Delete also sits on Backspace and "1": a press that did nothing must be heard too. + notifyKeyboardNote(KeyboardNoteEvent::EditFailed, committedNotes(ctx_), -1); return; + } if (result.pitchCurveEdited) { ctx_.notifyPitchCurveEdited(result.affectedRange.startFrame, @@ -1058,6 +1754,19 @@ void PianoRollToolHandler::handleDeleteKey() } if (ctx_.invalidateLiveNotes) ctx_.invalidateLiveNotes(result.beforeNotes, result.contentSnapshot->notes); + + // Accessibility: keep the place in the note list. The note after the removed ones + // (or the last note) becomes selected, so the arrows go on from here. + const auto& afterNotes = committedNotes(ctx_); + if (!afterNotes.empty()) { + const int firstRemoved = *std::min_element(selectedIndices.begin(), selectedIndices.end()); + const int neighbour = juce::jmin(firstRemoved, static_cast(afterNotes.size()) - 1); + ctx_.getState().noteSelection.setSingle(neighbour, static_cast(afterNotes.size())); + if (ctx_.invalidateSelectionFeedback) + ctx_.invalidateSelectionFeedback(); + } + // Delete also sits on Backspace and "1", so an accidental press must be heard. + notifyKeyboardNote(KeyboardNoteEvent::Removed, afterNotes, static_cast(selectedIndices.size())); } void PianoRollToolHandler::handleSelectTool(const juce::MouseEvent& e) @@ -2352,6 +3061,57 @@ void PianoRollToolHandler::handleVolumeEnvelopeToolDoubleClick(const juce::Mouse LOC(kToolVolumeEnvelope)); } +// Keyboard version of the Volume Envelope drag: every selected note keeps its own level +// and gets the same step, exactly like buildVolumeEnvelopeDragPreview. +void PianoRollToolHandler::adjustSelectedNotesVolumeByKeyboard(int direction, bool fine) +{ + const auto& notes = committedNotes(ctx_); + const auto selected = collectSelectedNoteIndices(notes); + if (selected.empty()) { + notifyKeyboardNote(notes.empty() ? KeyboardNoteEvent::NoNotes : KeyboardNoteEvent::NoSelection, notes, -1); + return; + } + if (!ctx_.editVolumeEnvelopeRegions) + return; + + // Same transaction as the mouse drag: every selected note keeps its own level and + // gets the same step (1 dB, Alt 0.1 dB). + const float step = static_cast(direction) * (fine ? 0.1f : 1.0f); + const auto result = ctx_.editVolumeEnvelopeRegions(selected, ctx_.getNotesRevision(), step, + LOC(kToolVolumeEnvelope)); + if (result.status == VolumeEnvelopeRegionEditStatus::StaleRevision + || result.status == VolumeEnvelopeRegionEditStatus::Failed) { + notifyKeyboardNote(KeyboardNoteEvent::EditFailed, committedNotes(ctx_), -1); + return; + } + // NoChange: at the limit; stay silent, as at list ends. + if (result.status != VolumeEnvelopeRegionEditStatus::Applied) + return; + notifyKeyboardNote(KeyboardNoteEvent::VolumeChanged, committedNotes(ctx_), selected.front()); +} + +// Enter with the Volume Envelope tool, like its double-click: back to 0 dB. +void PianoRollToolHandler::resetSelectedNotesVolumeByKeyboard() +{ + const auto& notes = committedNotes(ctx_); + const auto selected = collectSelectedNoteIndices(notes); + if (selected.empty() || !ctx_.resetVolumeEnvelopeRegion) + return; + + // The double-click resets one note; the keyboard resets each selected note the same way. + // A note already at 0 dB gives NoChange and nothing is committed, but the level is still said. + for (int index : selected) { + const auto result = ctx_.resetVolumeEnvelopeRegion(index, ctx_.getNotesRevision(), LOC(kToolVolumeEnvelope)); + // After a failure the other indices may point at different notes: stop here. + if (result.status == VolumeEnvelopeRegionEditStatus::StaleRevision + || result.status == VolumeEnvelopeRegionEditStatus::Failed) { + notifyKeyboardNote(KeyboardNoteEvent::EditFailed, committedNotes(ctx_), -1); + return; + } + } + notifyKeyboardNote(KeyboardNoteEvent::VolumeChanged, committedNotes(ctx_), selected.front()); +} + void PianoRollToolHandler::updateScissorsPreview(const juce::MouseEvent& e) { auto& state = ctx_.getState(); diff --git a/Source/Standalone/UI/PianoRoll/PianoRollToolHandler.h b/Source/Standalone/UI/PianoRoll/PianoRollToolHandler.h index 899c6131..a6262e35 100644 --- a/Source/Standalone/UI/PianoRoll/PianoRollToolHandler.h +++ b/Source/Standalone/UI/PianoRoll/PianoRollToolHandler.h @@ -84,6 +84,35 @@ class PianoRollToolHandler public: using ManualCorrectionOp = OpenTune::ManualCorrectionOp; + // What happened to a note during keyboard editing - drives speech and audition. + enum class KeyboardNoteEvent + { + Selected, // moved to a note with an arrow, Home or End + PitchMoved, // pitch moved with Up/Down + Info, // full details requested (I key) + NoNotes, // there are no notes at all + NoSelection, // notes exist but none is selected + Split, // X: split at the largest pitch change, index is the left part + Merged, // J: note merged with the next one, index is the result + SplitInHalf, // X: no clear pitch change, split in the middle + NoteTooShort, // X: note shorter than two minimal parts + SplitAtCursor, // Shift+X: index is the left part + CursorUnknown, // Shift+X: the host edit cursor is not known (not REAPER, or playing) + CursorOutsideNote, // Shift+X: the edit cursor is not inside the selected note + NoAdjacentNote, // J: no touching next note + AllSelected, // Ctrl+A: all notes selected + ModulationChanged, // arrows or Enter with the Pitch Modulation tool + DriftChanged, // arrows or Enter with the Pitch Drift tool + Removed, // Delete or Cut: index is the number of removed notes + VolumeChanged, // arrows or Enter with the Volume Envelope tool + ArrowHint, // plain Up/Down: say that Ctrl+Up/Down edits (index unused) + PositionInfo, // Shift+I: say where in the song the cursor actions work (index unused) + RangeSelected, // Shift+Left/Right: index is the note at the moving end + NoteResized, // Ctrl(+Shift)+Left/Right: index is the resized note + SingleNoteNeeded, // the action works on one selected note only + EditFailed // the edit was not committed (e.g. the notes changed meanwhile) + }; + // PianoRoll 组件提供的回调上下文。 // 所有数据读写均通过这些 std::function 回调完成, // 使 ToolHandler 可独立于具体组件实例进行测试。 @@ -179,8 +208,15 @@ class PianoRollToolHandler std::function notifyPlayPauseToggle; std::function notifyStopPlayback; bool transportShortcutsEnabled = true; - std::function notifyEscapeKey; + // Returns false when Esc is not used here and should go on to the host. + std::function notifyEscapeKey; std::function notifyNoteOffsetChanged; + // notes is the current list (after a move it already holds the new pitch), index is a note or -1. + std::function&, int)> notifyKeyboardNote; + // Accessibility: REAPER's edit cursor in source seconds while the transport is stopped. + std::function()> getEditCursorSourceTime; + // Tool switched by a key: the screen reader announces the new tool. + std::function notifyToolChangedFromKeyboard; // === Note pitch audition (piano roll trigger/lifecycle) === // startSeconds/endSeconds/targetHz: anchor note range + adjusted pitch. @@ -191,6 +227,8 @@ class PianoRollToolHandler // 打开 EQ 弹窗预览:参数为主音符 index(纯点击 = mouseDown 记录的 pending // 主音符;框选 = 完成选择后的 anchor 音符)。只打开弹窗,不改 Note 数据。 std::function openEqPreview; + // Accessibility: Enter with the EQ tool opens the full EQ window with keyboard focus. + std::function openEqFromKeyboard; // EQ 工具专属光标(组件侧构造一次,值拷贝共享 handle)。 juce::MouseCursor eqCursor; @@ -308,7 +346,21 @@ class PianoRollToolHandler // §8.4: Delete key removes selected handle (non-endpoint). bool handleTimeToolDeleteSelected(); bool handleNoteArrowKey(const juce::KeyPress& key); - void moveSelectedNotesPitchByKeyboard(int direction); + void moveSelectedNotesPitchByKeyboard(int direction, bool fineCents = false, bool resetToSung = false, + bool semitoneIgnoringScale = false); + void selectNoteFromKeyboard(const std::vector& notes, int index); + void extendSelectionByKeyboard(bool moveRight); + void resizeSelectedNoteByKeyboard(bool startEdge, int direction); + void notifyKeyboardNote(KeyboardNoteEvent event, const std::vector& notes, int index); + void splitSelectedNoteByKeyboard(bool atEditCursor = false); + void mergeSelectedNoteWithNext(); + void adjustSelectedNotesModDriftByKeyboard(int direction, bool fine); + void adjustSelectedNotesVolumeByKeyboard(int direction, bool fine); + void resetSelectedNotesVolumeByKeyboard(); + bool applyNoteDefaultActionByKeyboard(); + void switchToolFromKeyboard(ToolId tool); + bool commitKeyboardNoteEdit(const std::vector& work, const std::vector& changedIndices, + const juce::String& undoDescription); // Hit-test handles within ±5 px of a TimeGrid handle's output_seconds. // Returns 0 if no hit. uint64_t hitTestTimeGridHandle(const juce::MouseEvent& e) const; @@ -374,6 +426,8 @@ class PianoRollToolHandler // Scissors 自定义双击检测:记录上一次点击的时间戳和位置 // 在 handleScissorsToolUp 中检测:800ms / 30px 内的同位置点击触发合并。 + // Accessibility: the edit cursor (source seconds) at the last Left/Right press. + std::optional lastArrowCursor_; std::chrono::steady_clock::time_point scissorsLastClickTime_{}; juce::Point scissorsLastClickPos_{}; static constexpr int kScissorsDoubleClickMs = 800; // 800ms 双击阈值 @@ -390,6 +444,9 @@ class PianoRollToolHandler // EQ 工具:mouseDown 命中的 pending 主音符 index(纯点击 mouseUp 时消费一次)。 // 拖拽超过阈值转为框选时、setTool/cancelActiveMouseGesture 时清理。 int pendingEqPrimaryIndex_ = -1; + // Shift+Left/Right range: the fixed end and the moving end (note indices). + int keyboardRangeAnchor_ = -1; + int keyboardRangeActive_ = -1; double lastDrawTime_ = 0.0; float lastDrawF0_ = 0.0f; AutomationLane volumeDragBaselineEnvelope_; diff --git a/Source/Standalone/UI/PianoRollComponent.cpp b/Source/Standalone/UI/PianoRollComponent.cpp index e3827dfb..40bf3859 100644 --- a/Source/Standalone/UI/PianoRollComponent.cpp +++ b/Source/Standalone/UI/PianoRollComponent.cpp @@ -26,6 +26,11 @@ #include "../../Utils/ScaleUiMapping.h" #include "../../Utils/PitchUtils.h" #include "Utils/PianoKeyAudition.h" +#include "Utils/NoteAudition.h" +#include "Utils/NoteSpeech.h" +#include "Utils/ScreenReaderAnnouncer.h" +#include "Utils/TimeCoordinate.h" +#include "Inference/RenderCache.h" #include "TimelineViewportPolicy.h" #include "TimelineLayerComposer.h" #include "PianoRoll/PianoRollTimeMap.h" @@ -136,6 +141,12 @@ void PianoRollComponent::initializeUIComponents() { verticalZoomInButton_.onClick = [this] { zoomVerticalIn(); }; addAndMakeVisible(verticalZoomInButton_); + // Accessibility: zoom is only for the eyes and has keyboard shortcuts; NVDA object + // navigation read these as unnamed "+" / "-" buttons inside the notes list. + for (auto* button : { &horizontalZoomOutButton_, &horizontalZoomInButton_, + &verticalZoomOutButton_, &verticalZoomInButton_ }) + button->setAccessible(false); + updateZoomControlColours(); scrollVBlankAttachment_ = std::make_unique( @@ -500,6 +511,8 @@ PianoRollToolHandler::Context PianoRollComponent::buildToolHandlerContext() { toolCtx.setCurrentTool = [this](ToolId tool) { setCurrentTool(tool); }; // EQ 工具:主音符 index 由 ToolHandler 唯一判定并直通;EQ cursor 经主题机制应用 toolCtx.openEqPreview = [this](int primaryIndex) { openEqPopupForSelection(primaryIndex); }; + toolCtx.openEqFromKeyboard = [this](int primaryIndex) { openEqPopupForSelection(primaryIndex, true); }; + toolCtx.getEditCursorSourceTime = [this]() { return stoppedEditCursorSourceTime(); }; toolCtx.eqCursor = eqCursor_; toolCtx.showToolSelectionMenu = [this]() { // 在当前鼠标屏幕位置弹出纵向图标工具栏 @@ -510,10 +523,35 @@ PianoRollToolHandler::Context PianoRollComponent::buildToolHandlerContext() { toolCtx.notifyPlayPauseToggle = [this]() { listeners_.call([](Listener& l) { l.playPauseToggleRequested(); }); }; toolCtx.notifyStopPlayback = [this]() { listeners_.call([](Listener& l) { l.stopPlaybackRequested(); }); }; toolCtx.transportShortcutsEnabled = transportControlsEnabled_; - toolCtx.notifyEscapeKey = [this]() { listeners_.call([](Listener& l) { l.escapeKeyPressed(); }); }; + toolCtx.notifyEscapeKey = [this]() { + // Accessibility: an open EQ window closes first. + if (eqPopup_ != nullptr) { + closeEqPopup(); + a11y::announce(*this, LOC_RAW("EQ closed")); + return true; + } + // In the plugin Esc has no job of its own; the host gets it, so it closes the FX + // window as in other plugins instead of the key being swallowed silently. + if (escapePassesToHost_) + return false; + listeners_.call([](Listener& l) { l.escapeKeyPressed(); }); + return true; + }; toolCtx.notifyNoteOffsetChanged = [this](size_t noteIndex, float oldOffset, float newOffset) { listeners_.call([noteIndex, oldOffset, newOffset](Listener& l) { l.noteOffsetChanged(noteIndex, oldOffset, newOffset); }); }; + toolCtx.notifyKeyboardNote = [this](PianoRollToolHandler::KeyboardNoteEvent event, + const std::vector& notes, int index) { + handleKeyboardNote(event, notes, index); + }; + toolCtx.notifyToolChangedFromKeyboard = [this](ToolId tool) { + auto name = keyboardToolName(tool); + // The EQ tool does nothing by itself from the keyboard; say how to open the window. + if (tool == ToolId::Eq && name.isNotEmpty()) + name << ", " << LOC_RAW("Enter opens it"); + if (name.isNotEmpty()) + a11y::announce(*this, name); + }; toolCtx.auditionNotePitch = [this](double start, double end, float targetHz) { if (processor_ != nullptr) processor_->auditionNotePitch(editedContentKey_, start, end, targetHz); }; @@ -672,6 +710,87 @@ juce::Path makeToolIcon(ToolId id) { } // namespace +bool PianoRollComponent::keyStateChanged(bool isKeyDown) +{ + // The Applications (menu) key never reaches keyPressed in JUCE. + if (applicationsKey_.pressedNow() && isKeyDown) { + showToolMenuFromKeyboard(); + return true; + } + return juce::Component::keyStateChanged(isKeyDown); +} + +// Keyboard twin of the right-click tool bar (showToolSelectionBar): a standard PopupMenu, +// which JUCE makes navigable with arrows and readable by screen readers. The tool list +// follows showToolSelectionBar; keep both in sync. +void PianoRollComponent::showToolMenuFromKeyboard() +{ + using Id = KeyShortcutConfig::ShortcutId; + struct Entry { ToolId tool; juce::String name; Id shortcut; }; + std::vector entries; + if (isOpenDyne()) { + entries = { + { ToolId::Select, LOC(kToolODSelect), Id::ToolODSelect }, + { ToolId::Pitch, LOC(kToolODPitch), Id::ToolODPitch }, + { ToolId::PitchModulation, LOC(kToolODPitchModulation), Id::ToolODPitchModulation }, + { ToolId::PitchDrift, LOC(kToolODPitchDrift), Id::ToolODPitchDrift }, + { ToolId::HandDraw, LOC(kToolHandDraw), Id::ToolHandDraw }, + { ToolId::Eraser, LOC(kEraser), Id::Count }, + { ToolId::VolumeEnvelope, LOC(kToolODVolumeEnvelope), Id::ToolODVolumeEnvelope }, + }; + if (experimentalFeaturesEnabled_) + entries.push_back({ ToolId::TimeTool, LOC(kTime), Id::ToolTimeTool }); + entries.push_back({ ToolId::Scissors, LOC(kToolODScissors), Id::ToolODScissors }); + entries.push_back({ ToolId::Eq, LOC(kToolEq), Id::Eq }); + } else { + entries = { + { ToolId::Select, LOC(kToolSelect), Id::ToolSelect }, + { ToolId::DrawNote, LOC(kToolDrawNote), Id::ToolDrawNote }, + { ToolId::LineAnchor, LOC(kToolLineAnchor), Id::ToolLineAnchor }, + { ToolId::HandDraw, LOC(kToolHandDraw), Id::ToolHandDraw }, + { ToolId::Eraser, LOC(kEraser), Id::Count }, + }; + if (experimentalFeaturesEnabled_) + entries.push_back({ ToolId::TimeTool, LOC(kTime), Id::ToolTimeTool }); + } + + juce::PopupMenu menu; + for (const auto& entry : entries) { + juce::PopupMenu::Item item(entry.name); + item.itemID = static_cast(entry.tool) + 1; // 0 means "cancelled" + item.isTicked = currentTool_ == entry.tool; + // The real binding, so a user's own shortcut is shown, not the default. + if (entry.shortcut != Id::Count) + item.shortcutKeyDescription = KeyShortcutConfig::getShortcutBinding(shortcutSettings_, entry.shortcut) + .getDisplayNames(); + menu.addItem(std::move(item)); + } + + // Open on the current tool, highlighted, so Enter works at once (without a highlight JUCE + // ignores the first Enter although NVDA already reads an item). + auto options = juce::PopupMenu::Options().withTargetComponent(this); + const bool currentListed = std::any_of(entries.begin(), entries.end(), + [this](const Entry& entry) { return entry.tool == currentTool_; }); + if (currentListed) + options = options.withInitiallySelectedItem(static_cast(currentTool_) + 1); + else if (const int firstId = a11y::firstSelectableItemId(menu); firstId != 0) + options = options.withInitiallySelectedItem(firstId); + + juce::Component::SafePointer safeThis(this); + menu.showMenuAsync(options, + [safeThis](int result) { + if (safeThis == nullptr) + return; + // Bring focus back to the notes whether a tool was chosen or Esc pressed. + safeThis->grabKeyboardFocus(); + if (result > 0) { + const auto tool = static_cast(result - 1); + safeThis->setCurrentTool(tool); + a11y::announce(*safeThis, safeThis->keyboardToolName(tool)); + } + }); +} + void PianoRollComponent::showToolSelectionBar(juce::Point screenPos) { dismissToolPopup(); @@ -1018,6 +1137,10 @@ PianoRollComponent::PianoRollComponent(const PlayHeadState& playHeadState, overlay_ = std::make_unique(*this); addAndMakeVisible(*overlay_); overlay_->setInterceptsMouseClicks(false, false); + // The overlay only paints on top of the notes; screen readers do not need it. + overlay_->setAccessible(false); + // The vertical scroll bar is mouse-only; NVDA read it as "scroll bar 0". + verticalScrollBar_.setAccessible(false); } PianoRollComponent::~PianoRollComponent() { @@ -1205,7 +1328,7 @@ void PianoRollComponent::clearNoteDraft() // EQ 工具:预览弹窗(PianoRollComponent 唯一持有)与选中组原子提交 // ============================================================================ -void PianoRollComponent::openEqPopupForSelection(int primaryIndex) +void PianoRollComponent::openEqPopupForSelection(int primaryIndex, bool fromKeyboard) { closeEqPopup(); @@ -1227,11 +1350,25 @@ void PianoRollComponent::openEqPopupForSelection(int primaryIndex) if (appPreferences_ != nullptr) eqPopup_->setRemoveConfirmationSuppressed(appPreferences_->getState().shared.suppressEqRemoveConfirmation); eqPopup_->onCommitSettings = [this](const EqSettings& settings) { applyEqSettingsToSelection(settings); }; + // Accessibility: closed from the keyboard, focus is back on the notes (closeEqPopup) and the result is said. + // closeEqPopup deletes the popup and this lambda with it, so the captured pointer is + // copied to the stack first and only the copy is used afterwards. eqPopup_->onRemoveEq = [this]() { - if (removeEqFromSelection()) - closeEqPopup(); + auto* self = this; + const bool fromKeyboard = eqPopup_ != nullptr && eqPopup_->hasKeyboardFocus(true); + if (!self->removeEqFromSelection()) + return; + self->closeEqPopup(); + if (fromKeyboard) + a11y::announce(*self, LOC_RAW("EQ removed"), a11y::SpeechQueue::keepAll); + }; + eqPopup_->onClose = [this]() { + auto* self = this; + const bool fromKeyboard = eqPopup_ != nullptr && eqPopup_->hasKeyboardFocus(true); + self->closeEqPopup(); + if (fromKeyboard) + a11y::announce(*self, LOC_RAW("EQ closed"), a11y::SpeechQueue::keepAll); }; - eqPopup_->onClose = [this]() { closeEqPopup(); }; eqPopup_->onReadSpectrum = [this](SpectrumArray& spectrum, SpectrumArray& peaks) { spectrumReader_(spectrum, peaks); @@ -1251,16 +1388,27 @@ void PianoRollComponent::openEqPopupForSelection(int primaryIndex) anchor = getNoteBounds(primary); eqPopup_->setBounds(placeEqPopupBounds(anchor)); eqPopup_->toFront(false); + // Accessibility: from the keyboard the window opens full size with focus on it; + // NVDA reads its title ("EQ, Band 1 of 3, Type, Low shelf"). + if (fromKeyboard) + eqPopup_->startKeyboardEditing(); } void PianoRollComponent::closeEqPopup() { + // A keyboard change still waiting to be committed must reach the notes first. + if (eqPopup_ != nullptr) + eqPopup_->flushPendingCommit(); eqEditTargetIndices_.clear(); eqEditRevision_ = 0; if (eqPopup_ == nullptr) return; + // Focus inside the window would be lost with it; give it back to the notes. + const bool hadFocus = eqPopup_->hasKeyboardFocus(true); removeChildComponent(eqPopup_.get()); eqPopup_.reset(); + if (hadFocus && isShowing()) + grabKeyboardFocus(); } void PianoRollComponent::invalidateEqPopup() @@ -1276,7 +1424,13 @@ void PianoRollComponent::invalidateEqPopup() eqPopup_->onRemoveConfirmationSuppressed = {}; eqPopup_->onReadSpectrum = {}; eqPopup_->stopTimer(); + // Accessibility: hiding the window would drop the keyboard focus into nowhere. + const bool hadFocus = eqPopup_->hasKeyboardFocus(true); eqPopup_->setVisible(false); + if (hadFocus && isShowing()) { + grabKeyboardFocus(); + a11y::announce(*this, LOC_RAW("EQ closed"), a11y::SpeechQueue::keepAll); + } juce::Component::SafePointer safeThis(this); juce::Component::SafePointer safePopup(eqPopup_.get()); juce::MessageManager::callAsync([safeThis, safePopup]() { @@ -3052,6 +3206,26 @@ bool PianoRollComponent::getSingleSelectedNoteParameters(float& retuneSpeedPerce return true; } +juce::String PianoRollComponent::describeParameterEdit(AudioEditingScheme::ParameterId id, + const AudioEditingScheme::ParameterEditResult& result) const +{ + using Status = AudioEditingScheme::ParameterEditStatus; + if (result.status == Status::NoTarget) + return LOC_RAW("Default for new notes"); + if (result.status == Status::Failed) { + if (!currentCurve_ || currentF0Timeline().isEmpty()) + return LOC_RAW("No pitch data, read the audio first"); + return LOC_RAW("Could not apply"); + } + // Note Split cuts the notes again, so the new count is what changed. + if (id == AudioEditingScheme::ParameterId::NoteSplit) + return Loc::format(LOC_RAW("Notes now: {0}"), juce::String(static_cast(getCommittedNotes().size()))); + const auto count = static_cast(interactionState_.noteSelection.selectedIndices.size()); + if (count > 0) + return Loc::format(LOC_RAW("Applied to notes: {0}"), juce::String(count)); + return LOC_RAW("Applied to the selection"); +} + AudioEditingScheme::ParameterEditResult PianoRollComponent::editParameter(AudioEditingScheme::ParameterId id, float value) { AudioEditingScheme::ParameterEditResult result; @@ -4210,6 +4384,7 @@ void PianoRollComponent::onScrollVBlankCallback(double timestampSec) userScrollHold_ = false; lastObservedPlayHeadPlaying_ = playingNow; } + trackReaperTransport(); double playheadTime = playHeadState_.getPresentedPositionSeconds(); if (pendingSeekTime_ >= 0.0) { @@ -5580,11 +5755,64 @@ void PianoRollComponent::copySelectedNotes() if (idx >= 0 && idx < static_cast(notes.size())) notesClipboard_.push_back(notes[static_cast(idx)]); } + a11y::announce(*this, Loc::format(LOC_RAW("Notes copied: {0}"), + juce::String(static_cast(notesClipboard_.size())))); +} + +// Accessibility: follow REAPER's own transport state, read on every frame, to know the +// edit cursor at the moment playback paused (so a later cursor move can be noticed). +void PianoRollComponent::trackReaperTransport() +{ + const auto transport = processor_ != nullptr ? processor_->getReaperTransport() : std::nullopt; + if (!transport) + return; + + if (transport->playState != lastReaperPlayState_) { + const bool wasRunning = (lastReaperPlayState_ & (1 | 4)) != 0; + if (wasRunning && !transport->isRunning()) + haltEditCursor_ = transport->editCursor; + lastReaperPlayState_ = transport->playState; + } +} + +std::optional PianoRollComponent::currentSongPosition() const +{ + const auto transport = processor_ != nullptr ? processor_->getReaperTransport() : std::nullopt; + if (!transport || transport->isRunning()) + return std::nullopt; + + // The same place REAPER announces. Paused: where playback paused, unless the edit cursor + // was moved during the pause. Stopped: the edit cursor (REAPER itself decides whether a + // stop moves it; the plugin's own guess was a quarter second off in a user test). + if (transport->isPaused()) { + const bool cursorMoved = haltEditCursor_ && std::abs(transport->editCursor - *haltEditCursor_) > 1.0e-6; + return cursorMoved ? SongPosition{ transport->editCursor, SongPosition::Source::EditCursor } + : SongPosition{ transport->playPosition, SongPosition::Source::Paused }; + } + return SongPosition{ transport->editCursor, SongPosition::Source::EditCursor }; +} + +std::optional PianoRollComponent::stoppedEditCursorSourceTime() const +{ + const auto position = currentSongPosition(); + if (!position) + return std::nullopt; + const auto cursor = std::optional(position->seconds); + // Project (timeline) seconds to the clip's source seconds, as for the playhead in pasteNotes. + const auto projection = activeContentProjection(); + const auto snap = readEditedSnapshot(); + if (!projection.isValid() || !snap) + return std::nullopt; + const PianoRollTimeMap map(projection, *snap->timeGrid, makeViewMapper()); + return map.timelineToSource(*cursor); } void PianoRollComponent::pasteNotes() { - if (notesClipboard_.empty()) return; + if (notesClipboard_.empty()) { + a11y::announce(*this, LOC_RAW("Nothing to paste")); + return; + } if (contentCommands_ == nullptr || !editedContentKey_.isValid()) return; if (processor_ == nullptr) return; @@ -5596,7 +5824,10 @@ void PianoRollComponent::pasteNotes() // → PianoRollTimeMap::timelineToSource() // → source seconds double pasteStartTime = 0.0; - const double playheadTime = playHeadState_.getPresentedPositionSeconds(); + // Accessibility: with REAPER stopped the plugin's playhead is where playback last + // stopped, not where the user moved the edit cursor; ask REAPER for the cursor then. + const auto songPosition = currentSongPosition(); + const double playheadTime = songPosition ? songPosition->seconds : playHeadState_.getPresentedPositionSeconds(); if (playheadTime > 0.0) { const auto projection = activeContentProjection(); const auto snap = readEditedSnapshot(); @@ -5658,6 +5889,12 @@ void PianoRollComponent::pasteNotes() requestContentRedraw(); overlay_->repaint(); listeners_.call([](Listener& listener) { listener.contentEdited(); }); + + // Paste lands at the plugin's playhead, which goes stale while the host is stopped, + // so say where the notes went (project time, as in the host). + a11y::announce(*this, Loc::format(LOC_RAW("Notes pasted: {0}, start {1} s"), + juce::String(static_cast(result.pastedNotes.size())), + juce::String(sourceTimeToTimelineTime(pasteStartTime), 2))); } void PianoRollComponent::duplicateNotes() @@ -5753,6 +5990,12 @@ bool PianoRollComponent::handlePointerShortcut(const KeyShortcutConfig::KeyBindi } bool PianoRollComponent::keyPressed(const juce::KeyPress& key) { + // Shift+F10 opens what the right-click opens: the tool menu. + if (a11y::isContextMenuKey(key)) { + showToolMenuFromKeyboard(); + return true; + } + if (handleViewportShortcut(key)) return true; @@ -6333,4 +6576,436 @@ ViewMapper PianoRollComponent::makeViewMapperForView(const ViewportState& view) }; } +// ============================================================================ +// Accessibility: piano roll for screen readers, note speech and keyboard audition +// ============================================================================ + +std::unique_ptr PianoRollComponent::createAccessibilityHandler() +{ + // The title is computed on every request so NVDA+Up Arrow reads the current note + // without timers or extra events. + class NotesAccessibilityHandler final : public juce::AccessibilityHandler { + public: + explicit NotesAccessibilityHandler(PianoRollComponent& owner) + : juce::AccessibilityHandler(owner, juce::AccessibilityRole::list), owner_(owner) {} + + juce::String getTitle() const override + { + juce::String title = LOC_RAW("Notes"); + const auto& selected = owner_.interactionState_.noteSelection.selectedIndices; + if (selected.size() == 1) { + const auto line = owner_.describeKeyboardNote(owner_.getCommittedNotes(), selected.front(), + PianoRollComponent::NoteDetail::Navigation); + if (line.isNotEmpty()) + title << ", " << line; + } else if (selected.size() > 1) { + title << ", " << Loc::format(LOC_RAW("{0} selected"), juce::String(static_cast(selected.size()))); + } + return title; + } + + private: + PianoRollComponent& owner_; + }; + + return std::make_unique(*this); +} + +juce::String PianoRollComponent::describeKeyboardNote(const std::vector& notes, int index, + NoteDetail detail) const +{ + if (index < 0 || index >= static_cast(notes.size())) + return {}; + + const auto& note = notes[static_cast(index)]; + // originalPitch is the sung pitch; old projects and drawn notes may not have it. + const float sungHz = note.originalPitch > 0.0f ? note.originalPitch : note.pitch; + if (sungHz <= 0.0f) + return {}; + + const float sungMidi = PitchUtils::freqToMidi(sungHz); + const float targetMidi = note.pitch > 0.0f ? PitchUtils::freqToMidi(note.pitch) + note.pitchOffset + : sungMidi; + const std::string sharpWord = LOC_RAW("sharp").toStdString(); + const auto text = [&sharpWord](float midi) { + return juce::String::fromUTF8(NoteSpeech::describeMidi(midi, sharpWord).c_str()); + }; + + // When navigating and after a move, speak only how the note sounds now (the target). + // The sung pitch and the rest are spoken by the I key (NoteDetail::Full). + if (detail == NoteDetail::Target) + return text(targetMidi); + if (detail == NoteDetail::Navigation) { + // With the modulation or drift tool add its value: that is what is being edited. + juce::String line = text(targetMidi); + if (currentTool_ == ToolId::PitchModulation) + line << ", " << Loc::format(LOC_RAW("modulation {0}"), modulationPercentText(note)); + else if (currentTool_ == ToolId::PitchDrift) + line << ", " << Loc::format(LOC_RAW("drift {0}"), driftPercentText(note)); + else if (currentTool_ == ToolId::VolumeEnvelope) + line << ", " << Loc::format(LOC_RAW("volume {0}"), volumeText(note)); + return line; + } + + // Times are on the project timeline, as in the host, not inside the audio file. + const double timelineStart = sourceTimeToTimelineTime(note.startTime); + const double timelineEnd = sourceTimeToTimelineTime(note.endTime); + + // Ordinal by start time, not by array position. + int ordinal = 1; + for (const auto& other : notes) + if (other.startTime < note.startTime) + ++ordinal; + + juce::String line = Loc::format(LOC_RAW("Note {0} of {1}"), + juce::String(ordinal), juce::String(static_cast(notes.size()))); + line << ", " << Loc::format(LOC_RAW("sung {0}"), text(sungMidi)) + << ", " << Loc::format(LOC_RAW("target {0}"), text(targetMidi)) + << ", " << Loc::format(LOC_RAW("start {0} s, length {1} s"), + juce::String(timelineStart, 2), juce::String(timelineEnd - timelineStart, 2)); + if (isOpenDyne()) { + line << ", " << Loc::format(LOC_RAW("modulation {0}"), modulationPercentText(note)) + << ", " << Loc::format(LOC_RAW("drift {0}"), driftPercentText(note)) + << ", " << Loc::format(LOC_RAW("volume {0}"), volumeText(note)); + } + return line; +} + +// Note level from the volume envelope (the same value the Volume Envelope drag edits). +juce::String PianoRollComponent::volumeText(const Note& note) const +{ + const auto snap = readEditedSnapshot(); + const float db = snap != nullptr ? snap->volumeEnvelope.evalAt(note.startTime) : 0.0f; + // Round to 0.1 dB so tiny ramps do not read as "-0.0". + const float rounded = std::round(db * 10.0f) / 10.0f; + juce::String value = std::abs(rounded) < 0.05f ? juce::String("0") + : (rounded > 0.0f ? "+" : "") + juce::String(rounded, 1); + return Loc::format(LOC_RAW("{0} dB"), value); +} + +// With several notes selected an edit changes all of them, so name them all, in time order: +// "Notes: 3, A4, B4, C5", or "Notes: 3, 50%" when the value is the same for each. +juce::String PianoRollComponent::describeEditedSelection(const std::vector& notes, int index, + const std::function& valueAt) const +{ + const int count = static_cast(notes.size()); + std::vector selected; + for (int i : interactionState_.noteSelection.selectedIndices) + if (i >= 0 && i < count) + selected.push_back(i); + if (selected.size() < 2) + return index >= 0 && index < count ? valueAt(index) : juce::String(); + + std::sort(selected.begin(), selected.end(), [¬es](int a, int b) { + return notes[static_cast(a)].startTime < notes[static_cast(b)].startTime; + }); + + juce::StringArray values; + for (int i : selected) + values.add(valueAt(i)); + juce::StringArray distinct(values); + distinct.removeDuplicates(false); + + // A long list is not worth hearing: the first few are enough to tell what happened. + constexpr int kMaxSpoken = 5; + if (distinct.size() == 1) + values = distinct; + else if (values.size() > kMaxSpoken) + values.removeRange(kMaxSpoken, values.size() - kMaxSpoken); + + return Loc::format(LOC_RAW("Notes: {0}, {1}"), juce::String(static_cast(selected.size())), + values.joinIntoString(", ")); +} + +void PianoRollComponent::handleKeyboardNote(PianoRollToolHandler::KeyboardNoteEvent event, + const std::vector& notes, int index) +{ + using Event = PianoRollToolHandler::KeyboardNoteEvent; + switch (event) { + case Event::NoNotes: + a11y::announce(*this, LOC_RAW("No notes")); + return; + case Event::NoSelection: + a11y::announce(*this, LOC_RAW("No note selected")); + return; + case Event::Selected: + if (pendingAuditionTimer_ != nullptr) + pendingAuditionTimer_->stopTimer(); + a11y::announce(*this, describeKeyboardNote(notes, index, NoteDetail::Navigation)); + if (index >= 0 && index < static_cast(notes.size())) + auditionNote(notes[static_cast(index)]); + return; + case Event::PitchMoved: + // After a move only the new pitch matters; audio plays once the correction is re-rendered. + a11y::announce(*this, describeEditedSelection(notes, index, [this, ¬es](int i) { + return describeKeyboardNote(notes, i, NoteDetail::Target); + })); + scheduleAuditionAfterRender(index); + return; + case Event::Info: + a11y::announce(*this, describeKeyboardNote(notes, index, NoteDetail::Full)); + return; + case Event::Split: + case Event::SplitInHalf: { + // Name both parts so it is clear whether the cut separated two different notes. + const auto parts = describeKeyboardNote(notes, index, NoteDetail::Target) + ", " + + describeKeyboardNote(notes, index + 1, NoteDetail::Target); + a11y::announce(*this, Loc::format(event == Event::Split ? LOC_RAW("Note split: {0}") + : LOC_RAW("No clear pitch change, split in half: {0}"), + parts)); + return; + } + case Event::NoteTooShort: + a11y::announce(*this, LOC_RAW("Note too short to split")); + return; + case Event::SplitAtCursor: + a11y::announce(*this, Loc::format(LOC_RAW("Note split at the cursor: {0}"), + describeKeyboardNote(notes, index, NoteDetail::Target) + ", " + + describeKeyboardNote(notes, index + 1, NoteDetail::Target))); + return; + case Event::CursorUnknown: + a11y::announce(*this, LOC_RAW("Edit cursor unknown: works in REAPER with playback stopped")); + return; + case Event::CursorOutsideNote: + a11y::announce(*this, LOC_RAW("The edit cursor is not inside the note")); + return; + case Event::Merged: + a11y::announce(*this, LOC_RAW("Notes merged") + ", " + + describeKeyboardNote(notes, index, NoteDetail::Navigation)); + return; + case Event::NoAdjacentNote: + a11y::announce(*this, LOC_RAW("No adjacent next note")); + return; + case Event::ModulationChanged: + case Event::DriftChanged: + if (index >= 0 && index < static_cast(notes.size())) { + // Only the new value, like the drag tooltip: "40%", "+80%". + a11y::announce(*this, describeEditedSelection(notes, index, [this, ¬es, event](int i) { + const auto& note = notes[static_cast(i)]; + return event == Event::ModulationChanged ? modulationPercentText(note) + : driftPercentText(note); + })); + scheduleAuditionAfterRender(index); + } + return; + case Event::AllSelected: + a11y::announce(*this, Loc::format(LOC_RAW("All notes selected: {0}"), + juce::String(static_cast(notes.size())))); + return; + case Event::NoteResized: + if (index >= 0 && index < static_cast(notes.size())) { + const auto& note = notes[static_cast(index)]; + const double start = sourceTimeToTimelineTime(note.startTime); + const double end = sourceTimeToTimelineTime(note.endTime); + a11y::announce(*this, Loc::format(LOC_RAW("start {0} s, length {1} s"), + juce::String(start, 2), juce::String(end - start, 2))); + scheduleAuditionAfterRender(index); + } + return; + case Event::SingleNoteNeeded: + a11y::announce(*this, LOC_RAW("Select a single note")); + return; + case Event::RangeSelected: + // Count first, then the note at the moving end of the range. + if (pendingAuditionTimer_ != nullptr) + pendingAuditionTimer_->stopTimer(); + a11y::announce(*this, Loc::format(LOC_RAW("Notes selected: {0}, {1}"), + juce::String(static_cast(interactionState_.noteSelection.selectedIndices.size())), + describeKeyboardNote(notes, index, NoteDetail::Navigation))); + if (index >= 0 && index < static_cast(notes.size())) + auditionNote(notes[static_cast(index)]); + return; + case Event::PositionInfo: + { + // Shift+I: where the plugin thinks the user is, and where that comes from. + if (processor_ == nullptr || !processor_->getReaperTransport()) { + a11y::announce(*this, LOC_RAW("Position unknown: works in REAPER")); + return; + } + const auto position = currentSongPosition(); + if (!position) { + a11y::announce(*this, LOC_RAW("Playing: the position is known after a pause or stop")); + return; + } + const auto seconds = juce::String(position->seconds, 2); + const char* pattern = position->source == SongPosition::Source::Paused ? "Position {0} s, paused" + : "Position {0} s, edit cursor"; + a11y::announce(*this, Loc::format(LOC_RAW(pattern), seconds)); + return; + } + case Event::ArrowHint: + { + // Says what Ctrl+Up/Down edits with the current tool. + juce::String hint = LOC_RAW("Ctrl+Up/Down changes the pitch"); + if (currentTool_ == ToolId::PitchModulation) + hint = LOC_RAW("Ctrl+Up/Down changes the modulation"); + else if (currentTool_ == ToolId::PitchDrift) + hint = LOC_RAW("Ctrl+Up/Down changes the drift"); + else if (currentTool_ == ToolId::VolumeEnvelope) + hint = LOC_RAW("Ctrl+Up/Down changes the volume"); + a11y::announce(*this, hint); + return; + } + case Event::VolumeChanged: + if (index >= 0 && index < static_cast(notes.size())) { + // Only the new level, like the other value edits. + a11y::announce(*this, describeEditedSelection(notes, index, [this, ¬es](int i) { + return volumeText(notes[static_cast(i)]); + })); + scheduleAuditionAfterRender(index); + } + return; + case Event::Removed: + { + // Then the note that took the place of the removed ones, if any. + juce::String text = Loc::format(LOC_RAW("Notes removed: {0}"), juce::String(index)); + const auto& selected = interactionState_.noteSelection.selectedIndices; + if (selected.size() == 1) { + const auto line = describeKeyboardNote(notes, selected.front(), NoteDetail::Navigation); + if (line.isNotEmpty()) + text << ", " << line; + } + a11y::announce(*this, text); + return; + } + case Event::EditFailed: + // Sighted users see the note stay put and, when the notes changed meanwhile, + // the selection highlight disappear; say both. + a11y::announce(*this, interactionState_.noteSelection.selectedIndices.empty() + ? LOC_RAW("Could not apply, selection cleared") + : LOC_RAW("Could not apply"), + a11y::SpeechQueue::keepAll); + return; + } +} + +void PianoRollComponent::auditionNote(const Note& note) +{ + if (noteAudition_ == nullptr || audioBuffer_ == nullptr || audioBufferSampleRate_ <= 0.0) + return; + + // Note times are in source audio time, so the buffer index is computed directly. + const double sampleRate = audioBufferSampleRate_; + const int totalSamples = audioBuffer_->getNumSamples(); + const int startSample = juce::jlimit(0, totalSamples, + static_cast(std::llround(note.startTime * sampleRate))); + int numSamples = juce::jlimit(0, totalSamples - startSample, + static_cast(std::llround(note.getDuration() * sampleRate))); + numSamples = juce::jmin(numSamples, static_cast(NoteAudition::kMaxDurationSeconds * sampleRate)); + if (numSamples <= 0) + return; + + // As in export: the original vocal with the rendered correction overlaid where available. + // Rendered audio is stored at the render rate, so overlay only when the rates match. + juce::AudioBuffer segment(audioBuffer_->getNumChannels(), numSamples); + for (int channel = 0; channel < segment.getNumChannels(); ++channel) + segment.copyFrom(channel, 0, *audioBuffer_, channel, startSample, numSamples); + + if (renderCacheProvider_ != nullptr && editedContentKey_.isValid() + && std::abs(sampleRate - TimeCoordinate::kRenderSampleRate) < 1.0) { + if (const auto cache = renderCacheProvider_(editedContentKey_)) + cache->overlayCanonicalAudio(segment, 0, numSamples, startSample); + } + + // Note volume (Volume Envelope tool) is not in the render: playback applies it + // (applyAutomationGain). Apply it here too, or a volume change is not heard. + // Segment samples are source time, so no time grid mapping is needed. + if (const auto snapshot = readEditedSnapshot(); snapshot != nullptr && !snapshot->volumeEnvelope.empty()) { + constexpr float kDbToLinear = 0.11512925465f; // ln(10) / 20 + for (int s = 0; s < numSamples; ++s) { + const double sourceSeconds = static_cast(startSample + s) / sampleRate; + const float gain = std::exp(snapshot->volumeEnvelope.evalAt(sourceSeconds) * kDbToLinear); + for (int channel = 0; channel < segment.getNumChannels(); ++channel) + segment.getWritePointer(channel)[s] *= gain; + } + } + + noteAudition_->play(segment, sampleRate, 0, numSamples); +} + +// Same names as the tool buttons in the parameter panel (ParameterPanel). +juce::String PianoRollComponent::keyboardToolName(ToolId tool) const +{ + switch (tool) { + case ToolId::Select: return LOC(kToolODSelect); + case ToolId::Pitch: return LOC(kToolODPitch); + case ToolId::PitchModulation: return LOC(kToolODPitchModulation); + case ToolId::PitchDrift: return LOC(kToolODPitchDrift); + case ToolId::VolumeEnvelope: return LOC(kToolODVolumeEnvelope); + case ToolId::Scissors: return LOC(kToolODScissors); + case ToolId::HandDraw: return LOC(kTooltipHandDraw); + case ToolId::DrawNote: return LOC(kTooltipDrawNote); + case ToolId::LineAnchor: return LOC(kTooltipLineAnchor); + case ToolId::Eraser: return LOC(kEraser); + case ToolId::TimeTool: return LOC_RAW("Time tool"); + case ToolId::Eq: return "EQ"; + default: return {}; + } +} + +// Same format as the drag tooltip (drawModDriftDragPreview). +juce::String PianoRollComponent::modulationPercentText(const Note& note) const +{ + // A negative value means the note follows the global Retune Speed knob. + const float value = note.retuneSpeed >= 0.0f ? note.retuneSpeed : currentRetuneSpeed_; + return juce::String::formatted("%.0f%%", value * 100.0f); +} + +juce::String PianoRollComponent::driftPercentText(const Note& note) const +{ + return juce::String::formatted("%+.0f%%", note.pitchDriftScale * 100.0f); +} + +namespace { +// Lambda-driven timer: PianoRollComponent does not inherit from Timer itself. +class CallbackTimer final : public juce::Timer { +public: + explicit CallbackTimer(std::function callback) : callback_(std::move(callback)) {} + void timerCallback() override { callback_(); } + +private: + std::function callback_; +}; +} // namespace + +void PianoRollComponent::scheduleAuditionAfterRender(int noteIndex) +{ + // The user can turn this off in Preferences > Editing. + if (appPreferences_ != nullptr && !appPreferences_->getNoteTransposePreviewEnabled()) + return; + pendingAuditionNoteIndex_ = noteIndex; + pendingAuditionTicks_ = 0; + if (pendingAuditionTimer_ == nullptr) + pendingAuditionTimer_ = std::make_unique([this] { tickPendingAudition(); }); + // Each new move restarts the wait, so rapid key presses play only the final result. + pendingAuditionTimer_->startTimer(150); +} + +void PianoRollComponent::tickPendingAudition() +{ + ++pendingAuditionTicks_; + + bool settled = true; + if (renderCacheProvider_ != nullptr && editedContentKey_.isValid()) { + if (const auto cache = renderCacheProvider_(editedContentKey_)) + settled = cache->isCanonicalSettled(); + } + + // Always wait the first 2 ticks: the render may not have been queued yet. + // Do not wait longer than ~5 seconds; play whatever is there. + constexpr int kMinTicks = 2; + constexpr int kMaxTicks = 35; + if (pendingAuditionTicks_ < kMinTicks || (!settled && pendingAuditionTicks_ < kMaxTicks)) + return; + + pendingAuditionTimer_->stopTimer(); + // After the wait the render may still be running: the note then plays the old sound, + // so say so instead of letting it pass for the result. + if (!settled) + a11y::announce(*this, LOC_RAW("Not rendered yet")); + const auto& notes = getCommittedNotes(); + if (pendingAuditionNoteIndex_ >= 0 && pendingAuditionNoteIndex_ < static_cast(notes.size())) + auditionNote(notes[static_cast(pendingAuditionNoteIndex_)]); +} + } // namespace OpenTune diff --git a/Source/Standalone/UI/PianoRollComponent.h b/Source/Standalone/UI/PianoRollComponent.h index dde69f7a..43aa5b77 100644 --- a/Source/Standalone/UI/PianoRollComponent.h +++ b/Source/Standalone/UI/PianoRollComponent.h @@ -30,6 +30,7 @@ #include "Utils/NoteGeneratorTypes.h" #include "Utils/PitchControlConfig.h" #include "Utils/KeyShortcutConfig.h" +#include "Utils/ContextMenuKey.h" #include "Utils/ZoomSensitivityConfig.h" #include #include @@ -56,6 +57,8 @@ namespace OpenTune { class PianoKeyAudition; +class NoteAudition; +class RenderCache; class AppPreferences; class OpenTuneAudioProcessor; struct PlayHeadState; @@ -172,6 +175,13 @@ class PianoRollComponent : public juce::Component, void onNotesRevisionChanged(); void onPitchRevisionChanged(); void setPianoKeyAudition(PianoKeyAudition* audition) { pianoKeyAudition_ = audition; } + void setNoteAudition(NoteAudition* audition) { noteAudition_ = audition; } + /** Access to a content's rendered (corrected) audio, for keyboard note audition. */ + using RenderCacheProvider = std::function(ContentKey)>; + void setRenderCacheProvider(RenderCacheProvider provider) { renderCacheProvider_ = std::move(provider); } + /** The plugin has no use for Esc in the piano roll: let the host have it. */ + void setEscapePassesToHost(bool passes) noexcept { escapePassesToHost_ = passes; } + std::unique_ptr createAccessibilityHandler() override; /** 注入 AppPreferences 指针(两个 Editor 构造/同步时直接注入,无中转层)。 * 用于 EQ popup 和音符整体移动吸附偏好。 */ @@ -250,6 +260,19 @@ class PianoRollComponent : public juce::Component, bool getSingleSelectedNoteParameters(float& retuneSpeedPercent, float& vibratoDepth, float& vibratoRate) const; AudioEditingScheme::ParameterEditResult editParameter(AudioEditingScheme::ParameterId id, float value); + // Accessibility: where the user is in the song while REAPER is paused or stopped + // (project seconds), and the same in the clip's source seconds. Empty while playing + // or in other hosts. See trackReaperTransport. + struct SongPosition { + enum class Source { Paused, EditCursor }; + double seconds = 0.0; + Source source = Source::EditCursor; + }; + std::optional currentSongPosition() const; + std::optional stoppedEditCursorSourceTime() const; + // Accessibility: what a parameter knob change did, for speech ("Applied to notes: 3"). + juce::String describeParameterEdit(AudioEditingScheme::ParameterId id, + const AudioEditingScheme::ParameterEditResult& result) const; void setCreationDefault(AudioEditingScheme::ParameterId id, float value); NoteGeneratorParams getCurrentAutoTuneParams() const noexcept @@ -331,7 +354,7 @@ class PianoRollComponent : public juce::Component, /** 为当前选中组打开 EQ 预览弹窗:只读选中组与主音符,主音符 eq 有值显示它, * 无值显示 EqSettings 默认;打开零 draft、零提交。主音符 index 由 * ToolHandler 唯一判定并经 toolCtx.openEqPreview 直通。 */ - void openEqPopupForSelection(int primaryIndex); + void openEqPopupForSelection(int primaryIndex, bool fromKeyboard = false); void scrollBarMoved(juce::ScrollBar* scrollBar, double newRangeStart) override; void updateScrollBars(); @@ -449,6 +472,7 @@ class PianoRollComponent : public juce::Component, void mouseMagnify(const juce::MouseEvent& e, float scaleFactor) override; public: bool keyPressed(const juce::KeyPress& key) override; + bool keyStateChanged(bool isKeyDown) override; /// Re-read notes from the content store, update the cache, and return the snapshot used. std::shared_ptr refreshEditedContentNotes(); @@ -591,6 +615,8 @@ class PianoRollComponent : public juce::Component, // OpenDyne 右键工具选择弹出条 std::unique_ptr toolSelectionBar_; void showToolSelectionBar(juce::Point screenPos); + void showToolMenuFromKeyboard(); + a11y::ApplicationsKeyWatcher applicationsKey_; void dismissToolPopup(); InteractionState interactionState_; @@ -692,6 +718,10 @@ class PianoRollComponent : public juce::Component, ReadContentSnapshotFn readContentSnapshot_; std::shared_ptr contentCommands_; OpenTuneAudioProcessor* processor_ = nullptr; + // Accessibility: REAPER transport as last seen (trackReaperTransport) and the last halt. + void trackReaperTransport(); + int lastReaperPlayState_ = 0; + std::optional haltEditCursor_; // edit cursor when playback paused or stopped std::shared_ptr readSnapshotFor(ContentKey key) const { return readContentSnapshot_ ? readContentSnapshot_(key) : nullptr; @@ -740,6 +770,26 @@ class PianoRollComponent : public juce::Component, static constexpr int dragThreshold_ = 5; PianoKeyAudition* pianoKeyAudition_ = nullptr; + NoteAudition* noteAudition_ = nullptr; + + // Accessibility: speech for the keyboard-selected note and audition of its vocal. + void handleKeyboardNote(PianoRollToolHandler::KeyboardNoteEvent event, const std::vector& notes, int index); + enum class NoteDetail { Navigation, Target, Full }; + juce::String describeKeyboardNote(const std::vector& notes, int index, NoteDetail detail) const; + void auditionNote(const Note& note); + juce::String keyboardToolName(ToolId tool) const; + juce::String modulationPercentText(const Note& note) const; + juce::String driftPercentText(const Note& note) const; + juce::String volumeText(const Note& note) const; + juce::String describeEditedSelection(const std::vector& notes, int index, + const std::function& valueAt) const; + void scheduleAuditionAfterRender(int noteIndex); + bool escapePassesToHost_ = false; + void tickPendingAudition(); + RenderCacheProvider renderCacheProvider_; + std::unique_ptr pendingAuditionTimer_; + int pendingAuditionNoteIndex_ = -1; + int pendingAuditionTicks_ = 0; int pressedPianoKey_ = -1; std::unique_ptr scrollVBlankAttachment_; diff --git a/Source/Standalone/UI/TimelineOverviewComponent.cpp b/Source/Standalone/UI/TimelineOverviewComponent.cpp index 4259c8f1..8356a39a 100644 --- a/Source/Standalone/UI/TimelineOverviewComponent.cpp +++ b/Source/Standalone/UI/TimelineOverviewComponent.cpp @@ -142,6 +142,9 @@ TimelineOverviewComponent::TimelineOverviewComponent( : waveformMipmapCache_(waveformMipmapCache) { setMouseCursor(juce::MouseCursor::PointingHandCursor); + // Accessibility: a picture of the whole clip for mouse navigation only; NVDA read it + // as "unknown". The notes list gives the same information as text. + setAccessible(false); } void TimelineOverviewComponent::addListener(Listener* listener) diff --git a/Source/Standalone/UI/TopBarComponent.cpp b/Source/Standalone/UI/TopBarComponent.cpp index 234495c1..b58874ce 100644 --- a/Source/Standalone/UI/TopBarComponent.cpp +++ b/Source/Standalone/UI/TopBarComponent.cpp @@ -56,6 +56,14 @@ void TopBarComponent::setSidePanelsVisible(bool trackPanelVisible, bool paramete repaint(); } +void TopBarComponent::setSidePanelTogglesAccessible(bool accessible) +{ + for (auto* button : { &trackPanelToggleButton_, ¶meterPanelToggleButton_ }) { + button->setWantsKeyboardFocus(accessible); + button->setAccessible(accessible); + } +} + void TopBarComponent::setTrackPanelToggleVisible(bool visible) { trackPanelToggleVisible_ = visible; diff --git a/Source/Standalone/UI/TopBarComponent.h b/Source/Standalone/UI/TopBarComponent.h index 623b59bd..db871ce2 100644 --- a/Source/Standalone/UI/TopBarComponent.h +++ b/Source/Standalone/UI/TopBarComponent.h @@ -27,6 +27,9 @@ class TopBarComponent : public juce::Component // 同步按钮状态(避免 ToggleState 与真实可见性不一致) void setSidePanelsVisible(bool trackPanelVisible, bool parameterPanelVisible); void setTrackPanelToggleVisible(bool visible); + // Accessibility: false takes both toggles out of the Tab order and the screen reader tree + // (for an editor where they have no effect); they stay visible. + void setSidePanelTogglesAccessible(bool accessible); juce::Component& getParameterPanelButton() { return parameterPanelToggleButton_; } void refreshLocalizedText(); // 刷新本地化文本 diff --git a/Source/Standalone/UI/TransportBarComponent.cpp b/Source/Standalone/UI/TransportBarComponent.cpp index 458fc586..01f8db12 100644 --- a/Source/Standalone/UI/TransportBarComponent.cpp +++ b/Source/Standalone/UI/TransportBarComponent.cpp @@ -135,6 +135,50 @@ DigitalTimeDisplay::DigitalTimeDisplay() setInterceptsMouseClicks(false, false); } +std::unique_ptr DigitalTimeDisplay::createAccessibilityHandler() +{ + // The title is computed on request, so it is current whenever NVDA reads it. + class TimeAccessibilityHandler final : public juce::AccessibilityHandler { + public: + explicit TimeAccessibilityHandler(DigitalTimeDisplay& owner) + : juce::AccessibilityHandler(owner, juce::AccessibilityRole::staticText), owner_(owner) {} + + juce::String getTitle() const override + { + if (owner_.isBarsMode_) + return OpenTune::Loc::format(LOC_RAW("Bar {0}, beat {1}"), juce::String(owner_.bar_), + juce::String(owner_.beat_)); + return OpenTune::Loc::format(LOC_RAW("Time {0}"), owner_.timeString_); + } + + private: + DigitalTimeDisplay& owner_; + }; + + return std::make_unique(*this); +} + +std::unique_ptr BpmValueField::createAccessibilityHandler() +{ + // In the plugin (ARA) the host owns the tempo and the field is read-only text. + class TempoAccessibilityHandler final : public juce::AccessibilityHandler { + public: + explicit TempoAccessibilityHandler(BpmValueField& owner) + : juce::AccessibilityHandler(owner, juce::AccessibilityRole::staticText), owner_(owner) {} + + juce::String getTitle() const override + { + return OpenTune::Loc::format(LOC_RAW("Tempo {0} BPM, {1}"), owner_.formatBpmText(), + juce::String(owner_.timeSigNum_) + "/" + juce::String(owner_.timeSigDenom_)); + } + + private: + BpmValueField& owner_; + }; + + return std::make_unique(*this); +} + void DigitalTimeDisplay::setTimeString(const juce::String& time) { if (timeString_ != time || isBarsMode_) @@ -800,7 +844,10 @@ void BpmValueField::cancelEdit() UnifiedToolbarButton::UnifiedToolbarButton(const juce::String& name, juce::Path iconPath, juce::Path toggledIconPath) : juce::Button(name), iconPath_(iconPath), toggledIconPath_(toggledIconPath) { - setWantsKeyboardFocus(false); + // Accessibility: toolbar buttons (File, Edit, View, Record, ...) must be reachable with Tab. + // A mouse click still does not take focus, so keys keep going to the piano roll. + setWantsKeyboardFocus(true); + setMouseClickGrabsKeyboardFocus(false); } void UnifiedToolbarButton::setIcon(juce::Path iconPath) @@ -1300,15 +1347,18 @@ TransportBarComponent::TransportBarComponent() scaleTypeSelector_.setJustificationType(juce::Justification::centred); addAndMakeVisible(scaleTypeSelector_); + // Accessibility: without a title NVDA read only the value ("combo box C"). + scaleRootSelector_.setTitle(LOC(kRootNote)); + scaleTypeSelector_.setTitle(LOC(kScale)); + externalEditButton_.setButtonText(LOC(kExternalEdit)); - externalEditButton_.setTooltip(LOC(kExternalEdit)); + // Accessibility: no tooltip equal to the button text; NVDA read it twice (name + help). externalEditButton_.onClick = [this] { listeners_.call([](Listener& listener) { listener.externalEditRequested(); }); }; addAndMakeVisible(externalEditButton_); saveAndReturnButton_.setButtonText(LOC(kSaveAndReturn)); - saveAndReturnButton_.setTooltip(LOC(kSaveAndReturn)); saveAndReturnButton_.onClick = [this] { listeners_.call([](Listener& listener) { listener.saveAndReturnRequested(); }); }; @@ -1323,6 +1373,9 @@ TransportBarComponent::~TransportBarComponent() void TransportBarComponent::refreshLocalizedText() { + scaleRootSelector_.setTitle(LOC(kRootNote)); + scaleTypeSelector_.setTitle(LOC(kScale)); + // 刷新所有按钮的 tooltip fileButton_.setTooltip(LOC(kTooltipFile)); editButton_.setTooltip(LOC(kTooltipEdit)); diff --git a/Source/Standalone/UI/TransportBarComponent.h b/Source/Standalone/UI/TransportBarComponent.h index 7d8167b6..57d36a26 100644 --- a/Source/Standalone/UI/TransportBarComponent.h +++ b/Source/Standalone/UI/TransportBarComponent.h @@ -17,6 +17,7 @@ #include #include "UIColors.h" #include "../../Utils/TimelineDisplayMode.h" +#include "../../Utils/AccessibleComboBox.h" namespace OpenTune { @@ -64,6 +65,8 @@ class DigitalTimeDisplay : public juce::Component, juce::String getTooltip() override { return tooltip_; } void setTooltip(const juce::String& t) { tooltip_ = t; } + // Accessibility: read as text ("Time 00:12.345") instead of an unnamed object. + std::unique_ptr createAccessibilityHandler() override; private: void drawChar(juce::Graphics& g, juce::juce_wchar c, juce::Rectangle area); @@ -96,6 +99,8 @@ class BpmValueField : public juce::Component, std::function onCommit; std::function onTimeSignatureCommit; // num, denom + // Accessibility: read as text ("Tempo 120 BPM, 4/4") instead of an unnamed object. + std::unique_ptr createAccessibilityHandler() override; private: void timerCallback() override; @@ -300,8 +305,8 @@ class TransportBarComponent : public juce::Component UnifiedToolbarButton tapButton_; // Scale controls - juce::ComboBox scaleRootSelector_; - juce::ComboBox scaleTypeSelector_; + a11y::AccessibleComboBox scaleRootSelector_; + a11y::AccessibleComboBox scaleTypeSelector_; juce::TextButton externalEditButton_; juce::TextButton saveAndReturnButton_; diff --git a/Source/Utils/AccessibleComboBox.h b/Source/Utils/AccessibleComboBox.h new file mode 100644 index 00000000..5f30867c --- /dev/null +++ b/Source/Utils/AccessibleComboBox.h @@ -0,0 +1,43 @@ +#pragma once + +#include + +namespace OpenTune::a11y { + +// ComboBox with Home/End (first/last item), which the stock JUCE ComboBox ignores. +// NVDA speaks the new item itself (JUCE raises a UIA value change); an extra +// announcement here was heard twice. Pitch snap once seemed silent only because +// it was scrolled out of the panel (NVDA: offscreen), see ParameterPanel. +class AccessibleComboBox : public juce::ComboBox +{ +public: + using juce::ComboBox::ComboBox; + + bool keyPressed(const juce::KeyPress& key) override + { + bool handled = false; + + if (key == juce::KeyPress::homeKey || key == juce::KeyPress::endKey) + { + // Walk from the edge so disabled items are skipped, like the arrows do. + const bool fromStart = key == juce::KeyPress::homeKey; + for (int i = fromStart ? 0 : getNumItems() - 1; i >= 0 && i < getNumItems(); i += fromStart ? 1 : -1) + { + if (isItemEnabled(getItemId(i))) + { + setSelectedItemIndex(i); + break; + } + } + handled = true; + } + else + { + handled = juce::ComboBox::keyPressed(key); + } + + return handled; + } +}; + +} // namespace OpenTune::a11y diff --git a/Source/Utils/AccessibleKnob.h b/Source/Utils/AccessibleKnob.h new file mode 100644 index 00000000..1bb82200 --- /dev/null +++ b/Source/Utils/AccessibleKnob.h @@ -0,0 +1,209 @@ +#pragma once + +#include +#include +#include +#include + +namespace OpenTune::a11y { + +// Slider or knob for the keyboard, with the same keys everywhere in the plugin: +// arrows step, Alt is a fine step, Page Up/Down a big one, Home = maximum and +// End = minimum (the user's rule), Backspace = default value, Enter = type a number +// (Enter keeps it, Esc drops it, Tab keeps it and goes to the next control). +// The stock JUCE slider moves by its interval (often 0.01) and has no Home/End. +// +// Changes from the arrow keys reach onCommit once the keys stop, so a held arrow is one +// undo step and one render; other changes reach it at once. Use onCommit, not onValueChange. +class AccessibleKnob : public juce::Slider, private juce::Timer +{ +public: + AccessibleKnob() + { + setWantsKeyboardFocus(true); + // The value box is an editable Label: as a Tab stop it opened a text field + // ("Retune Speed edit selected 15.00%"). A focus container keeps its children + // out of the Tab order; Enter opens the field and the mouse can still click it. + setFocusContainerType(FocusContainerType::keyboardFocusContainer); + } + + ~AccessibleKnob() override { stopTimer(); } + + void setKeySteps(double normal, double fine, double big) + { + step_ = normal; + fineStep_ = fine; + bigStep_ = big; + } + + // Backspace value when the slider has no double-click return value. + void setResetValue(double value) { resetValue_ = value; } + + std::function onCommit; + + bool keyPressed(const juce::KeyPress& key) override + { + const int code = key.getKeyCode(); + const auto mods = key.getModifiers(); + + if (auto* box = valueBox(); box != nullptr && box->isBeingEdited()) + { + // The field takes the other keys itself; these bubble up from it. + if (code == juce::KeyPress::tabKey) + { + tabAfterEditor_ = mods.isShiftDown() ? -1 : 1; + box->hideEditor(false); + } + else if (code == juce::KeyPress::escapeKey) + { + box->hideEditor(true); + } + return true; + } + + // The key that closed the field bubbles up here as well; it is done already. + if (editorJustClosed_) + return true; + + if (mods.isCtrlDown() || mods.isCommandDown() || mods.isShiftDown()) + return juce::Slider::keyPressed(key); + + if (code == juce::KeyPress::returnKey && !mods.isAltDown()) + { + openValueEditor(); + return true; + } + + const double small = mods.isAltDown() ? fineStep_ : step_; + double target = getValue(); + if (code == juce::KeyPress::upKey || code == juce::KeyPress::rightKey) + target += small; + else if (code == juce::KeyPress::downKey || code == juce::KeyPress::leftKey) + target -= small; + else if (code == juce::KeyPress::pageUpKey) + target += bigStep_; + else if (code == juce::KeyPress::pageDownKey) + target -= bigStep_; + else if (code == juce::KeyPress::homeKey) + target = getMaximum(); + else if (code == juce::KeyPress::endKey) + target = getMinimum(); + else if (code == juce::KeyPress::backspaceKey && !mods.isAltDown()) + return resetToDefault(); + else + return juce::Slider::keyPressed(key); + + target = juce::jlimit(getMinimum(), getMaximum(), target); + // At the edge the value does not change and NVDA says nothing. + if (target != getValue()) + { + keyboardChange_ = true; + // NVDA speaks the new value of the focused slider itself (JUCE value change event). + setValue(target, juce::sendNotificationSync); + keyboardChange_ = false; + } + return true; + } + + void focusLost(FocusChangeType cause) override + { + commitPending(); + juce::Slider::focusLost(cause); + } + +private: + juce::Label* valueBox() const + { + for (auto* child : getChildren()) + if (auto* label = dynamic_cast(child)) + return label; + return nullptr; + } + + void openValueEditor() + { + auto* box = valueBox(); + if (box == nullptr || !isTextBoxEditable()) + return; + + commitPending(); + juce::Component::SafePointer safeThis(this); + // Set every time: the Label is recreated when the look and feel changes. + box->onEditorHide = [safeThis] { + if (safeThis == nullptr) + return; + safeThis->editorJustClosed_ = true; + // Focus moves a tick later: moving it while the field is being removed + // crashed REAPER in another plugin (skill pitfall 7). + juce::MessageManager::callAsync([safeThis] { + if (safeThis == nullptr) + return; + safeThis->editorJustClosed_ = false; + const int tab = std::exchange(safeThis->tabAfterEditor_, 0); + if (!safeThis->isShowing()) + return; + // Not when a click already took focus somewhere else. + auto* focused = juce::Component::getCurrentlyFocusedComponent(); + if (focused != nullptr && focused != safeThis.getComponent() && !safeThis->isParentOf(focused)) + return; + if (tab != 0) + safeThis->moveKeyboardFocusToSibling(tab > 0); + else if (!safeThis->hasKeyboardFocus(false)) + safeThis->grabKeyboardFocus(); + }); + }; + showTextBox(); + // Only a number can be typed; the unit is added back by the slider. + if (auto* editor = box->getCurrentTextEditor()) + editor->setInputRestrictions(0, "-0123456789."); + } + + bool resetToDefault() + { + std::optional target = resetValue_; + if (!target.has_value() && isDoubleClickReturnEnabled()) + target = getDoubleClickReturnValue(); + if (!target.has_value()) + return false; + + const double value = juce::jlimit(getMinimum(), getMaximum(), *target); + if (value != getValue()) + setValue(value, juce::sendNotificationSync); + return true; + } + + void valueChanged() override + { + if (keyboardChange_) + { + startTimer(400); + return; + } + stopTimer(); + if (onCommit) + onCommit(); + } + + void timerCallback() override + { + stopTimer(); + if (onCommit) + onCommit(); + } + + void commitPending() + { + if (isTimerRunning()) + timerCallback(); + } + + double step_ = 1.0; + double fineStep_ = 0.1; + double bigStep_ = 10.0; + std::optional resetValue_; + bool keyboardChange_ = false; + bool editorJustClosed_ = false; + int tabAfterEditor_ = 0; // after Tab in the field: +1 next control, -1 previous +}; + +} // namespace OpenTune::a11y diff --git a/Source/Utils/AccessibleToggleButton.h b/Source/Utils/AccessibleToggleButton.h new file mode 100644 index 00000000..494ecbdf --- /dev/null +++ b/Source/Utils/AccessibleToggleButton.h @@ -0,0 +1,62 @@ +#pragma once + +#include +#include "ScreenReaderAnnouncer.h" + +namespace OpenTune::a11y { + +// Check box for screen readers. The stock JUCE ToggleButton has two problems (user test): +// its "On"/"Off" value is read-only, so NVDA says "read only" on every check box, and a +// key press raises no toggle event, so NVDA stays silent after Space. This handler has no +// value, the state comes from the toggle pattern, and a click reports the new state. +class AccessibleToggleButton : public juce::ToggleButton +{ +public: + using juce::ToggleButton::ToggleButton; + + std::unique_ptr createAccessibilityHandler() override + { + class Handler final : public juce::AccessibilityHandler + { + public: + explicit Handler(AccessibleToggleButton& owner) + : juce::AccessibilityHandler( + owner, juce::AccessibilityRole::toggleButton, + juce::AccessibilityActions() + .addAction(juce::AccessibilityActionType::press, [&owner] { owner.triggerClick(); }) + .addAction(juce::AccessibilityActionType::toggle, + [&owner] { owner.setToggleState(!owner.getToggleState(), juce::sendNotification); })), + owner_(owner) + { + } + + juce::AccessibleState getCurrentState() const override + { + auto state = juce::AccessibilityHandler::getCurrentState().withCheckable(); + return owner_.getToggleState() ? state.withChecked() : state; + } + + juce::String getTitle() const override + { + const auto title = juce::AccessibilityHandler::getTitle(); + return title.isNotEmpty() ? title : owner_.getButtonText(); + } + + juce::String getHelp() const override { return owner_.getTooltip(); } + + private: + AccessibleToggleButton& owner_; + }; + + return std::make_unique(*this); + } + +protected: + void clicked() override + { + juce::ToggleButton::clicked(); + notifyToggleChanged(*this, getToggleState()); + } +}; + +} // namespace OpenTune::a11y diff --git a/Source/Utils/AppPreferences.cpp b/Source/Utils/AppPreferences.cpp index 34b640de..0caa0a14 100644 --- a/Source/Utils/AppPreferences.cpp +++ b/Source/Utils/AppPreferences.cpp @@ -45,7 +45,10 @@ constexpr const char* kPluginEditorSizeKey = "defaultSize"; constexpr const char* kShortcutSchemaVersionKey = "shared.shortcuts.schemaVersion"; constexpr int kShortcutMouseSchemaVersion = 1; constexpr int kShortcutMacModifierSchemaVersion = 2; -constexpr int kShortcutSchemaVersion = 3; +constexpr int kShortcutMacSpacePlaySchemaVersion = 3; +// 4: Pitch Modulation / Pitch Drift got default keys F3 / F5 (Windows). +constexpr int kShortcutModDriftKeysSchemaVersion = 4; +constexpr int kShortcutSchemaVersion = 4; juce::File resolveSettingsDirectory(const AppPreferences::StorageOptions& storageOptions) { @@ -268,8 +271,11 @@ KeyShortcutConfig::KeyShortcutSettings decodeShortcutSettings(const juce::Proper const bool migrateMouseDefaults = storedSchemaVersion < kShortcutMouseSchemaVersion; #if JUCE_MAC || JUCE_IOS const bool migrateMacDefaultShortcuts = storedSchemaVersion < kShortcutMacModifierSchemaVersion; - const bool restoreMacSpacePlay = storedSchemaVersion < kShortcutSchemaVersion; + const bool restoreMacSpacePlay = storedSchemaVersion < kShortcutMacSpacePlaySchemaVersion; #endif + // Modulation and drift used to have no keys, so settings stored an empty string. + // Do not treat it as a user choice; adopt the new F3 / F5. + const bool adoptNewToolDefaults = storedSchemaVersion < kShortcutModDriftKeysSchemaVersion; for (const auto& info : KeyShortcutConfig::kShortcutInfos) { if (!properties.containsKey(info.storageKey)) @@ -277,7 +283,11 @@ KeyShortcutConfig::KeyShortcutSettings decodeShortcutSettings(const juce::Proper const auto stored = properties.getValue(info.storageKey, {}); if (stored.isEmpty()) { - settings.bindings[static_cast(info.id)].bindings.clear(); + const bool keepNewDefault = adoptNewToolDefaults + && (info.id == KeyShortcutConfig::ShortcutId::ToolODPitchModulation + || info.id == KeyShortcutConfig::ShortcutId::ToolODPitchDrift); + if (!keepNewDefault) + settings.bindings[static_cast(info.id)].bindings.clear(); continue; } diff --git a/Source/Utils/ContextMenuKey.cpp b/Source/Utils/ContextMenuKey.cpp new file mode 100644 index 00000000..a00acb21 --- /dev/null +++ b/Source/Utils/ContextMenuKey.cpp @@ -0,0 +1,42 @@ +#include "ContextMenuKey.h" + +#if JUCE_WINDOWS + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include +#endif + +namespace OpenTune::a11y { + +bool isContextMenuKey(const juce::KeyPress& key) +{ + const auto mods = key.getModifiers(); + return key.getKeyCode() == juce::KeyPress::F10Key + && mods.isShiftDown() && !mods.isCtrlDown() && !mods.isAltDown() && !mods.isCommandDown(); +} + +int firstSelectableItemId(const juce::PopupMenu& menu) +{ + for (juce::PopupMenu::MenuItemIterator it(menu); it.next();) { + const auto& item = it.getItem(); + if (item.itemID != 0 && item.isEnabled && !item.isSeparator && !item.isSectionHeader) + return item.itemID; + } + return 0; +} + +bool ApplicationsKeyWatcher::pressedNow() +{ +#if JUCE_WINDOWS + // juce::KeyPress::isKeyCurrentlyDown cannot ask for VK_APPS: 0x5D is translated as ']'. + const bool down = (::GetAsyncKeyState(VK_APPS) & 0x8000) != 0; + const bool pressed = down && !wasDown_; + wasDown_ = down; + return pressed; +#else + return false; +#endif +} + +} // namespace OpenTune::a11y diff --git a/Source/Utils/ContextMenuKey.h b/Source/Utils/ContextMenuKey.h new file mode 100644 index 00000000..ab9d4ff3 --- /dev/null +++ b/Source/Utils/ContextMenuKey.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +namespace OpenTune::a11y { + +// Shift+F10: the standard Windows keyboard replacement for a right-click. +bool isContextMenuKey(const juce::KeyPress& key); + +// ID of the first enabled top-level item that has one (submenus and separators have none), +// or 0. Pass it to PopupMenu::Options::withInitiallySelectedItem: otherwise NVDA reads the +// first item when the menu opens, but JUCE has not highlighted it and the first Enter is lost. +int firstSelectableItemId(const juce::PopupMenu& menu); + +// The Applications (menu) key. JUCE treats it like a modifier key and never calls +// keyPressed for it, so call pressedNow() from keyStateChanged: it returns true once +// per press. Always false outside Windows. +class ApplicationsKeyWatcher +{ +public: + bool pressedNow(); + +private: + bool wasDown_ = false; +}; + +} // namespace OpenTune::a11y diff --git a/Source/Utils/KeyShortcutConfig.h b/Source/Utils/KeyShortcutConfig.h index 51b0c192..23a0898a 100644 --- a/Source/Utils/KeyShortcutConfig.h +++ b/Source/Utils/KeyShortcutConfig.h @@ -443,10 +443,11 @@ inline const ShortcutInfo kShortcutInfos[] = { kPianoRollOpenDyneScope, { KeyBinding(juce::KeyPress::F1Key, {}) } }, { ShortcutId::ToolODPitch, "shared.shortcuts.toolODPitch", Loc::Keys::kToolODPitch, kPianoRollOpenDyneScope, { KeyBinding(juce::KeyPress::F2Key, {}) } }, + // F3/F5: free keys next to F2 and F4/F6, so modulation and drift are reachable without the mouse. { ShortcutId::ToolODPitchModulation, "shared.shortcuts.toolODPitchModulation", Loc::Keys::kToolODPitchModulation, - kPianoRollOpenDyneScope, {} }, + kPianoRollOpenDyneScope, { KeyBinding(juce::KeyPress::F3Key, {}) } }, { ShortcutId::ToolODPitchDrift, "shared.shortcuts.toolODPitchDrift", Loc::Keys::kToolODPitchDrift, - kPianoRollOpenDyneScope, {} }, + kPianoRollOpenDyneScope, { KeyBinding(juce::KeyPress::F5Key, {}) } }, { ShortcutId::ToolODVolumeEnvelope, "shared.shortcuts.toolODVolumeEnvelope", Loc::Keys::kToolODVolumeEnvelope, kPianoRollOpenDyneScope, { KeyBinding(juce::KeyPress::F4Key, {}) } }, { ShortcutId::ToolODScissors, "shared.shortcuts.toolODScissors", Loc::Keys::kToolODScissors, diff --git a/Source/Utils/LocalizationManager.h b/Source/Utils/LocalizationManager.h index b5181d76..115f7100 100644 --- a/Source/Utils/LocalizationManager.h +++ b/Source/Utils/LocalizationManager.h @@ -941,6 +941,92 @@ inline juce::String get(Language lang, const char* key) { Keys::kEraser, "Eraser", "橡皮擦", "消しゴム", "Ластик", "Borrador" }, { "Resize note", "Resize note", "调整音符长度", "ノートの長さを調整", "Изменить длину ноты", "Cambiar duración de nota" }, { "Move note", "Move note", "移动音符", "ノートを移動", "Переместить ноту", "Mover nota" }, + // Piano roll screen reader speech + { "Notes", "Notes", "音符", "ノート", "Ноты", "Notas" }, + { "No notes", "No notes", "没有音符", "ノートがありません", "Нет нот", "No hay notas" }, + { "No note selected", "No note selected", "未选择音符", "ノートが選択されていません", "Нота не выбрана", "No hay ninguna nota seleccionada" }, + { "Note split: {0}", "Note split: {0}", "音符已分割:{0}", "ノートを分割しました:{0}", "Нота разрезана: {0}", "Nota dividida: {0}" }, + { "Notes merged", "Notes merged", "音符已合并", "ノートを結合しました", "Ноты склеены", "Notas unidas" }, + { "No clear pitch change, split in half: {0}", "No clear pitch change, split in half: {0}", "没有明显的音高变化,已从中间分割:{0}", "明確なピッチ変化がないため半分に分割しました:{0}", "Явного скачка высоты нет, нота разрезана пополам: {0}", "Sin cambio claro de tono, dividida por la mitad: {0}" }, + { "Note too short to split", "Note too short to split", "音符太短,无法分割", "ノートが短すぎて分割できません", "Нота слишком короткая для разреза", "La nota es demasiado corta para dividirla" }, + { "Audio read, notes: {0}", "Audio read, notes: {0}", "音频已读取,音符:{0}", "オーディオを読み込みました。ノート:{0}", "Аудио прочитано, нот: {0}", "Audio leído, notas: {0}" }, + { "Audio analysis failed", "Audio analysis failed", "音频分析失败", "オーディオ解析に失敗しました", "Не удалось проанализировать аудио", "Falló el análisis del audio" }, + { "Audio already read", "Audio already read", "音频已读取过", "オーディオは読み込み済みです", "Это аудио уже прочитано", "El audio ya se leyó" }, + { "modulation {0}", "modulation {0}", "调制 {0}", "変調 {0}", "модуляция {0}", "modulación {0}" }, + { "drift {0}", "drift {0}", "漂移 {0}", "ドリフト {0}", "дрейф {0}", "deriva {0}" }, + { "Undone: {0}", "Undone: {0}", "已撤销:{0}", "元に戻しました:{0}", "Отменено: {0}", "Deshecho: {0}" }, + { "Redone: {0}", "Redone: {0}", "已重做:{0}", "やり直しました:{0}", "Повторено: {0}", "Rehecho: {0}" }, + { "Nothing to undo", "Nothing to undo", "没有可撤销的操作", "元に戻す操作はありません", "Нечего отменять", "Nada que deshacer" }, + { "Nothing to redo", "Nothing to redo", "没有可重做的操作", "やり直す操作はありません", "Нечего повторять", "Nada que rehacer" }, + { "AUTO correction applied", "AUTO correction applied", "已应用自动调音", "AUTO補正を適用しました", "Автокоррекция применена", "Corrección automática aplicada" }, + { "Already corrected", "Already corrected", "已经修正过", "すでに補正済みです", "Уже исправлено", "Ya está corregido" }, + { "Notes copied: {0}", "Notes copied: {0}", "已复制音符:{0}", "コピーしたノート:{0}", "Скопировано нот: {0}", "Notas copiadas: {0}" }, + { "Nothing to paste", "Nothing to paste", "没有可粘贴的内容", "貼り付けるものがありません", "Нечего вставлять", "Nada que pegar" }, + { "Notes pasted: {0}, start {1} s", "Notes pasted: {0}, start {1} s", "已粘贴音符:{0},开始 {1} 秒", "貼り付けたノート:{0}、開始 {1} 秒", "Вставлено нот: {0}, начало {1} с", "Notas pegadas: {0}, inicio {1} s" }, + { "Notes selected: {0}, {1}", "Notes selected: {0}, {1}", "已选择音符:{0},{1}", "選択したノート:{0}、{1}", "Выбрано нот: {0}, {1}", "Notas seleccionadas: {0}, {1}" }, + { "Select a single note", "Select a single note", "请只选择一个音符", "ノートを1つだけ選択してください", "Выберите одну ноту", "Seleccione una sola nota" }, + { "volume {0}", "volume {0}", "音量 {0}", "音量 {0}", "громкость {0}", "volumen {0}" }, + { "{0} dB", "{0} dB", "{0} dB", "{0} dB", "{0} дБ", "{0} dB" }, + { "Notes removed: {0}", "Notes removed: {0}", "已删除音符:{0}", "削除したノート:{0}", "Удалено нот: {0}", "Notas eliminadas: {0}" }, + { "Notes: {0}, {1}", "Notes: {0}, {1}", "音符:{0},{1}", "ノート:{0}、{1}", "Нот: {0}, {1}", "Notas: {0}, {1}" }, + { "Rendering done", "Rendering done", "渲染完成", "レンダリング完了", "Рендеринг завершён", "Renderizado terminado" }, + { "EQ closed", "EQ closed", "EQ 已关闭", "EQを閉じました", "Эквалайзер закрыт", "EQ cerrado" }, + { "{0} selected", "{0} selected", "已选择 {0} 个", "{0} 個選択", "выделено: {0}", "{0} seleccionadas" }, + { "Not rendered yet", "Not rendered yet", "尚未渲染完成", "まだレンダリングされていません", "Ещё не пересчитано", "Aún no renderizado" }, + { "Time {0}", "Time {0}", "时间 {0}", "時間 {0}", "Время {0}", "Tiempo {0}" }, + { "Bar {0}, beat {1}", "Bar {0}, beat {1}", "第 {0} 小节,第 {1} 拍", "{0} 小節、{1} 拍", "Такт {0}, доля {1}", "Compás {0}, tiempo {1}" }, + { "Tempo {0} BPM, {1}", "Tempo {0} BPM, {1}", "速度 {0} BPM,{1}", "テンポ {0} BPM、{1}", "Темп {0} BPM, {1}", "Tempo {0} BPM, {1}" }, + { "Bands: {0}", "Bands: {0}", "频段:{0}", "バンド:{0}", "Полос: {0}", "Bandas: {0}" }, + { "EQ bypassed", "EQ bypassed", "EQ 已旁通", "EQ バイパス中", "Эквалайзер в обходе", "EQ en bypass" }, + { "Enter opens it", "Enter opens it", "按 Enter 打开", "Enter で開きます", "Enter открывает", "Enter lo abre" }, + { "Applied to notes: {0}", "Applied to notes: {0}", "已应用到音符:{0}", "ノートに適用:{0}", "Применено к нотам: {0}", "Aplicado a notas: {0}" }, + { "Applied to the selection", "Applied to the selection", "已应用到选区", "選択範囲に適用しました", "Применено к выделению", "Aplicado a la selección" }, + { "Default for new notes", "Default for new notes", "新音符的默认值", "新しいノートの既定値", "По умолчанию для новых нот", "Predeterminado para notas nuevas" }, + { "No pitch data, read the audio first", "No pitch data, read the audio first", "没有音高数据,请先读取音频", "ピッチデータがありません。先にオーディオを読み込んでください", "Нет данных о высоте, сначала прочитайте аудио", "Sin datos de tono, lea primero el audio" }, + { "Notes now: {0}", "Notes now: {0}", "现在音符数:{0}", "現在のノート数:{0}", "Теперь нот: {0}", "Notas ahora: {0}" }, + { "Could not apply", "Could not apply", "无法应用", "適用できませんでした", "Не удалось применить", "No se pudo aplicar" }, + { "Could not apply, selection cleared", "Could not apply, selection cleared", "无法应用,已取消选择", "適用できませんでした。選択を解除しました", "Не удалось применить, выделение снято", "No se pudo aplicar, selección anulada" }, + { "Ctrl+Up/Down changes the pitch", "Ctrl+Up/Down changes the pitch", "Ctrl+上/下 改变音高", "Ctrl+上/下でピッチを変更", "Ctrl+Вверх/Вниз меняет высоту", "Ctrl+Arriba/Abajo cambia el tono" }, + { "Ctrl+Up/Down changes the modulation", "Ctrl+Up/Down changes the modulation", "Ctrl+上/下 改变调制", "Ctrl+上/下で変調を変更", "Ctrl+Вверх/Вниз меняет модуляцию", "Ctrl+Arriba/Abajo cambia la modulación" }, + { "Ctrl+Up/Down changes the drift", "Ctrl+Up/Down changes the drift", "Ctrl+上/下 改变漂移", "Ctrl+上/下でドリフトを変更", "Ctrl+Вверх/Вниз меняет дрейф", "Ctrl+Arriba/Abajo cambia la deriva" }, + { "Ctrl+Up/Down changes the volume", "Ctrl+Up/Down changes the volume", "Ctrl+上/下 改变音量", "Ctrl+上/下で音量を変更", "Ctrl+Вверх/Вниз меняет громкость", "Ctrl+Arriba/Abajo cambia el volumen" }, + { "Note split at the cursor: {0}", "Note split at the cursor: {0}", "已在光标处分割音符:{0}", "カーソル位置でノートを分割しました:{0}", "Нота разрезана по курсору: {0}", "Nota dividida en el cursor: {0}" }, + { "Edit cursor unknown: works in REAPER with playback stopped", "Edit cursor unknown: works in REAPER with playback stopped", "未知编辑光标:仅在 REAPER 停止播放时可用", "編集カーソルが不明です:REAPER で再生停止中のみ使えます", "Курсор неизвестен: работает в REAPER при остановленном воспроизведении", "Cursor de edición desconocido: funciona en REAPER con la reproducción detenida" }, + { "The edit cursor is not inside the note", "The edit cursor is not inside the note", "编辑光标不在音符内", "編集カーソルがノートの内側にありません", "Курсор не внутри ноты", "El cursor de edición no está dentro de la nota" }, + { "Position {0} s, paused", "Position {0} s, paused", "位置 {0} 秒,已暂停", "位置 {0} 秒、一時停止中", "Позиция {0} с, пауза", "Posición {0} s, en pausa" }, + { "Position {0} s, edit cursor", "Position {0} s, edit cursor", "位置 {0} 秒,编辑光标", "位置 {0} 秒、編集カーソル", "Позиция {0} с, курсор", "Posición {0} s, cursor de edición" }, + { "Position unknown: works in REAPER", "Position unknown: works in REAPER", "位置未知:仅在 REAPER 中可用", "位置不明:REAPER でのみ使えます", "Позиция неизвестна: работает в REAPER", "Posición desconocida: funciona en REAPER" }, + { "Playing: the position is known after a pause or stop", "Playing: the position is known after a pause or stop", "正在播放:暂停或停止后才能得知位置", "再生中:一時停止か停止の後に位置がわかります", "Идёт воспроизведение: позиция известна после паузы или остановки", "Reproduciendo: la posición se conoce tras pausar o detener" }, + { "External edit applied", "External edit applied", "外部编辑已应用", "外部編集を適用しました", "Внешняя правка применена", "Edición externa aplicada" }, + { "EQ removed", "EQ removed", "EQ 已移除", "EQを削除しました", "Эквалайзер удалён", "EQ eliminado" }, + { "Band {0} of {1}", "Band {0} of {1}", "频段 {0},共 {1} 个", "バンド {0}/{1}", "Полоса {0} из {1}", "Banda {0} de {1}" }, + { "Band {0} added", "Band {0} added", "已添加频段 {0}", "バンド {0} を追加しました", "Полоса {0} добавлена", "Banda {0} añadida" }, + { "Band {0} removed", "Band {0} removed", "已删除频段 {0}", "バンド {0} を削除しました", "Полоса {0} удалена", "Banda {0} eliminada" }, + { "Maximum {0} bands", "Maximum {0} bands", "最多 {0} 个频段", "バンドは最大 {0} 個です", "Не больше {0} полос", "Máximo {0} bandas" }, + { "Type", "Type", "类型", "タイプ", "Тип", "Tipo" }, + { "Frequency", "Frequency", "频率", "周波数", "Частота", "Frecuencia" }, + { "Gain", "Gain", "增益", "ゲイン", "Усиление", "Ganancia" }, + { "Gain, not used by {0}", "Gain, not used by {0}", "增益,{0} 不使用", "ゲイン、{0} では使用しません", "Усиление, у {0} не используется", "Ganancia, no se usa en {0}" }, + { "Low cut", "Low cut", "低切", "ローカット", "Срез низов", "Corte de graves" }, + { "Low shelf", "Low shelf", "低架", "ローシェルフ", "Полка низов", "Estante de graves" }, + { "Peak", "Peak", "峰值", "ピーク", "Колокол", "Pico" }, + { "High shelf", "High shelf", "高架", "ハイシェルフ", "Полка верхов", "Estante de agudos" }, + { "High cut", "High cut", "高切", "ハイカット", "Срез верхов", "Corte de agudos" }, + { "Bypass band", "Bypass band", "旁通频段", "バンドをバイパス", "Обойти полосу", "Desactivar banda" }, + { "Remove band", "Remove band", "删除频段", "バンドを削除", "Удалить полосу", "Eliminar banda" }, + { "Add band", "Add band", "添加频段", "バンドを追加", "Добавить полосу", "Añadir banda" }, + { "bypassed", "bypassed", "已旁通", "バイパス中", "в обходе", "en bypass" }, + { "On", "On", "开启", "オン", "Вкл", "Encendido" }, + { "Play the note after a keyboard edit", "Play the note after a keyboard edit", "键盘编辑后播放音符", "キーボード編集後にノートを再生", "Проигрывать ноту после правки с клавиатуры", "Reproducir la nota tras editar con el teclado" }, + { "Copied to clipboard", "Copied to clipboard", "已复制到剪贴板", "クリップボードにコピーしました", "Скопировано в буфер обмена", "Copiado al portapapeles" }, + { "Time tool", "Time tool", "时间工具", "タイムツール", "Инструмент времени", "Herramienta de tiempo" }, + { "All notes selected: {0}", "All notes selected: {0}", "已选择全部音符:{0}", "すべてのノートを選択:{0}", "Выделены все ноты: {0}", "Todas las notas seleccionadas: {0}" }, + { "No adjacent next note","No adjacent next note", "没有紧邻的下一个音符", "隣接する次のノートがありません", "Нет следующей ноты вплотную", "No hay una nota siguiente contigua" }, + { "sharp", "sharp", "升", "シャープ", "диез", "sostenido" }, + { "target {0}", "target {0}", "目标 {0}", "ターゲット {0}", "цель {0}", "objetivo {0}" }, + { "sung {0}", "sung {0}", "演唱 {0}", "歌唱 {0}", "спето {0}", "cantado {0}" }, + { "Note {0} of {1}", "Note {0} of {1}", "第 {0} 个音符,共 {1} 个", "ノート {0}/{1}", "Нота {0} из {1}", "Nota {0} de {1}" }, + { "start {0} s, length {1} s", "start {0} s, length {1} s", "开始 {0} 秒,长度 {1} 秒", "開始 {0} 秒、長さ {1} 秒", "начало {0} с, длина {1} с", "inicio {0} s, duración {1} s" }, { "Pitch snap", "Pitch snap", "音高吸附", "ピッチをスナップ", "Привязка высоты тона", "Ajuste magnético del tono" }, { "Modulation depth", "Modulation depth", "调制深度", "モジュレーションの深さ", "Глубина модуляции", "Profundidad de modulación" }, { "Drift correction", "Drift correction", "漂移修正", "ドリフト補正", "Коррекция дрейфа", "Corrección de deriva" }, diff --git a/Source/Utils/NoteAudition.cpp b/Source/Utils/NoteAudition.cpp new file mode 100644 index 00000000..144a262c --- /dev/null +++ b/Source/Utils/NoteAudition.cpp @@ -0,0 +1,113 @@ +#include "NoteAudition.h" + +namespace OpenTune { + +void NoteAudition::play(const juce::AudioBuffer& source, double sourceSampleRate, + int startSample, int numSamples) +{ + const int sourceLength = source.getNumSamples(); + const int sourceChannels = source.getNumChannels(); + if (sourceSampleRate <= 0.0 || sourceChannels <= 0 || sourceLength <= 0) + return; + + startSample = juce::jlimit(0, sourceLength, startSample); + numSamples = juce::jlimit(0, sourceLength - startSample, numSamples); + numSamples = juce::jmin(numSamples, static_cast(kMaxDurationSeconds * sourceSampleRate)); + if (numSamples <= 0) + return; + + // Prepare the clip up front: mono with 5 ms fades to avoid clicks. + auto clip = std::make_unique(); + clip->sampleRate = sourceSampleRate; + clip->mono.setSize(1, numSamples); + clip->mono.clear(); + const float channelGain = 1.0f / static_cast(sourceChannels); + for (int ch = 0; ch < sourceChannels; ++ch) + clip->mono.addFrom(0, 0, source, ch, startSample, numSamples, channelGain); + + const int fade = juce::jmin(numSamples / 2, static_cast(0.005 * sourceSampleRate)); + if (fade > 0) { + clip->mono.applyGainRamp(0, 0, fade, 0.0f, 1.0f); + clip->mono.applyGainRamp(0, numSamples - fade, fade, 1.0f, 0.0f); + } + + std::unique_ptr toFree1, toFree2; + { + const juce::SpinLock::ScopedLockType lock(lock_); + toFree1 = std::move(retired_); + toFree2 = std::move(pending_); + pending_ = std::move(clip); + stopRequested_ = false; + } + // toFree1/toFree2 are released here, on the message thread. +} + +void NoteAudition::stop() +{ + std::unique_ptr toFree1, toFree2; + { + const juce::SpinLock::ScopedLockType lock(lock_); + toFree1 = std::move(retired_); + toFree2 = std::move(pending_); + stopRequested_ = true; + } +} + +void NoteAudition::takePendingClip() +{ + // Never wait for the lock: if the message thread holds it, pick the clip up next block. + const juce::SpinLock::ScopedTryLockType tryLock(lock_); + if (!tryLock.isLocked()) + return; + + if (pending_ == nullptr && !stopRequested_) + return; + + // The old clip can be retired only if the retired slot is free. + // Otherwise wait until the message thread frees it (the clip plays one more block). + if (playing_ != nullptr && retired_ != nullptr) + return; + + if (playing_ != nullptr) + retired_ = std::move(playing_); + + if (stopRequested_) { + stopRequested_ = false; + return; + } + + playing_ = std::move(pending_); + position_ = 0.0; +} + +void NoteAudition::mixIntoBuffer(juce::AudioBuffer& output, int numSamples, double outputSampleRate) +{ + takePendingClip(); + + if (playing_ == nullptr || outputSampleRate <= 0.0) + return; + + const auto& clip = *playing_; + const int clipLength = clip.mono.getNumSamples(); + if (position_ >= static_cast(clipLength - 1)) + return; // finished - stay silent until the next note + + const float* src = clip.mono.getReadPointer(0); + const double step = clip.sampleRate / outputSampleRate; + const int outChannels = output.getNumChannels(); + numSamples = juce::jmin(numSamples, output.getNumSamples()); + + for (int i = 0; i < numSamples; ++i) { + const int index = static_cast(position_); + if (index >= clipLength - 1) + break; + // Linear interpolation is good enough for audition when the sample rates differ. + const float frac = static_cast(position_ - static_cast(index)); + const float sample = src[index] + (src[index + 1] - src[index]) * frac; + for (int ch = 0; ch < outChannels; ++ch) + output.addSample(ch, i, sample); + position_ += step; + } +} + +} // namespace OpenTune diff --git a/Source/Utils/NoteAudition.h b/Source/Utils/NoteAudition.h new file mode 100644 index 00000000..36ec5c03 --- /dev/null +++ b/Source/Utils/NoteAudition.h @@ -0,0 +1,51 @@ +#pragma once + +#include +#include +#include + +namespace OpenTune { + +/** + * Note audition: when moving between notes with the arrows, plays that note's vocal + * fragment, as in Melodyne. The host transport is not touched: the audio is + * mixed into the plugin output just like the piano key audition. + * + * play/stop are called on the message thread, mixIntoBuffer on the audio thread. + * The audio thread never allocates or frees memory: it parks the old clip + * in retired_, and the message thread frees it on its next call. + */ +class NoteAudition { +public: + NoteAudition() = default; + + /// Play numSamples of source from startSample (replaces whatever is playing). + void play(const juce::AudioBuffer& source, double sourceSampleRate, + int startSample, int numSamples); + void stop(); + + void mixIntoBuffer(juce::AudioBuffer& output, int numSamples, double outputSampleRate); + + static constexpr double kMaxDurationSeconds = 4.0; + +private: + struct Clip { + juce::AudioBuffer mono; + double sampleRate = 44100.0; + }; + + void takePendingClip(); + + juce::SpinLock lock_; + std::unique_ptr pending_; // guarded by lock_ + std::unique_ptr retired_; // guarded by lock_ + bool stopRequested_ = false; // guarded by lock_ + + // Audio thread only. + std::unique_ptr playing_; + double position_ = 0.0; + + JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NoteAudition) +}; + +} // namespace OpenTune diff --git a/Source/Utils/NoteSpeech.h b/Source/Utils/NoteSpeech.h new file mode 100644 index 00000000..3d43ec4d --- /dev/null +++ b/Source/Utils/NoteSpeech.h @@ -0,0 +1,54 @@ +#pragma once + +// Spoken note pitch text for screen readers: "A4 +25 ct", "C sharp 4". +// Standard library only, so the format can be tested without JUCE. + +#include +#include + +namespace OpenTune::NoteSpeech { + +// Nearest note and the deviation from it in cents (-50 to +49). +struct PitchParts +{ + int midi = 0; + int cents = 0; +}; + +inline PitchParts splitMidi(float midi) +{ + // Round to whole cents first, then split; otherwise 68.996 would give "A4 -0 ct". + const long totalCents = std::lround(static_cast(midi) * 100.0); + const long nearest = (totalCents + 50) / 100; + return { static_cast(nearest), static_cast(totalCents - nearest * 100) }; +} + +// "A4" or "C sharp 4". The # sign is avoided: speech synthesizers read it differently +// ("hash", "number"), so the sharp is passed as the word sharpWord. +inline std::string noteName(int midi, const std::string& sharpWord) +{ + static const char* const letters[12] = { "C", "C", "D", "D", "E", "F", "F", "G", "G", "A", "A", "B" }; + static const bool sharp[12] = { false, true, false, true, false, false, true, false, true, false, true, false }; + + const int pitchClass = ((midi % 12) + 12) % 12; + // Floor division for negative note numbers so the octave stays correct. + const int octave = (midi >= 0 ? midi / 12 : (midi - 11) / 12) - 1; + + std::string text = letters[pitchClass]; + if (sharp[pitchClass]) + text += " " + sharpWord + " "; + text += std::to_string(octave); + return text; +} + +// "A4 +25 ct"; with zero deviation just "A4". +inline std::string describeMidi(float midi, const std::string& sharpWord) +{ + const auto parts = splitMidi(midi); + std::string text = noteName(parts.midi, sharpWord); + if (parts.cents != 0) + text += (parts.cents > 0 ? " +" : " ") + std::to_string(parts.cents) + " ct"; + return text; +} + +} // namespace OpenTune::NoteSpeech diff --git a/Source/Utils/ScreenReaderAnnouncer.cpp b/Source/Utils/ScreenReaderAnnouncer.cpp new file mode 100644 index 00000000..628b2b93 --- /dev/null +++ b/Source/Utils/ScreenReaderAnnouncer.cpp @@ -0,0 +1,153 @@ +#include "ScreenReaderAnnouncer.h" + +#if JUCE_WINDOWS + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include + #include + #include + #if JUCE_MSVC + #pragma comment(lib, "oleaut32.lib") // SysAllocString / SysFreeString + #endif +#endif + +namespace OpenTune::a11y { + +#if JUCE_WINDOWS +namespace { + +// Values from UIAutomationCore.h (Windows 10 1709+). Declared here so the code does not +// depend on the Windows SDK version or _WIN32_WINNT. +constexpr int kNotificationKindOther = 4; // NotificationKind_Other +constexpr int kProcessingImportantAll = 0; // NotificationProcessing_ImportantAll +constexpr int kProcessingImportantMostRecent = 1; // NotificationProcessing_ImportantMostRecent + +using RaiseNotificationFn = HRESULT(WINAPI*)(IRawElementProviderSimple*, int, int, BSTR, BSTR); +using ClientsListeningFn = BOOL(WINAPI*)(); +using RaisePropertyChangedFn = HRESULT(WINAPI*)(IRawElementProviderSimple*, int, VARIANT, VARIANT); + +constexpr int kToggleStatePropertyId = 30086; // UIA_ToggleToggleStatePropertyId + +struct UiaFunctions +{ + UiaFunctions() + { + // Load at run time instead of linking: on old Windows the plugin should + // just stay silent rather than fail to load in the host. + if (auto* module = ::LoadLibraryW(L"UIAutomationCore.dll")) { + raise = reinterpret_cast(::GetProcAddress(module, "UiaRaiseNotificationEvent")); + listening = reinterpret_cast(::GetProcAddress(module, "UiaClientsAreListening")); + raiseProperty = reinterpret_cast( + ::GetProcAddress(module, "UiaRaiseAutomationPropertyChangedEvent")); + } + } + + RaiseNotificationFn raise = nullptr; + ClientsListeningFn listening = nullptr; + RaisePropertyChangedFn raiseProperty = nullptr; +}; + +const UiaFunctions& uia() +{ + static const UiaFunctions instance; + return instance; +} + +// The caller releases the result. nullptr if the component is excluded from the +// accessibility tree or not on screen yet. +IRawElementProviderSimple* providerFor(juce::Component& source) +{ + auto* handler = source.getAccessibilityHandler(); + if (handler == nullptr) + return nullptr; + + // On Windows JUCE's native implementation is a UI Automation provider COM object. + auto* unknown = reinterpret_cast(handler->getNativeImplementation()); + if (unknown == nullptr) + return nullptr; + + IRawElementProviderSimple* provider = nullptr; + if (FAILED(unknown->QueryInterface(__uuidof(IRawElementProviderSimple), + reinterpret_cast(&provider)))) + return nullptr; + return provider; +} + +} // namespace +#endif + +void announce(juce::Component& source, const juce::String& text, SpeechQueue queue) +{ + JUCE_ASSERT_MESSAGE_THREAD + + if (text.isEmpty()) + return; + +#if JUCE_WINDOWS + // Do not use juce::AccessibilityHandler::postAnnouncement: on Windows JUCE speaks it + // with a SAPI voice that bypasses the screen reader, and NVDA / JAWS never get it. + const auto& functions = uia(); + if (functions.raise == nullptr) + return; + if (functions.listening != nullptr && !functions.listening()) + return; // no screen reader running + + auto* provider = providerFor(source); + if (provider == nullptr) + return; + + auto* message = ::SysAllocString(text.toWideCharPointer()); + auto* activity = ::SysAllocString(L"OpenTuneAnnouncement"); + + functions.raise(provider, + kNotificationKindOther, + queue == SpeechQueue::replacePrevious ? kProcessingImportantMostRecent + : kProcessingImportantAll, + message, + activity); + + ::SysFreeString(message); + ::SysFreeString(activity); + provider->Release(); +#else + juce::ignoreUnused(source); + // On macOS JUCE forwards this to VoiceOver as a regular announcement. + juce::AccessibilityHandler::postAnnouncement(text, + queue == SpeechQueue::replacePrevious ? juce::AccessibilityHandler::AnnouncementPriority::high + : juce::AccessibilityHandler::AnnouncementPriority::medium); +#endif +} + +void notifyToggleChanged(juce::Component& source, bool checked) +{ + JUCE_ASSERT_MESSAGE_THREAD + +#if JUCE_WINDOWS + const auto& functions = uia(); + if (functions.raiseProperty == nullptr) + return; + if (functions.listening != nullptr && !functions.listening()) + return; // no screen reader running + + auto* provider = providerFor(source); + if (provider == nullptr) + return; + + VARIANT oldValue; + VARIANT newValue; + ::VariantInit(&oldValue); + ::VariantInit(&newValue); + oldValue.vt = VT_I4; + newValue.vt = VT_I4; + oldValue.lVal = checked ? 0 : 1; // ToggleState_Off / ToggleState_On + newValue.lVal = checked ? 1 : 0; + + functions.raiseProperty(provider, kToggleStatePropertyId, oldValue, newValue); + provider->Release(); +#else + announce(source, checked ? "Checked" : "Not checked"); +#endif +} + +} // namespace OpenTune::a11y diff --git a/Source/Utils/ScreenReaderAnnouncer.h b/Source/Utils/ScreenReaderAnnouncer.h new file mode 100644 index 00000000..119862a3 --- /dev/null +++ b/Source/Utils/ScreenReaderAnnouncer.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +// Short spoken messages for NVDA, JAWS and Narrator (Windows, UI Automation) +// and VoiceOver (macOS). +namespace OpenTune::a11y { + +enum class SpeechQueue +{ + replacePrevious, // a new message interrupts the previous one: navigation, values + keepAll // the message must not be lost: results, errors +}; + +// Speak text on behalf of the source component. It must be on screen and in the +// accessibility tree (usually the focused control). Title and description are not changed. +// Message thread only. +void announce(juce::Component& source, const juce::String& text, + SpeechQueue queue = SpeechQueue::replacePrevious); + +// Tell the screen reader that a check box on the source component changed: it then says +// "checked" / "not checked" itself, in its own language, as for a native check box. +// JUCE raises this event only for a toggle made through UI Automation, not for key presses. +// Message thread only. +void notifyToggleChanged(juce::Component& source, bool checked); + +} // namespace OpenTune::a11y diff --git a/Tests/AppPreferencesEditorSizeTests.cpp b/Tests/AppPreferencesEditorSizeTests.cpp index 22621836..8986101c 100644 --- a/Tests/AppPreferencesEditorSizeTests.cpp +++ b/Tests/AppPreferencesEditorSizeTests.cpp @@ -237,7 +237,7 @@ bool testLegacyShortcutMigration() juce::PropertiesFile migratedSettings(propertiesOptions); OpenTune::KeyShortcutConfig::ShortcutBinding persistedHorizontalZoom; OpenTune::KeyShortcutConfig::ShortcutBinding persistedVerticalZoomIn; - persistedMigration = migratedSettings.getIntValue("shared.shortcuts.schemaVersion", 0) == 3 + persistedMigration = migratedSettings.getIntValue("shared.shortcuts.schemaVersion", 0) == 4 // 4: F3/F5 for modulation/drift && OpenTune::KeyShortcutConfig::parseShortcutBinding( migratedSettings.getValue("shared.shortcuts.zoomHorizontalIn", {}), persistedHorizontalZoom) @@ -322,7 +322,7 @@ bool testMacShortcutDefaultMigration() OpenTune::KeyShortcutConfig::ShortcutBinding verticalZoomIn; OpenTune::KeyShortcutConfig::ShortcutBinding verticalZoomOut; OpenTune::KeyShortcutConfig::ShortcutBinding customSelect; - migrated = migratedSettings.getIntValue("shared.shortcuts.schemaVersion", 0) == 3 + migrated = migratedSettings.getIntValue("shared.shortcuts.schemaVersion", 0) == 4 // 4: F3/F5 for modulation/drift && OpenTune::KeyShortcutConfig::parseShortcutBinding( migratedSettings.getValue("shared.shortcuts.delete", {}), deleteBindings) && OpenTune::KeyShortcutConfig::parseShortcutBinding( @@ -454,7 +454,7 @@ bool testMacShortcutDefaultMigration() juce::PropertiesFile restoredSettings(propertiesOptions); OpenTune::KeyShortcutConfig::ShortcutBinding playPause; OpenTune::KeyShortcutConfig::ShortcutBinding stop; - restoredSpacePlay = restoredSettings.getIntValue("shared.shortcuts.schemaVersion", 0) == 3 + restoredSpacePlay = restoredSettings.getIntValue("shared.shortcuts.schemaVersion", 0) == 4 && OpenTune::KeyShortcutConfig::parseShortcutBinding( restoredSettings.getValue("shared.shortcuts.playPause", {}), playPause) && playPause.bindings.size() == 1 diff --git a/Tests/NoteSpeechTests.cpp b/Tests/NoteSpeechTests.cpp new file mode 100644 index 00000000..34751f71 --- /dev/null +++ b/Tests/NoteSpeechTests.cpp @@ -0,0 +1,37 @@ +// Tests for the spoken note pitch text (Utils/NoteSpeech.h). Standard library only. +#include "Utils/NoteSpeech.h" + +#include + +namespace { + +int failures = 0; + +void expectText(float midi, const char* expected) +{ + const auto text = OpenTune::NoteSpeech::describeMidi(midi, "sharp"); + if (text != expected) { + std::printf("FAIL: midi %.4f -> \"%s\", expected \"%s\"\n", midi, text.c_str(), expected); + ++failures; + } +} + +} // namespace + +int main() +{ + expectText(69.0f, "A4"); + expectText(69.25f, "A4 +25 ct"); + expectText(68.75f, "A4 -25 ct"); + expectText(68.996f, "A4"); // rounding to cents must not give "-0 ct" + expectText(60.0f, "C4"); + expectText(61.0f, "C sharp 4"); + expectText(71.5f, "C5 -50 ct"); // exactly halfway rounds up to the higher note + expectText(71.49f, "B4 +49 ct"); + expectText(59.0f, "B3"); + expectText(21.0f, "A0"); + + if (failures == 0) + std::printf("NoteSpeech tests passed\n"); + return failures == 0 ? 0 : 1; +}