адаптация s13bby/osc под vst и gui. (вайбкод)
вайбкод потому что мне в моменте стало понятно. что проще было сразу писать на фреймворке JUCE, чем адаптировать консольное приложение на MiniAudio. обновляться данный репозиторий не будет. СmakeLists адаптирован онли под linux.
This commit is contained in:
1 parent
8384123f87
commit
b0a75e98db
10387 files changed
+4025195
No files matched your search
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#if ! JUCE_NATIVE_ACCESSIBILITY_INCLUDED
|
||||
class AccessibilityHandler::AccessibilityNativeImpl
|
||||
{
|
||||
public:
|
||||
AccessibilityNativeImpl (AccessibilityHandler&) {}
|
||||
};
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
+662
@@ -0,0 +1,662 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
|
||||
int AccessibilityNativeHandle::idCounter = 0;
|
||||
|
||||
//==============================================================================
|
||||
class UIAScrollProvider final : public UIAProviderBase,
|
||||
public ComBaseClassHelper<IScrollProvider>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
JUCE_COMCALL Scroll (ScrollAmount, ScrollAmount) override { return E_FAIL; }
|
||||
JUCE_COMCALL SetScrollPercent (double, double) override { return E_FAIL; }
|
||||
JUCE_COMCALL get_HorizontalScrollPercent (double*) override { return E_FAIL; }
|
||||
JUCE_COMCALL get_VerticalScrollPercent (double*) override { return E_FAIL; }
|
||||
JUCE_COMCALL get_HorizontalViewSize (double*) override { return E_FAIL; }
|
||||
JUCE_COMCALL get_VerticalViewSize (double*) override { return E_FAIL; }
|
||||
JUCE_COMCALL get_HorizontallyScrollable (BOOL*) override { return E_FAIL; }
|
||||
JUCE_COMCALL get_VerticallyScrollable (BOOL*) override { return E_FAIL; }
|
||||
|
||||
private:
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIAScrollProvider)
|
||||
};
|
||||
|
||||
class UIAScrollItemProvider final : public UIAProviderBase,
|
||||
public ComBaseClassHelper<IScrollItemProvider>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
JUCE_COMCALL ScrollIntoView() override
|
||||
{
|
||||
if (auto* handler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (&getHandler(), &AccessibilityHandler::getTableInterface))
|
||||
{
|
||||
if (auto* tableInterface = handler->getTableInterface())
|
||||
{
|
||||
tableInterface->showCell (getHandler());
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
private:
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIAScrollItemProvider)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
static String getAutomationId (const AccessibilityHandler& handler)
|
||||
{
|
||||
auto result = handler.getTitle();
|
||||
auto* parentComponent = handler.getComponent().getParentComponent();
|
||||
|
||||
while (parentComponent != nullptr)
|
||||
{
|
||||
if (auto* parentHandler = parentComponent->getAccessibilityHandler())
|
||||
{
|
||||
auto parentTitle = parentHandler->getTitle();
|
||||
result << "." << (parentTitle.isNotEmpty() ? parentTitle : "<empty>");
|
||||
}
|
||||
|
||||
parentComponent = parentComponent->getParentComponent();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static auto roleToControlTypeId (AccessibilityRole roleType)
|
||||
{
|
||||
switch (roleType)
|
||||
{
|
||||
case AccessibilityRole::popupMenu:
|
||||
case AccessibilityRole::dialogWindow:
|
||||
case AccessibilityRole::splashScreen:
|
||||
case AccessibilityRole::window: return UIA_WindowControlTypeId;
|
||||
|
||||
case AccessibilityRole::label:
|
||||
case AccessibilityRole::staticText: return UIA_TextControlTypeId;
|
||||
|
||||
case AccessibilityRole::column:
|
||||
case AccessibilityRole::row: return UIA_ListItemControlTypeId;
|
||||
|
||||
case AccessibilityRole::button: return UIA_ButtonControlTypeId;
|
||||
case AccessibilityRole::toggleButton: return UIA_CheckBoxControlTypeId;
|
||||
case AccessibilityRole::radioButton: return UIA_RadioButtonControlTypeId;
|
||||
case AccessibilityRole::comboBox: return UIA_ComboBoxControlTypeId;
|
||||
case AccessibilityRole::image: return UIA_ImageControlTypeId;
|
||||
case AccessibilityRole::slider: return UIA_SliderControlTypeId;
|
||||
case AccessibilityRole::editableText: return UIA_EditControlTypeId;
|
||||
case AccessibilityRole::menuItem: return UIA_MenuItemControlTypeId;
|
||||
case AccessibilityRole::menuBar: return UIA_MenuBarControlTypeId;
|
||||
case AccessibilityRole::table: return UIA_TableControlTypeId;
|
||||
case AccessibilityRole::tableHeader: return UIA_HeaderControlTypeId;
|
||||
case AccessibilityRole::cell: return UIA_DataItemControlTypeId;
|
||||
case AccessibilityRole::hyperlink: return UIA_HyperlinkControlTypeId;
|
||||
case AccessibilityRole::list: return UIA_ListControlTypeId;
|
||||
case AccessibilityRole::listItem: return UIA_ListItemControlTypeId;
|
||||
case AccessibilityRole::tree: return UIA_TreeControlTypeId;
|
||||
case AccessibilityRole::treeItem: return UIA_TreeItemControlTypeId;
|
||||
case AccessibilityRole::progressBar: return UIA_ProgressBarControlTypeId;
|
||||
case AccessibilityRole::group: return UIA_GroupControlTypeId;
|
||||
case AccessibilityRole::scrollBar: return UIA_ScrollBarControlTypeId;
|
||||
case AccessibilityRole::tooltip: return UIA_ToolTipControlTypeId;
|
||||
|
||||
case AccessibilityRole::ignored:
|
||||
case AccessibilityRole::unspecified: break;
|
||||
};
|
||||
|
||||
return UIA_CustomControlTypeId;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
AccessibilityNativeHandle::AccessibilityNativeHandle (AccessibilityHandler& handler)
|
||||
: accessibilityHandler (handler)
|
||||
{
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::QueryInterface (REFIID refId, void** result)
|
||||
{
|
||||
*result = nullptr;
|
||||
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
if ((refId == __uuidof (IRawElementProviderFragmentRoot) && ! isFragmentRoot()))
|
||||
return E_NOINTERFACE;
|
||||
|
||||
return ComBaseClassHelper::QueryInterface (refId, result);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::get_HostRawElementProvider (IRawElementProviderSimple** pRetVal)
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
if (auto* wrapper = WindowsUIAWrapper::getInstanceWithoutCreating())
|
||||
{
|
||||
if (isFragmentRoot())
|
||||
return wrapper->hostProviderFromHwnd ((HWND) accessibilityHandler.getComponent().getWindowHandle(), pRetVal);
|
||||
|
||||
if (auto* embeddedWindow = static_cast<HWND> (AccessibilityHandler::getNativeChildForComponent (accessibilityHandler.getComponent())))
|
||||
return wrapper->hostProviderFromHwnd (embeddedWindow, pRetVal);
|
||||
}
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::get_ProviderOptions (ProviderOptions* options)
|
||||
{
|
||||
if (options == nullptr)
|
||||
return E_INVALIDARG;
|
||||
|
||||
*options = (ProviderOptions) (ProviderOptions_ServerSideProvider | ProviderOptions_UseComThreading);
|
||||
|
||||
if (isElementValid()
|
||||
&& AccessibilityHandler::getNativeChildForComponent (accessibilityHandler.getComponent()) != nullptr)
|
||||
{
|
||||
*options = (ProviderOptions) (*options | ProviderOptions_OverrideProvider);
|
||||
}
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::GetPatternProvider (PATTERNID pId, IUnknown** pRetVal)
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
*pRetVal = [&]() -> IUnknown*
|
||||
{
|
||||
const auto role = accessibilityHandler.getRole();
|
||||
const auto fragmentRoot = isFragmentRoot();
|
||||
|
||||
const auto isListOrTableCell = [] (auto& handler)
|
||||
{
|
||||
if (auto* tableHandler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (&handler, &AccessibilityHandler::getTableInterface))
|
||||
{
|
||||
if (auto* tableInterface = tableHandler->getTableInterface())
|
||||
{
|
||||
const auto row = tableInterface->getRowSpan (handler);
|
||||
const auto column = tableInterface->getColumnSpan (handler);
|
||||
|
||||
return row.hasValue() && column.hasValue();
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
switch (pId)
|
||||
{
|
||||
case UIA_WindowPatternId:
|
||||
{
|
||||
if (fragmentRoot)
|
||||
return new UIAWindowProvider (this);
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_TransformPatternId:
|
||||
{
|
||||
if (fragmentRoot)
|
||||
return new UIATransformProvider (this);
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_TextPatternId:
|
||||
case UIA_TextPattern2Id:
|
||||
{
|
||||
if (accessibilityHandler.getTextInterface() != nullptr)
|
||||
return new UIATextProvider (this);
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_ValuePatternId:
|
||||
{
|
||||
if (accessibilityHandler.getValueInterface() != nullptr)
|
||||
return new UIAValueProvider (this);
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_RangeValuePatternId:
|
||||
{
|
||||
if (accessibilityHandler.getValueInterface() != nullptr
|
||||
&& accessibilityHandler.getValueInterface()->getRange().isValid())
|
||||
{
|
||||
return new UIARangeValueProvider (this);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_TogglePatternId:
|
||||
{
|
||||
if (accessibilityHandler.getCurrentState().isCheckable()
|
||||
&& (accessibilityHandler.getActions().contains (AccessibilityActionType::toggle)
|
||||
|| accessibilityHandler.getActions().contains (AccessibilityActionType::press)))
|
||||
{
|
||||
return new UIAToggleProvider (this);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_SelectionPatternId:
|
||||
{
|
||||
if (role == AccessibilityRole::list
|
||||
|| role == AccessibilityRole::popupMenu
|
||||
|| role == AccessibilityRole::tree)
|
||||
{
|
||||
return new UIASelectionProvider (this);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_SelectionItemPatternId:
|
||||
{
|
||||
auto state = accessibilityHandler.getCurrentState();
|
||||
|
||||
if (state.isSelectable() || state.isMultiSelectable() || role == AccessibilityRole::radioButton)
|
||||
{
|
||||
return new UIASelectionItemProvider (this);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_TablePatternId:
|
||||
case UIA_GridPatternId:
|
||||
{
|
||||
if (accessibilityHandler.getTableInterface() != nullptr
|
||||
&& (pId == UIA_GridPatternId || accessibilityHandler.getRole() == AccessibilityRole::table))
|
||||
return static_cast<IGridProvider*> (new UIAGridProvider (this));
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_TableItemPatternId:
|
||||
case UIA_GridItemPatternId:
|
||||
{
|
||||
if (isListOrTableCell (accessibilityHandler))
|
||||
return static_cast<IGridItemProvider*> (new UIAGridItemProvider (this));
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_InvokePatternId:
|
||||
{
|
||||
if (accessibilityHandler.getActions().contains (AccessibilityActionType::press))
|
||||
return new UIAInvokeProvider (this);
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_ExpandCollapsePatternId:
|
||||
{
|
||||
if (accessibilityHandler.getActions().contains (AccessibilityActionType::showMenu)
|
||||
&& accessibilityHandler.getCurrentState().isExpandable())
|
||||
return new UIAExpandCollapseProvider (this);
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_ScrollPatternId:
|
||||
{
|
||||
if (accessibilityHandler.getTableInterface() != nullptr)
|
||||
return new UIAScrollProvider (this);
|
||||
|
||||
break;
|
||||
}
|
||||
case UIA_ScrollItemPatternId:
|
||||
{
|
||||
if (isListOrTableCell (accessibilityHandler))
|
||||
return new UIAScrollItemProvider (this);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}();
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::GetPropertyValue (PROPERTYID propertyId, VARIANT* pRetVal)
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
VariantHelpers::clear (pRetVal);
|
||||
|
||||
const auto role = accessibilityHandler.getRole();
|
||||
const auto state = accessibilityHandler.getCurrentState();
|
||||
const auto ignored = accessibilityHandler.isIgnored();
|
||||
|
||||
switch (propertyId)
|
||||
{
|
||||
case UIA_AutomationIdPropertyId:
|
||||
VariantHelpers::setString (getAutomationId (accessibilityHandler), pRetVal);
|
||||
break;
|
||||
case UIA_ControlTypePropertyId:
|
||||
VariantHelpers::setInt (roleToControlTypeId (role), pRetVal);
|
||||
break;
|
||||
case UIA_FrameworkIdPropertyId:
|
||||
VariantHelpers::setString ("JUCE", pRetVal);
|
||||
break;
|
||||
case UIA_FullDescriptionPropertyId:
|
||||
VariantHelpers::setString (accessibilityHandler.getDescription(), pRetVal);
|
||||
break;
|
||||
case UIA_HelpTextPropertyId:
|
||||
VariantHelpers::setString (accessibilityHandler.getHelp(), pRetVal);
|
||||
break;
|
||||
case UIA_IsContentElementPropertyId:
|
||||
VariantHelpers::setBool (! ignored && accessibilityHandler.isVisibleWithinParent(),
|
||||
pRetVal);
|
||||
break;
|
||||
case UIA_IsControlElementPropertyId:
|
||||
VariantHelpers::setBool (true, pRetVal);
|
||||
break;
|
||||
case UIA_IsDialogPropertyId:
|
||||
VariantHelpers::setBool (role == AccessibilityRole::dialogWindow, pRetVal);
|
||||
break;
|
||||
case UIA_IsEnabledPropertyId:
|
||||
VariantHelpers::setBool (accessibilityHandler.getComponent().isEnabled(), pRetVal);
|
||||
break;
|
||||
case UIA_IsKeyboardFocusablePropertyId:
|
||||
VariantHelpers::setBool (state.isFocusable(), pRetVal);
|
||||
break;
|
||||
case UIA_HasKeyboardFocusPropertyId:
|
||||
VariantHelpers::setBool (accessibilityHandler.hasFocus (true), pRetVal);
|
||||
break;
|
||||
case UIA_IsOffscreenPropertyId:
|
||||
VariantHelpers::setBool (! accessibilityHandler.isVisibleWithinParent(), pRetVal);
|
||||
break;
|
||||
case UIA_IsPasswordPropertyId:
|
||||
if (auto* textInterface = accessibilityHandler.getTextInterface())
|
||||
VariantHelpers::setBool (textInterface->isDisplayingProtectedText(), pRetVal);
|
||||
|
||||
break;
|
||||
case UIA_IsPeripheralPropertyId:
|
||||
VariantHelpers::setBool (role == AccessibilityRole::tooltip
|
||||
|| role == AccessibilityRole::popupMenu
|
||||
|| role == AccessibilityRole::splashScreen,
|
||||
pRetVal);
|
||||
break;
|
||||
case UIA_NamePropertyId:
|
||||
if (! ignored)
|
||||
VariantHelpers::setString (getElementName(), pRetVal);
|
||||
|
||||
break;
|
||||
case UIA_ProcessIdPropertyId:
|
||||
VariantHelpers::setInt ((int) GetCurrentProcessId(), pRetVal);
|
||||
break;
|
||||
case UIA_NativeWindowHandlePropertyId:
|
||||
if (isFragmentRoot())
|
||||
VariantHelpers::setInt ((int) (pointer_sized_int) accessibilityHandler.getComponent().getWindowHandle(), pRetVal);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::Navigate (NavigateDirection direction, IRawElementProviderFragment** pRetVal)
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
auto* handler = [&]() -> AccessibilityHandler*
|
||||
{
|
||||
if (direction == NavigateDirection_Parent)
|
||||
return accessibilityHandler.getParent();
|
||||
|
||||
if (direction == NavigateDirection_FirstChild
|
||||
|| direction == NavigateDirection_LastChild)
|
||||
{
|
||||
auto children = accessibilityHandler.getChildren();
|
||||
|
||||
return children.empty() ? nullptr
|
||||
: (direction == NavigateDirection_FirstChild ? children.front()
|
||||
: children.back());
|
||||
}
|
||||
|
||||
if (direction == NavigateDirection_NextSibling
|
||||
|| direction == NavigateDirection_PreviousSibling)
|
||||
{
|
||||
if (auto* parent = accessibilityHandler.getParent())
|
||||
{
|
||||
const auto siblings = parent->getChildren();
|
||||
const auto iter = std::find (siblings.cbegin(), siblings.cend(), &accessibilityHandler);
|
||||
|
||||
if (iter == siblings.end())
|
||||
return nullptr;
|
||||
|
||||
if (direction == NavigateDirection_NextSibling && iter != std::prev (siblings.cend()))
|
||||
return *std::next (iter);
|
||||
|
||||
if (direction == NavigateDirection_PreviousSibling && iter != siblings.cbegin())
|
||||
return *std::prev (iter);
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}();
|
||||
|
||||
if (handler != nullptr)
|
||||
if (auto* provider = handler->getNativeImplementation())
|
||||
if (provider->isElementValid())
|
||||
provider->QueryInterface (IID_PPV_ARGS (pRetVal));
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::GetRuntimeId (SAFEARRAY** pRetVal)
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
if (isFragmentRoot())
|
||||
return S_OK;
|
||||
|
||||
SafeArrayHandle result { SafeArrayCreateVector (VT_I4, 0, 2) };
|
||||
|
||||
if (result == nullptr)
|
||||
return E_FAIL;
|
||||
|
||||
for (LONG i = 0; i < 2; ++i)
|
||||
{
|
||||
if (FAILED (SafeArrayPutElement (result.get(), &i, &rtid[(size_t) i])))
|
||||
return E_FAIL;
|
||||
}
|
||||
|
||||
*pRetVal = result.release();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::get_BoundingRectangle (UiaRect* pRetVal)
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
auto bounds = Desktop::getInstance().getDisplays()
|
||||
.logicalToPhysical (accessibilityHandler.getComponent().getScreenBounds());
|
||||
|
||||
pRetVal->left = bounds.getX();
|
||||
pRetVal->top = bounds.getY();
|
||||
pRetVal->width = bounds.getWidth();
|
||||
pRetVal->height = bounds.getHeight();
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::GetEmbeddedFragmentRoots (SAFEARRAY** pRetVal)
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, []
|
||||
{
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::SetFocus()
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
const WeakReference<Component> safeComponent (&accessibilityHandler.getComponent());
|
||||
|
||||
accessibilityHandler.getActions().invoke (AccessibilityActionType::focus);
|
||||
|
||||
if (safeComponent != nullptr)
|
||||
accessibilityHandler.grabFocus();
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::get_FragmentRoot (IRawElementProviderFragmentRoot** pRetVal)
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]() -> HRESULT
|
||||
{
|
||||
auto* handler = [&]() -> AccessibilityHandler*
|
||||
{
|
||||
if (isFragmentRoot())
|
||||
return &accessibilityHandler;
|
||||
|
||||
if (auto* peer = accessibilityHandler.getComponent().getPeer())
|
||||
return peer->getComponent().getAccessibilityHandler();
|
||||
|
||||
return nullptr;
|
||||
}();
|
||||
|
||||
if (handler != nullptr)
|
||||
{
|
||||
handler->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (pRetVal));
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
});
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::ElementProviderFromPoint (double x, double y, IRawElementProviderFragment** pRetVal)
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
auto* handler = std::invoke ([&]
|
||||
{
|
||||
const auto logicalScreenPoint = Desktop::getInstance().getDisplays()
|
||||
.physicalToLogical (Point { x, y }.toFloat())
|
||||
.roundToInt();
|
||||
|
||||
if (auto* child = accessibilityHandler.getChildAt (logicalScreenPoint))
|
||||
return child;
|
||||
|
||||
return &accessibilityHandler;
|
||||
});
|
||||
|
||||
handler->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (pRetVal));
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::GetFocus (IRawElementProviderFragment** pRetVal)
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
const auto getFocusHandler = [this]() -> AccessibilityHandler*
|
||||
{
|
||||
if (auto* modal = Component::getCurrentlyModalComponent())
|
||||
{
|
||||
const auto& component = accessibilityHandler.getComponent();
|
||||
|
||||
if (! component.isParentOf (modal)
|
||||
&& component.isCurrentlyBlockedByAnotherModalComponent())
|
||||
{
|
||||
if (auto* modalHandler = modal->getAccessibilityHandler())
|
||||
{
|
||||
if (auto* focusChild = modalHandler->getChildFocus())
|
||||
return focusChild;
|
||||
|
||||
return modalHandler;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (auto* focusChild = accessibilityHandler.getChildFocus())
|
||||
return focusChild;
|
||||
|
||||
return nullptr;
|
||||
};
|
||||
|
||||
if (auto* focusHandler = getFocusHandler())
|
||||
focusHandler->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (pRetVal));
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT AccessibilityNativeHandle::GetOverrideProviderForHwnd (HWND hwnd, IRawElementProviderSimple** pRetVal)
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
if (auto* component = AccessibilityHandler::getComponentForNativeChild (hwnd))
|
||||
if (auto* handler = component->getAccessibilityHandler())
|
||||
handler->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (pRetVal));
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
String AccessibilityNativeHandle::getElementName() const
|
||||
{
|
||||
if (accessibilityHandler.getRole() == AccessibilityRole::tooltip)
|
||||
return accessibilityHandler.getDescription();
|
||||
|
||||
auto name = accessibilityHandler.getTitle();
|
||||
|
||||
if (name.isEmpty() && isFragmentRoot())
|
||||
return detail::AccessibilityHelpers::getApplicationOrPluginName();
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class AccessibilityNativeHandle : public ComBaseClassHelper<IRawElementProviderSimple,
|
||||
IRawElementProviderFragment,
|
||||
IRawElementProviderFragmentRoot,
|
||||
IRawElementProviderHwndOverride>
|
||||
{
|
||||
public:
|
||||
explicit AccessibilityNativeHandle (AccessibilityHandler& handler);
|
||||
|
||||
//==============================================================================
|
||||
void invalidateElement() noexcept { valid = false; }
|
||||
bool isElementValid() const noexcept { return valid; }
|
||||
|
||||
const AccessibilityHandler& getHandler() { return accessibilityHandler; }
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT QueryInterface (REFIID refId, void** result) override;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT get_HostRawElementProvider (IRawElementProviderSimple** provider) override;
|
||||
JUCE_COMRESULT get_ProviderOptions (ProviderOptions* options) override;
|
||||
JUCE_COMRESULT GetPatternProvider (PATTERNID pId, IUnknown** provider) override;
|
||||
JUCE_COMRESULT GetPropertyValue (PROPERTYID propertyId, VARIANT* pRetVal) override;
|
||||
|
||||
JUCE_COMRESULT Navigate (NavigateDirection direction, IRawElementProviderFragment** pRetVal) override;
|
||||
JUCE_COMRESULT GetRuntimeId (SAFEARRAY** pRetVal) override;
|
||||
JUCE_COMRESULT get_BoundingRectangle (UiaRect* pRetVal) override;
|
||||
JUCE_COMRESULT GetEmbeddedFragmentRoots (SAFEARRAY** pRetVal) override;
|
||||
JUCE_COMRESULT SetFocus() override;
|
||||
JUCE_COMRESULT get_FragmentRoot (IRawElementProviderFragmentRoot** pRetVal) override;
|
||||
|
||||
JUCE_COMRESULT ElementProviderFromPoint (double x, double y, IRawElementProviderFragment** pRetVal) override;
|
||||
JUCE_COMRESULT GetFocus (IRawElementProviderFragment** pRetVal) override;
|
||||
|
||||
JUCE_COMRESULT GetOverrideProviderForHwnd (HWND hwnd, IRawElementProviderSimple** pRetVal) override;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
String getElementName() const;
|
||||
bool isFragmentRoot() const { return accessibilityHandler.getComponent().isOnDesktop(); }
|
||||
|
||||
//==============================================================================
|
||||
AccessibilityHandler& accessibilityHandler;
|
||||
|
||||
static int idCounter;
|
||||
std::array<int, 2> rtid { UiaAppendRuntimeId, ++idCounter };
|
||||
bool valid = true;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AccessibilityNativeHandle)
|
||||
};
|
||||
|
||||
}
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
struct AccessibleObjCClassDeleter
|
||||
{
|
||||
template <typename ElementType>
|
||||
void operator() (ElementType* element) const
|
||||
{
|
||||
juceFreeAccessibilityPlatformSpecificData (element);
|
||||
|
||||
object_setInstanceVariable (element, "handler", nullptr);
|
||||
[element release];
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Base>
|
||||
class AccessibleObjCClass : public ObjCClass<Base>
|
||||
{
|
||||
public:
|
||||
using Holder = std::unique_ptr<Base, AccessibleObjCClassDeleter>;
|
||||
|
||||
protected:
|
||||
AccessibleObjCClass() : AccessibleObjCClass ("JUCEAccessibilityElement_") {}
|
||||
|
||||
explicit AccessibleObjCClass (const char* name) : ObjCClass<Base> (name)
|
||||
{
|
||||
ObjCClass<Base>::template addIvar<AccessibilityHandler*> ("handler");
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
static AccessibilityHandler* getHandler (id self)
|
||||
{
|
||||
return getIvar<AccessibilityHandler*> (self, "handler");
|
||||
}
|
||||
|
||||
template <typename MemberFn>
|
||||
static auto getInterface (id self, MemberFn fn) noexcept -> decltype ((std::declval<AccessibilityHandler>().*fn)())
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return (handler->*fn)();
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static AccessibilityTextInterface* getTextInterface (id self) noexcept { return getInterface (self, &AccessibilityHandler::getTextInterface); }
|
||||
static AccessibilityValueInterface* getValueInterface (id self) noexcept { return getInterface (self, &AccessibilityHandler::getValueInterface); }
|
||||
static AccessibilityTableInterface* getTableInterface (id self) noexcept { return getInterface (self, &AccessibilityHandler::getTableInterface); }
|
||||
static AccessibilityCellInterface* getCellInterface (id self) noexcept { return getInterface (self, &AccessibilityHandler::getCellInterface); }
|
||||
|
||||
static bool hasEditableText (AccessibilityHandler& handler) noexcept
|
||||
{
|
||||
return handler.getRole() == AccessibilityRole::editableText
|
||||
&& handler.getTextInterface() != nullptr
|
||||
&& ! handler.getTextInterface()->isReadOnly();
|
||||
}
|
||||
|
||||
static id getAccessibilityValueFromInterfaces (const AccessibilityHandler& handler)
|
||||
{
|
||||
if (auto* textInterface = handler.getTextInterface())
|
||||
return juceStringToNS (textInterface->getText ({ 0, textInterface->getTotalNumCharacters() }));
|
||||
|
||||
if (auto* valueInterface = handler.getValueInterface())
|
||||
return juceStringToNS (valueInterface->getCurrentValueAsString());
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
static BOOL getIsAccessibilityElement (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return ! handler->isIgnored() && handler->getRole() != AccessibilityRole::window;
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
static void setAccessibilityValue (id self, SEL, NSString* value)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (hasEditableText (*handler))
|
||||
{
|
||||
handler->getTextInterface()->setText (nsStringToJuce (value));
|
||||
return;
|
||||
}
|
||||
|
||||
if (auto* valueInterface = handler->getValueInterface())
|
||||
if (! valueInterface->isReadOnly())
|
||||
valueInterface->setValueAsString (nsStringToJuce (value));
|
||||
}
|
||||
}
|
||||
|
||||
static BOOL performActionIfSupported (id self, AccessibilityActionType actionType)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
if (handler->getActions().invoke (actionType))
|
||||
return YES;
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
static BOOL accessibilityPerformPress (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
if (handler->getCurrentState().isCheckable() && handler->getActions().invoke (AccessibilityActionType::toggle))
|
||||
return YES;
|
||||
|
||||
return performActionIfSupported (self, AccessibilityActionType::press);
|
||||
}
|
||||
|
||||
static BOOL accessibilityPerformIncrement (id self, SEL)
|
||||
{
|
||||
if (auto* valueInterface = getValueInterface (self))
|
||||
{
|
||||
if (! valueInterface->isReadOnly())
|
||||
{
|
||||
auto range = valueInterface->getRange();
|
||||
|
||||
if (range.isValid())
|
||||
{
|
||||
valueInterface->setValue (jlimit (range.getMinimumValue(),
|
||||
range.getMaximumValue(),
|
||||
valueInterface->getCurrentValue() + range.getInterval()));
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
static BOOL accessibilityPerformDecrement (id self, SEL)
|
||||
{
|
||||
if (auto* valueInterface = getValueInterface (self))
|
||||
{
|
||||
if (! valueInterface->isReadOnly())
|
||||
{
|
||||
auto range = valueInterface->getRange();
|
||||
|
||||
if (range.isValid())
|
||||
{
|
||||
valueInterface->setValue (jlimit (range.getMinimumValue(),
|
||||
range.getMaximumValue(),
|
||||
valueInterface->getCurrentValue() - range.getInterval()));
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
static NSString* getAccessibilityTitle (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
auto title = handler->getTitle();
|
||||
|
||||
if (title.isEmpty() && handler->getComponent().isOnDesktop())
|
||||
title = detail::AccessibilityHelpers::getApplicationOrPluginName();
|
||||
|
||||
NSString* nsString = juceStringToNS (title);
|
||||
|
||||
if (nsString != nil && [[self accessibilityValue] isEqual: nsString])
|
||||
return @"";
|
||||
|
||||
return nsString;
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
static NSString* getAccessibilityHelp (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return juceStringToNS (handler->getHelp());
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
static BOOL getIsAccessibilityModal (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return handler->getComponent().isCurrentlyModal();
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
static NSInteger getAccessibilityRowCount (id self, SEL)
|
||||
{
|
||||
if (auto* tableHandler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (getHandler (self), &AccessibilityHandler::getTableInterface))
|
||||
if (auto* tableInterface = tableHandler->getTableInterface())
|
||||
return tableInterface->getNumRows();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static NSInteger getAccessibilityColumnCount (id self, SEL)
|
||||
{
|
||||
if (auto* tableHandler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (getHandler (self), &AccessibilityHandler::getTableInterface))
|
||||
if (auto* tableInterface = tableHandler->getTableInterface())
|
||||
return tableInterface->getNumColumns();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
template <typename Getter>
|
||||
static NSRange getCellDimensions (id self, Getter getter)
|
||||
{
|
||||
const auto notFound = NSMakeRange (NSNotFound, 0);
|
||||
|
||||
auto* handler = getHandler (self);
|
||||
|
||||
if (handler == nullptr)
|
||||
return notFound;
|
||||
|
||||
auto* tableHandler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (getHandler (self), &AccessibilityHandler::getTableInterface);
|
||||
|
||||
if (tableHandler == nullptr)
|
||||
return notFound;
|
||||
|
||||
auto* tableInterface = tableHandler->getTableInterface();
|
||||
|
||||
if (tableInterface == nullptr)
|
||||
return notFound;
|
||||
|
||||
const auto result = (tableInterface->*getter) (*handler);
|
||||
|
||||
if (! result.hasValue())
|
||||
return notFound;
|
||||
|
||||
return NSMakeRange ((NSUInteger) result->begin, (NSUInteger) result->num);
|
||||
}
|
||||
|
||||
static NSRange getAccessibilityRowIndexRange (id self, SEL)
|
||||
{
|
||||
return getCellDimensions (self, &AccessibilityTableInterface::getRowSpan);
|
||||
}
|
||||
|
||||
static NSRange getAccessibilityColumnIndexRange (id self, SEL)
|
||||
{
|
||||
return getCellDimensions (self, &AccessibilityTableInterface::getColumnSpan);
|
||||
}
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AccessibleObjCClass)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,311 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
struct AccessibilityTextHelpers
|
||||
{
|
||||
/* Wraps a CharPtr into a stdlib-compatible iterator.
|
||||
|
||||
MSVC's std::reverse_iterator requires the wrapped iterator to be default constructible
|
||||
when building in C++20 mode, but I don't really want to add public default constructors to
|
||||
the CharPtr types. Instead, we add a very basic default constructor here which sets the
|
||||
wrapped CharPtr to nullptr.
|
||||
*/
|
||||
template <typename CharPtr>
|
||||
class CharPtrIteratorAdapter
|
||||
{
|
||||
public:
|
||||
using difference_type = int;
|
||||
using value_type = decltype (*std::declval<CharPtr>());
|
||||
using pointer = value_type*;
|
||||
using reference = value_type;
|
||||
using iterator_category = std::bidirectional_iterator_tag;
|
||||
|
||||
CharPtrIteratorAdapter() = default;
|
||||
constexpr explicit CharPtrIteratorAdapter (CharPtr arg) : ptr (arg) {}
|
||||
|
||||
constexpr auto operator*() const { return *ptr; }
|
||||
|
||||
constexpr CharPtrIteratorAdapter& operator++()
|
||||
{
|
||||
++ptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
constexpr CharPtrIteratorAdapter& operator--()
|
||||
{
|
||||
--ptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
constexpr bool operator== (const CharPtrIteratorAdapter& other) const { return ptr == other.ptr; }
|
||||
constexpr bool operator!= (const CharPtrIteratorAdapter& other) const { return ptr != other.ptr; }
|
||||
|
||||
constexpr auto operator+ (difference_type offset) const { return CharPtrIteratorAdapter { ptr + offset }; }
|
||||
constexpr auto operator- (difference_type offset) const { return CharPtrIteratorAdapter { ptr - offset }; }
|
||||
|
||||
private:
|
||||
CharPtr ptr { {} };
|
||||
};
|
||||
|
||||
template <typename CharPtr>
|
||||
static auto makeCharPtrIteratorAdapter (CharPtr ptr)
|
||||
{
|
||||
return CharPtrIteratorAdapter<CharPtr> { ptr };
|
||||
}
|
||||
|
||||
enum class BoundaryType
|
||||
{
|
||||
character,
|
||||
word,
|
||||
line,
|
||||
document
|
||||
};
|
||||
|
||||
enum class Direction
|
||||
{
|
||||
forwards,
|
||||
backwards
|
||||
};
|
||||
|
||||
enum class ExtendSelection
|
||||
{
|
||||
no,
|
||||
yes
|
||||
};
|
||||
|
||||
/* Indicates whether a function may return the current text position, in the case that the
|
||||
position already falls on a text unit boundary.
|
||||
*/
|
||||
enum class IncludeThisBoundary
|
||||
{
|
||||
no, //< Always search for the following boundary, even if the current position falls on a boundary
|
||||
yes //< Return the current position if it falls on a boundary
|
||||
};
|
||||
|
||||
/* Indicates whether a word boundary should include any whitespaces that follow the
|
||||
non-whitespace characters.
|
||||
*/
|
||||
enum class IncludeWhitespaceAfterWords
|
||||
{
|
||||
no, //< The word ends on the first whitespace character
|
||||
yes //< The word ends after the last whitespace character
|
||||
};
|
||||
|
||||
/* Like std::distance, but always does an O(N) count rather than an O(1) count, and doesn't
|
||||
require the iterators to have any member type aliases.
|
||||
*/
|
||||
template <typename Iter>
|
||||
static int countDifference (Iter from, Iter to)
|
||||
{
|
||||
int distance = 0;
|
||||
|
||||
while (from != to)
|
||||
{
|
||||
++from;
|
||||
++distance;
|
||||
}
|
||||
|
||||
return distance;
|
||||
}
|
||||
|
||||
/* Returns the number of characters between ptr and the next word end in a specific
|
||||
direction.
|
||||
|
||||
If ptr is inside a word, the result will be the distance to the end of the same
|
||||
word.
|
||||
*/
|
||||
template <typename CharPtr>
|
||||
static int findNextWordEndOffset (CharPtr beginIn,
|
||||
CharPtr endIn,
|
||||
CharPtr ptrIn,
|
||||
Direction direction,
|
||||
IncludeThisBoundary includeBoundary,
|
||||
IncludeWhitespaceAfterWords includeWhitespace)
|
||||
{
|
||||
const auto begin = makeCharPtrIteratorAdapter (beginIn);
|
||||
const auto end = makeCharPtrIteratorAdapter (endIn);
|
||||
const auto ptr = makeCharPtrIteratorAdapter (ptrIn);
|
||||
|
||||
const auto move = [&] (auto b, auto e, auto iter)
|
||||
{
|
||||
const auto isSpace = [] (juce_wchar c) { return CharacterFunctions::isWhitespace (c); };
|
||||
|
||||
const auto start = [&]
|
||||
{
|
||||
if (iter == b && includeBoundary == IncludeThisBoundary::yes)
|
||||
return b;
|
||||
|
||||
const auto nudged = iter - (iter != b && includeBoundary == IncludeThisBoundary::yes ? 1 : 0);
|
||||
|
||||
return includeWhitespace == IncludeWhitespaceAfterWords::yes
|
||||
? std::find_if (nudged, e, isSpace)
|
||||
: std::find_if_not (nudged, e, isSpace);
|
||||
}();
|
||||
|
||||
const auto found = includeWhitespace == IncludeWhitespaceAfterWords::yes
|
||||
? std::find_if_not (start, e, isSpace)
|
||||
: std::find_if (start, e, isSpace);
|
||||
|
||||
return countDifference (iter, found);
|
||||
};
|
||||
|
||||
return direction == Direction::forwards ? move (begin, end, ptr)
|
||||
: -move (std::make_reverse_iterator (end),
|
||||
std::make_reverse_iterator (begin),
|
||||
std::make_reverse_iterator (ptr));
|
||||
}
|
||||
|
||||
/* Returns the number of characters between ptr and the beginning of the next line in a
|
||||
specific direction.
|
||||
*/
|
||||
template <typename CharPtr>
|
||||
static int findNextLineOffset (CharPtr beginIn,
|
||||
CharPtr endIn,
|
||||
CharPtr ptrIn,
|
||||
Direction direction,
|
||||
IncludeThisBoundary includeBoundary)
|
||||
{
|
||||
const auto begin = makeCharPtrIteratorAdapter (beginIn);
|
||||
const auto end = makeCharPtrIteratorAdapter (endIn);
|
||||
const auto ptr = makeCharPtrIteratorAdapter (ptrIn);
|
||||
|
||||
const auto findNewline = [] (auto from, auto to) { return std::find (from, to, juce_wchar { '\n' }); };
|
||||
|
||||
if (direction == Direction::forwards)
|
||||
{
|
||||
if (ptr != begin && includeBoundary == IncludeThisBoundary::yes && *(ptr - 1) == '\n')
|
||||
return 0;
|
||||
|
||||
const auto newline = findNewline (ptr, end);
|
||||
return countDifference (ptr, newline) + (newline == end ? 0 : 1);
|
||||
}
|
||||
|
||||
const auto rbegin = std::make_reverse_iterator (ptr);
|
||||
const auto rend = std::make_reverse_iterator (begin);
|
||||
|
||||
return -countDifference (rbegin, findNewline (rbegin + (rbegin == rend || includeBoundary == IncludeThisBoundary::yes ? 0 : 1), rend));
|
||||
}
|
||||
|
||||
/* Unfortunately, the method of computing end-points of text units depends on context, and on
|
||||
the current platform.
|
||||
|
||||
Some examples of different behaviour:
|
||||
- On Android, updating the cursor/selection always searches for the next text unit boundary;
|
||||
but on Windows, ExpandToEnclosingUnit() should not move the starting point of the
|
||||
selection if it already at a unit boundary. This means that we need both inclusive and
|
||||
exclusive methods for finding the next text boundary.
|
||||
- On Android, moving the cursor by 'words' should move to the first space following a
|
||||
non-space character in the requested direction. On Windows, a 'word' includes trailing
|
||||
whitespace, but not preceding whitespace. This means that we need a way of specifying
|
||||
whether whitespace should be included when navigating by words.
|
||||
*/
|
||||
static int findTextBoundary (const AccessibilityTextInterface& textInterface,
|
||||
int currentPosition,
|
||||
BoundaryType boundary,
|
||||
Direction direction,
|
||||
IncludeThisBoundary includeBoundary,
|
||||
IncludeWhitespaceAfterWords includeWhitespace)
|
||||
{
|
||||
const auto numCharacters = textInterface.getTotalNumCharacters();
|
||||
const auto isForwards = (direction == Direction::forwards);
|
||||
const auto currentClamped = jlimit (0, numCharacters, currentPosition);
|
||||
|
||||
switch (boundary)
|
||||
{
|
||||
case BoundaryType::character:
|
||||
{
|
||||
const auto offset = includeBoundary == IncludeThisBoundary::yes ? 0
|
||||
: (isForwards ? 1 : -1);
|
||||
return jlimit (0, numCharacters, currentPosition + offset);
|
||||
}
|
||||
|
||||
case BoundaryType::word:
|
||||
{
|
||||
const auto str = textInterface.getText ({ 0, numCharacters });
|
||||
return currentClamped + findNextWordEndOffset (str.begin(),
|
||||
str.end(),
|
||||
str.begin() + currentClamped,
|
||||
direction,
|
||||
includeBoundary,
|
||||
includeWhitespace);
|
||||
}
|
||||
|
||||
case BoundaryType::line:
|
||||
{
|
||||
const auto str = textInterface.getText ({ 0, numCharacters });
|
||||
return currentClamped + findNextLineOffset (str.begin(),
|
||||
str.end(),
|
||||
str.begin() + currentClamped,
|
||||
direction,
|
||||
includeBoundary);
|
||||
}
|
||||
|
||||
case BoundaryType::document:
|
||||
return isForwards ? numCharacters : 0;
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Adjusts the current text selection range, using an algorithm appropriate for cursor movement
|
||||
on Android.
|
||||
*/
|
||||
static Range<int> findNewSelectionRangeAndroid (const AccessibilityTextInterface& textInterface,
|
||||
BoundaryType boundaryType,
|
||||
ExtendSelection extend,
|
||||
Direction direction)
|
||||
{
|
||||
const auto oldPos = textInterface.getTextInsertionOffset();
|
||||
const auto cursorPos = findTextBoundary (textInterface,
|
||||
oldPos,
|
||||
boundaryType,
|
||||
direction,
|
||||
IncludeThisBoundary::no,
|
||||
IncludeWhitespaceAfterWords::no);
|
||||
|
||||
if (extend == ExtendSelection::no)
|
||||
return { cursorPos, cursorPos };
|
||||
|
||||
const auto currentSelection = textInterface.getSelection();
|
||||
const auto start = currentSelection.getStart();
|
||||
const auto end = currentSelection.getEnd();
|
||||
return Range<int>::between (cursorPos, oldPos == start ? end : start);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
struct AccessibilityTextHelpersTest final : public UnitTest
|
||||
{
|
||||
AccessibilityTextHelpersTest()
|
||||
: UnitTest ("AccessibilityTextHelpers", UnitTestCategories::gui) {}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
using ATH = AccessibilityTextHelpers;
|
||||
|
||||
beginTest ("Android find word end");
|
||||
{
|
||||
const auto testMultiple = [this] (String str,
|
||||
int start,
|
||||
const std::vector<int>& collection)
|
||||
{
|
||||
auto it = collection.begin();
|
||||
|
||||
for (const auto direction : { ATH::Direction::forwards, ATH::Direction::backwards })
|
||||
{
|
||||
for (const auto includeBoundary : { ATH::IncludeThisBoundary::no, ATH::IncludeThisBoundary::yes })
|
||||
{
|
||||
for (const auto includeWhitespace : { ATH::IncludeWhitespaceAfterWords::no, ATH::IncludeWhitespaceAfterWords::yes })
|
||||
{
|
||||
const auto actual = ATH::findNextWordEndOffset (str.begin(), str.end(), str.begin() + start, direction, includeBoundary, includeWhitespace);
|
||||
const auto expected = *it++;
|
||||
expect (expected == actual);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Character Indices 0 3 56 13 50 51
|
||||
// | | || | | |
|
||||
const auto string = String ("hello world \r\n with some spaces in this sentence ") + String (CharPointer_UTF8 ("\xe2\x88\xae E\xe2\x8b\x85""da = Q"));
|
||||
// Direction forwards forwards forwards forwards backwards backwards backwards backwards
|
||||
// IncludeBoundary no no yes yes no no yes yes
|
||||
// IncludeWhitespace no yes no yes no yes no yes
|
||||
testMultiple (string, 0, { 5, 6, 5, 0, 0, 0, 0, 0 });
|
||||
testMultiple (string, 3, { 2, 3, 2, 3, -3, -3, -3, -3 });
|
||||
testMultiple (string, 5, { 6, 1, 0, 1, -5, -5, -5, 0 });
|
||||
testMultiple (string, 6, { 5, 9, 5, 0, -6, -1, 0, -1 });
|
||||
testMultiple (string, 13, { 6, 2, 6, 2, -7, -2, -7, -2 });
|
||||
testMultiple (string, 50, { 1, 2, 1, 0, -9, -1, 0, -1 });
|
||||
testMultiple (string, 51, { 5, 1, 0, 1, -1, -2, -1, 0 });
|
||||
|
||||
testMultiple (" a b ", 0, { 3, 2, 0, 2, 0, 0, 0, 0 });
|
||||
testMultiple (" a b ", 1, { 2, 1, 2, 1, -1, -1, -1, -1 });
|
||||
}
|
||||
|
||||
beginTest ("Android text range adjustment");
|
||||
{
|
||||
const auto testMultiple = [this] (String str,
|
||||
Range<int> initial,
|
||||
auto boundary,
|
||||
const std::vector<Range<int>>& collection)
|
||||
{
|
||||
auto it = collection.begin();
|
||||
|
||||
for (auto extend : { ATH::ExtendSelection::no, ATH::ExtendSelection::yes })
|
||||
{
|
||||
for (auto direction : { ATH::Direction::forwards, ATH::Direction::backwards })
|
||||
{
|
||||
for (auto insert : { CursorPosition::begin, CursorPosition::end })
|
||||
{
|
||||
const MockAccessibilityTextInterface mock { str, initial, insert };
|
||||
const auto actual = ATH::findNewSelectionRangeAndroid (mock, boundary, extend, direction);
|
||||
const auto expected = *it++;
|
||||
expect (expected == actual);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Extend no no no no yes yes yes yes
|
||||
// Direction forwards forwards backwards backwards forwards forwards backwards backwards
|
||||
// Insert begin end begin end begin end begin end
|
||||
testMultiple ("hello world", { 5, 5 }, ATH::BoundaryType::character, { { 6, 6 }, { 6, 6 }, { 4, 4 }, { 4, 4 }, { 5, 6 }, { 5, 6 }, { 4, 5 }, { 4, 5 } });
|
||||
testMultiple ("hello world", { 0, 0 }, ATH::BoundaryType::character, { { 1, 1 }, { 1, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 }, { 0, 1 }, { 0, 0 }, { 0, 0 } });
|
||||
testMultiple ("hello world", { 11, 11 }, ATH::BoundaryType::character, { { 11, 11 }, { 11, 11 }, { 10, 10 }, { 10, 10 }, { 11, 11 }, { 11, 11 }, { 10, 11 }, { 10, 11 } });
|
||||
testMultiple ("hello world", { 4, 5 }, ATH::BoundaryType::character, { { 5, 5 }, { 6, 6 }, { 3, 3 }, { 4, 4 }, { 5, 5 }, { 4, 6 }, { 3, 5 }, { 4, 4 } });
|
||||
testMultiple ("hello world", { 0, 1 }, ATH::BoundaryType::character, { { 1, 1 }, { 2, 2 }, { 0, 0 }, { 0, 0 }, { 1, 1 }, { 0, 2 }, { 0, 1 }, { 0, 0 } });
|
||||
testMultiple ("hello world", { 10, 11 }, ATH::BoundaryType::character, { { 11, 11 }, { 11, 11 }, { 9, 9 }, { 10, 10 }, { 11, 11 }, { 10, 11 }, { 9, 11 }, { 10, 10 } });
|
||||
|
||||
testMultiple ("foo bar baz", { 0, 0 }, ATH::BoundaryType::word, { { 3, 3 }, { 3, 3 }, { 0, 0 }, { 0, 0 }, { 0, 3 }, { 0, 3 }, { 0, 0 }, { 0, 0 } });
|
||||
testMultiple ("foo bar baz", { 1, 6 }, ATH::BoundaryType::word, { { 3, 3 }, { 8, 8 }, { 0, 0 }, { 5, 5 }, { 3, 6 }, { 1, 8 }, { 0, 6 }, { 1, 5 } });
|
||||
testMultiple ("foo bar baz", { 3, 3 }, ATH::BoundaryType::word, { { 8, 8 }, { 8, 8 }, { 0, 0 }, { 0, 0 }, { 3, 8 }, { 3, 8 }, { 0, 3 }, { 0, 3 } });
|
||||
testMultiple ("foo bar baz", { 3, 5 }, ATH::BoundaryType::word, { { 8, 8 }, { 8, 8 }, { 0, 0 }, { 0, 0 }, { 5, 8 }, { 3, 8 }, { 0, 5 }, { 0, 3 } });
|
||||
|
||||
testMultiple ("foo bar\n\n\na b\nc d e", { 0, 0 }, ATH::BoundaryType::line, { { 8, 8 }, { 8, 8 }, { 0, 0 }, { 0, 0 }, { 0, 8 }, { 0, 8 }, { 0, 0 }, { 0, 0 } });
|
||||
testMultiple ("foo bar\n\n\na b\nc d e", { 7, 7 }, ATH::BoundaryType::line, { { 8, 8 }, { 8, 8 }, { 0, 0 }, { 0, 0 }, { 7, 8 }, { 7, 8 }, { 0, 7 }, { 0, 7 } });
|
||||
testMultiple ("foo bar\n\n\na b\nc d e", { 8, 8 }, ATH::BoundaryType::line, { { 9, 9 }, { 9, 9 }, { 0, 0 }, { 0, 0 }, { 8, 9 }, { 8, 9 }, { 0, 8 }, { 0, 8 } });
|
||||
|
||||
testMultiple ("foo bar\r\na b\r\nxyz", { 0, 0 }, ATH::BoundaryType::line, { { 9, 9 }, { 9, 9 }, { 0, 0 }, { 0, 0 }, { 0, 9 }, { 0, 9 }, { 0, 0 }, { 0, 0 } });
|
||||
testMultiple ("foo bar\r\na b\r\nxyz", { 10, 10 }, ATH::BoundaryType::line, { { 14, 14 }, { 14, 14 }, { 9, 9 }, { 9, 9 }, { 10, 14 }, { 10, 14 }, { 9, 10 }, { 9, 10 } });
|
||||
}
|
||||
}
|
||||
|
||||
enum class CursorPosition { begin, end };
|
||||
|
||||
class MockAccessibilityTextInterface final : public AccessibilityTextInterface
|
||||
{
|
||||
public:
|
||||
MockAccessibilityTextInterface (String stringIn, Range<int> selectionIn, CursorPosition insertIn)
|
||||
: string (stringIn), selection (selectionIn), insert (insertIn) {}
|
||||
|
||||
bool isDisplayingProtectedText() const override { return false; }
|
||||
bool isReadOnly() const override { return false; }
|
||||
int getTotalNumCharacters() const override { return string.length(); }
|
||||
Range<int> getSelection() const override { return selection; }
|
||||
int getTextInsertionOffset() const override { return insert == CursorPosition::begin ? selection.getStart() : selection.getEnd(); }
|
||||
String getText (Range<int> range) const override { return string.substring (range.getStart(), range.getEnd()); }
|
||||
RectangleList<int> getTextBounds (Range<int>) const override { return {}; }
|
||||
int getOffsetAtPoint (Point<int>) const override { return 0; }
|
||||
|
||||
void setSelection (Range<int> newRange) override { selection = newRange; }
|
||||
void setText (const String& newText) override { string = newText; }
|
||||
|
||||
private:
|
||||
String string;
|
||||
Range<int> selection;
|
||||
CursorPosition insert;
|
||||
};
|
||||
};
|
||||
|
||||
static AccessibilityTextHelpersTest accessibilityTextHelpersTest;
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,674 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
static void juceFreeAccessibilityPlatformSpecificData (UIAccessibilityElement* element)
|
||||
{
|
||||
if (auto* container = juce::getIvar<UIAccessibilityElement*> (element, "container"))
|
||||
{
|
||||
object_setInstanceVariable (element, "container", nullptr);
|
||||
object_setInstanceVariable (container, "handler", nullptr);
|
||||
|
||||
[container release];
|
||||
}
|
||||
}
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#define JUCE_NATIVE_ACCESSIBILITY_INCLUDED 1
|
||||
|
||||
template <typename> struct Signature {};
|
||||
|
||||
template <typename Result, typename... Args>
|
||||
struct Signature<Result (Args...)> {};
|
||||
|
||||
// @selector isn't constexpr, so the 'sel' members are functions rather than static constexpr data members
|
||||
struct SignatureHasText final : public Signature<BOOL()> { static auto sel() { return @selector (hasText); } };
|
||||
struct SignatureSetSelectedTextRange final : public Signature<void (UITextRange*)> { static auto sel() { return @selector (setSelectedTextRange:); } };
|
||||
struct SignatureSelectedTextRange final : public Signature<UITextRange*()> { static auto sel() { return @selector (selectedTextRange); } };
|
||||
struct SignatureMarkedTextRange final : public Signature<UITextRange*()> { static auto sel() { return @selector (markedTextRange); } };
|
||||
struct SignatureSetMarkedTextSelectedRange final : public Signature<void (NSString*, NSRange)> { static auto sel() { return @selector (setMarkedText:selectedRange:); } };
|
||||
struct SignatureUnmarkText final : public Signature<void()> { static auto sel() { return @selector (unmarkText); } };
|
||||
struct SignatureMarkedTextStyle final : public Signature<NSDictionary<NSAttributedStringKey, id>*()> { static auto sel() { return @selector (markedTextStyle); } };
|
||||
struct SignatureSetMarkedTextStyle final : public Signature<void (NSDictionary<NSAttributedStringKey, id>*)> { static auto sel() { return @selector (setMarkedTextStyle:); } };
|
||||
struct SignatureBeginningOfDocument final : public Signature<UITextPosition*()> { static auto sel() { return @selector (beginningOfDocument); } };
|
||||
struct SignatureEndOfDocument final : public Signature<UITextPosition*()> { static auto sel() { return @selector (endOfDocument); } };
|
||||
struct SignatureTokenizer final : public Signature<id<UITextInputTokenizer>()> { static auto sel() { return @selector (tokenizer); } };
|
||||
struct SignatureBaseWritingDirection final : public Signature<NSWritingDirection (UITextPosition*, UITextStorageDirection)> { static auto sel() { return @selector (baseWritingDirectionForPosition:inDirection:); } };
|
||||
struct SignatureCaretRectForPosition final : public Signature<CGRect (UITextPosition*)> { static auto sel() { return @selector (caretRectForPosition:); } };
|
||||
struct SignatureCharacterRangeByExtending final : public Signature<UITextRange* (UITextPosition*, UITextLayoutDirection)> { static auto sel() { return @selector (characterRangeByExtendingPosition:inDirection:); } };
|
||||
struct SignatureCharacterRangeAtPoint final : public Signature<UITextRange* (CGPoint)> { static auto sel() { return @selector (characterRangeAtPoint:); } };
|
||||
struct SignatureClosestPositionToPoint final : public Signature<UITextPosition* (CGPoint)> { static auto sel() { return @selector (closestPositionToPoint:); } };
|
||||
struct SignatureClosestPositionToPointInRange final : public Signature<UITextPosition* (CGPoint, UITextRange*)> { static auto sel() { return @selector (closestPositionToPoint:withinRange:); } };
|
||||
struct SignatureComparePositionToPosition final : public Signature<NSComparisonResult (UITextPosition*, UITextPosition*)> { static auto sel() { return @selector (comparePosition:toPosition:); } };
|
||||
struct SignatureOffsetFromPositionToPosition final : public Signature<NSInteger (UITextPosition*, UITextPosition*)> { static auto sel() { return @selector (offsetFromPosition:toPosition:); } };
|
||||
struct SignaturePositionFromPositionInDirection final : public Signature<UITextPosition* (UITextPosition*, UITextLayoutDirection, NSInteger)> { static auto sel() { return @selector (positionFromPosition:inDirection:offset:); } };
|
||||
struct SignaturePositionFromPositionOffset final : public Signature<UITextPosition* (UITextPosition*, NSInteger)> { static auto sel() { return @selector (positionFromPosition:offset:); } };
|
||||
struct SignatureFirstRectForRange final : public Signature<CGRect (UITextRange*)> { static auto sel() { return @selector (firstRectForRange:); } };
|
||||
struct SignatureSelectionRectsForRange final : public Signature<NSArray<UITextSelectionRect*>* (UITextRange*)> { static auto sel() { return @selector (selectionRectsForRange:); } };
|
||||
struct SignaturePositionWithinRange final : public Signature<UITextPosition* (UITextRange*, UITextLayoutDirection)> { static auto sel() { return @selector (positionWithinRange:farthestInDirection:); } };
|
||||
struct SignatureReplaceRangeWithText final : public Signature<void (UITextRange*, NSString*)> { static auto sel() { return @selector (replaceRange:withText:); } };
|
||||
struct SignatureSetBaseWritingDirection final : public Signature<void (NSWritingDirection, UITextRange*)> { static auto sel() { return @selector (setBaseWritingDirection:forRange:); } };
|
||||
struct SignatureTextInRange final : public Signature<NSString* (UITextRange*)> { static auto sel() { return @selector (textInRange:); } };
|
||||
struct SignatureTextRangeFromPosition final : public Signature<UITextRange* (UITextPosition*, UITextPosition*)> { static auto sel() { return @selector (textRangeFromPosition:toPosition:); } };
|
||||
struct SignatureSetInputDelegate final : public Signature<void (id)> { static auto sel() { return @selector (setInputDelegate:); } };
|
||||
struct SignatureInputDelegate final : public Signature<id()> { static auto sel() { return @selector (inputDelegate); } };
|
||||
struct SignatureKeyboardType final : public Signature<UIKeyboardType()> { static auto sel() { return @selector (keyboardType); } };
|
||||
struct SignatureAutocapitalizationType final : public Signature<UITextAutocapitalizationType()> { static auto sel() { return @selector (autocapitalizationType); } };
|
||||
struct SignatureAutocorrectionType final : public Signature<UITextAutocorrectionType()> { static auto sel() { return @selector (autocorrectionType); } };
|
||||
|
||||
//==============================================================================
|
||||
class AccessibilityHandler::AccessibilityNativeImpl
|
||||
{
|
||||
public:
|
||||
explicit AccessibilityNativeImpl (AccessibilityHandler& handler)
|
||||
: accessibilityElement (AccessibilityElement::create (handler))
|
||||
{
|
||||
}
|
||||
|
||||
UIAccessibilityElement* getAccessibilityElement() const noexcept
|
||||
{
|
||||
return accessibilityElement.get();
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
class AccessibilityContainer final : public AccessibleObjCClass<NSObject>
|
||||
{
|
||||
public:
|
||||
AccessibilityContainer()
|
||||
: AccessibleObjCClass ("JUCEUIAccessibilityContainer_")
|
||||
{
|
||||
addMethod (@selector (isAccessibilityElement), [] (id, SEL) { return false; });
|
||||
|
||||
addMethod (@selector (accessibilityFrame), [] (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return convertToCGRect (handler->getComponent().getScreenBounds());
|
||||
|
||||
return CGRectZero;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityElements), [] (id self, SEL) -> NSArray*
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return getContainerAccessibilityElements (*handler);
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityDataTableCellElementForRow:column:), [] (id self, SEL, NSUInteger row, NSUInteger column) -> id
|
||||
{
|
||||
if (auto* tableHandler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (getHandler (self), &AccessibilityHandler::getTableInterface))
|
||||
if (auto* tableInterface = tableHandler->getTableInterface())
|
||||
if (auto* cellHandler = tableInterface->getCellHandler ((int) row, (int) column))
|
||||
if (auto* parent = getAccessibleParent (cellHandler))
|
||||
return static_cast<id> (parent->getNativeImplementation());
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityRowCount), getAccessibilityRowCount);
|
||||
addMethod (@selector (accessibilityColumnCount), getAccessibilityColumnCount);
|
||||
|
||||
addMethod (@selector (accessibilityHeaderElementsForColumn:), [] (id self, SEL, NSUInteger column) -> NSArray*
|
||||
{
|
||||
if (auto* tableHandler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (getHandler (self), &AccessibilityHandler::getTableInterface))
|
||||
{
|
||||
if (auto* tableInterface = tableHandler->getTableInterface())
|
||||
{
|
||||
if (auto* header = tableInterface->getHeaderHandler())
|
||||
{
|
||||
if (isPositiveAndBelow (column, header->getChildren().size()))
|
||||
{
|
||||
auto* result = [NSMutableArray new];
|
||||
[result addObject: static_cast<id> (header->getChildren()[(size_t) column]->getNativeImplementation())];
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
});
|
||||
|
||||
addProtocol (@protocol (UIAccessibilityContainerDataTable));
|
||||
|
||||
addMethod (@selector (accessibilityContainerType), [] (id self, SEL) -> NSInteger
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (handler->getTableInterface() != nullptr)
|
||||
return UIAccessibilityContainerTypeDataTable;
|
||||
|
||||
const auto handlerRole = handler->getRole();
|
||||
|
||||
if (handlerRole == AccessibilityRole::popupMenu
|
||||
|| handlerRole == AccessibilityRole::list
|
||||
|| handlerRole == AccessibilityRole::tree)
|
||||
{
|
||||
return UIAccessibilityContainerTypeList;
|
||||
}
|
||||
}
|
||||
|
||||
return UIAccessibilityContainerTypeNone;
|
||||
});
|
||||
|
||||
registerClass();
|
||||
}
|
||||
|
||||
private:
|
||||
static const AccessibilityHandler* getAccessibleParent (const AccessibilityHandler* h)
|
||||
{
|
||||
if (h == nullptr)
|
||||
return nullptr;
|
||||
|
||||
if ([static_cast<id> (h->getNativeImplementation()) isAccessibilityElement])
|
||||
return h;
|
||||
|
||||
return getAccessibleParent (h->getParent());
|
||||
}
|
||||
|
||||
static AccessibilityHandler* getHandler (id self)
|
||||
{
|
||||
return getIvar<AccessibilityHandler*> (self, "handler");
|
||||
}
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class AccessibilityElement final : public AccessibleObjCClass<UIAccessibilityElement>
|
||||
{
|
||||
template <typename Func, typename... Items>
|
||||
static constexpr void forEach (Func&& func, Items&&... items)
|
||||
{
|
||||
(func (std::forward<Items> (items)), ...);
|
||||
}
|
||||
|
||||
public:
|
||||
enum class Type { defaultElement, textElement };
|
||||
|
||||
static Holder create (AccessibilityHandler& handler)
|
||||
{
|
||||
static AccessibilityElement cls { Type::defaultElement };
|
||||
static AccessibilityElement textCls { Type::textElement };
|
||||
|
||||
id instance = (hasEditableText (handler) ? textCls : cls).createInstance();
|
||||
|
||||
Holder element ([instance initWithAccessibilityContainer: static_cast<id> (handler.getComponent().getWindowHandle())]);
|
||||
object_setInstanceVariable (element.get(), "handler", &handler);
|
||||
return element;
|
||||
}
|
||||
|
||||
AccessibilityElement (Type elementType)
|
||||
{
|
||||
addMethod (@selector (isAccessibilityElement), [] (id self, SEL)
|
||||
{
|
||||
auto* handler = getHandler (self);
|
||||
|
||||
const auto hasAccessiblePropertiesOrIsTableCell = [] (auto& handlerRef)
|
||||
{
|
||||
const auto isTableCell = [&]
|
||||
{
|
||||
if (auto* tableHandler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (&handlerRef, &AccessibilityHandler::getTableInterface))
|
||||
{
|
||||
if (auto* tableInterface = tableHandler->getTableInterface())
|
||||
{
|
||||
return tableInterface->getRowSpan (handlerRef).hasValue()
|
||||
&& tableInterface->getColumnSpan (handlerRef).hasValue();
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
return handlerRef.getTitle().isNotEmpty()
|
||||
|| handlerRef.getHelp().isNotEmpty()
|
||||
|| handlerRef.getTextInterface() != nullptr
|
||||
|| handlerRef.getValueInterface() != nullptr
|
||||
|| isTableCell();
|
||||
};
|
||||
|
||||
return handler != nullptr
|
||||
&& ! handler->isIgnored()
|
||||
&& handler->getRole() != AccessibilityRole::window
|
||||
&& hasAccessiblePropertiesOrIsTableCell (*handler);
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityContainer), [] (id self, SEL) -> id
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (handler->getComponent().isOnDesktop())
|
||||
return static_cast<id> (handler->getComponent().getWindowHandle());
|
||||
|
||||
if ( ! handler->getChildren().empty()
|
||||
|| AccessibilityHandler::getNativeChildForComponent (handler->getComponent()) != nullptr)
|
||||
{
|
||||
if (UIAccessibilityElement* container = getContainer (self))
|
||||
return container;
|
||||
|
||||
static AccessibilityContainer cls;
|
||||
|
||||
id container = cls.createInstance();
|
||||
|
||||
object_setInstanceVariable (container, "handler", handler);
|
||||
object_setInstanceVariable (self, "container", container);
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
if (auto* parent = handler->getParent())
|
||||
return [static_cast<id> (parent->getNativeImplementation()) accessibilityContainer];
|
||||
}
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityFrame), [] (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return convertToCGRect (handler->getComponent().getScreenBounds());
|
||||
|
||||
return CGRectZero;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityTraits), [] (id self, SEL)
|
||||
{
|
||||
auto traits = UIAccessibilityTraits{};
|
||||
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
traits |= [&handler]
|
||||
{
|
||||
switch (handler->getRole())
|
||||
{
|
||||
case AccessibilityRole::button:
|
||||
case AccessibilityRole::toggleButton:
|
||||
case AccessibilityRole::radioButton:
|
||||
case AccessibilityRole::comboBox: return UIAccessibilityTraitButton;
|
||||
|
||||
case AccessibilityRole::label:
|
||||
case AccessibilityRole::staticText: return UIAccessibilityTraitStaticText;
|
||||
|
||||
case AccessibilityRole::image: return UIAccessibilityTraitImage;
|
||||
case AccessibilityRole::tableHeader: return UIAccessibilityTraitHeader;
|
||||
case AccessibilityRole::hyperlink: return UIAccessibilityTraitLink;
|
||||
case AccessibilityRole::ignored: return UIAccessibilityTraitNotEnabled;
|
||||
|
||||
case AccessibilityRole::editableText: return UIAccessibilityTraitKeyboardKey;
|
||||
|
||||
case AccessibilityRole::slider:
|
||||
case AccessibilityRole::menuItem:
|
||||
case AccessibilityRole::menuBar:
|
||||
case AccessibilityRole::popupMenu:
|
||||
case AccessibilityRole::table:
|
||||
case AccessibilityRole::column:
|
||||
case AccessibilityRole::row:
|
||||
case AccessibilityRole::cell:
|
||||
case AccessibilityRole::list:
|
||||
case AccessibilityRole::listItem:
|
||||
case AccessibilityRole::tree:
|
||||
case AccessibilityRole::treeItem:
|
||||
case AccessibilityRole::progressBar:
|
||||
case AccessibilityRole::group:
|
||||
case AccessibilityRole::dialogWindow:
|
||||
case AccessibilityRole::window:
|
||||
case AccessibilityRole::scrollBar:
|
||||
case AccessibilityRole::tooltip:
|
||||
case AccessibilityRole::splashScreen:
|
||||
case AccessibilityRole::unspecified: break;
|
||||
}
|
||||
|
||||
return UIAccessibilityTraitNone;
|
||||
}();
|
||||
|
||||
const auto state = handler->getCurrentState();
|
||||
|
||||
if (state.isSelected() || state.isChecked())
|
||||
traits |= UIAccessibilityTraitSelected;
|
||||
|
||||
if (auto* valueInterface = getValueInterface (self))
|
||||
if (! valueInterface->isReadOnly() && valueInterface->getRange().isValid())
|
||||
traits |= UIAccessibilityTraitAdjustable;
|
||||
}
|
||||
|
||||
return traits | sendSuperclassMessage<UIAccessibilityTraits> (self, @selector (accessibilityTraits));
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityLabel), getAccessibilityTitle);
|
||||
addMethod (@selector (accessibilityHint), getAccessibilityHelp);
|
||||
|
||||
addMethod (@selector (accessibilityValue), [] (id self, SEL) -> NSString*
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (handler->getCurrentState().isCheckable())
|
||||
return handler->getCurrentState().isChecked() ? @"1" : @"0";
|
||||
|
||||
return (NSString*) getAccessibilityValueFromInterfaces (*handler);
|
||||
}
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (setAccessibilityValue:), setAccessibilityValue);
|
||||
|
||||
addMethod (@selector (accessibilityElementDidBecomeFocused), [] (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
const WeakReference<Component> safeComponent (&handler->getComponent());
|
||||
|
||||
performActionIfSupported (self, AccessibilityActionType::focus);
|
||||
|
||||
if (safeComponent != nullptr)
|
||||
handler->grabFocus();
|
||||
}
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityElementDidLoseFocus), [] (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
handler->giveAwayFocus();
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityElementIsFocused), [] (id self, SEL) -> BOOL
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return handler->hasFocus (false);
|
||||
|
||||
return NO;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityViewIsModal), getIsAccessibilityModal);
|
||||
|
||||
addMethod (@selector (accessibilityActivate), [] (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
// Occasionally VoiceOver sends accessibilityActivate to the wrong element, so we first query
|
||||
// which element it thinks has focus and forward the event on to that element if it differs
|
||||
id focusedElement = UIAccessibilityFocusedElement (UIAccessibilityNotificationVoiceOverIdentifier);
|
||||
|
||||
if (focusedElement != nullptr && ! [static_cast<id> (handler->getNativeImplementation()) isEqual: focusedElement])
|
||||
return [focusedElement accessibilityActivate];
|
||||
|
||||
if (handler->hasFocus (false))
|
||||
return accessibilityPerformPress (self, {});
|
||||
}
|
||||
|
||||
return NO;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityIncrement), accessibilityPerformIncrement);
|
||||
addMethod (@selector (accessibilityDecrement), accessibilityPerformDecrement);
|
||||
|
||||
addMethod (@selector (accessibilityPerformEscape), [] (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (auto* modal = Component::getCurrentlyModalComponent())
|
||||
{
|
||||
if (auto* modalHandler = modal->getAccessibilityHandler())
|
||||
{
|
||||
if (modalHandler == handler || modalHandler->isParentOf (handler))
|
||||
{
|
||||
modal->exitModalState (0);
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NO;
|
||||
});
|
||||
|
||||
if (elementType == Type::textElement)
|
||||
{
|
||||
addMethod (@selector (deleteBackward), [] (id, SEL) {});
|
||||
addMethod (@selector (insertText:), [] (id, SEL, NSString*) {});
|
||||
|
||||
forEach ([this] (auto signature) { addPassthroughMethodWithSignature (signature); },
|
||||
SignatureHasText{},
|
||||
SignatureSetSelectedTextRange{},
|
||||
SignatureSelectedTextRange{},
|
||||
SignatureMarkedTextRange{},
|
||||
SignatureSetMarkedTextSelectedRange{},
|
||||
SignatureUnmarkText{},
|
||||
SignatureMarkedTextStyle{},
|
||||
SignatureSetMarkedTextStyle{},
|
||||
SignatureBeginningOfDocument{},
|
||||
SignatureEndOfDocument{},
|
||||
SignatureTokenizer{},
|
||||
SignatureBaseWritingDirection{},
|
||||
SignatureCaretRectForPosition{},
|
||||
SignatureCharacterRangeByExtending{},
|
||||
SignatureCharacterRangeAtPoint{},
|
||||
SignatureClosestPositionToPoint{},
|
||||
SignatureClosestPositionToPointInRange{},
|
||||
SignatureComparePositionToPosition{},
|
||||
SignatureOffsetFromPositionToPosition{},
|
||||
SignaturePositionFromPositionInDirection{},
|
||||
SignaturePositionFromPositionOffset{},
|
||||
SignatureFirstRectForRange{},
|
||||
SignatureSelectionRectsForRange{},
|
||||
SignaturePositionWithinRange{},
|
||||
SignatureReplaceRangeWithText{},
|
||||
SignatureSetBaseWritingDirection{},
|
||||
SignatureTextInRange{},
|
||||
SignatureTextRangeFromPosition{},
|
||||
SignatureSetInputDelegate{},
|
||||
SignatureInputDelegate{},
|
||||
SignatureKeyboardType{},
|
||||
SignatureAutocapitalizationType{},
|
||||
SignatureAutocorrectionType{});
|
||||
|
||||
addProtocol (@protocol (UITextInput));
|
||||
}
|
||||
|
||||
addMethod (@selector (accessibilityRowRange), getAccessibilityRowIndexRange);
|
||||
addMethod (@selector (accessibilityColumnRange), getAccessibilityColumnIndexRange);
|
||||
addProtocol (@protocol (UIAccessibilityContainerDataTableCell));
|
||||
|
||||
addIvar<UIAccessibilityElement*> ("container");
|
||||
|
||||
registerClass();
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename Result>
|
||||
static auto getResult (NSInvocation* invocation, detail::Tag<Result>)
|
||||
{
|
||||
Result result{};
|
||||
[invocation getReturnValue: &result];
|
||||
return result;
|
||||
}
|
||||
|
||||
static void getResult (NSInvocation*, detail::Tag<void>) {}
|
||||
|
||||
template <typename HasSelector, typename Result, typename... Args>
|
||||
auto makePassthroughCallback (HasSelector, Signature<Result (Args...)>)
|
||||
{
|
||||
return [] (id self, SEL, Args... args) -> Result
|
||||
{
|
||||
if (auto* input = getPeerTextInput (self))
|
||||
{
|
||||
const auto s = detail::makeCompileTimeStr (@encode (Result), @encode (id), @encode (SEL), @encode (Args)...);
|
||||
const auto signature = [NSMethodSignature signatureWithObjCTypes: s.data()];
|
||||
|
||||
if (signature == nullptr)
|
||||
{
|
||||
jassertfalse;
|
||||
return Result();
|
||||
}
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wnullable-to-nonnull-conversion")
|
||||
const auto invocation = [NSInvocation invocationWithMethodSignature: signature];
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
invocation.selector = HasSelector::sel();
|
||||
|
||||
// Indices 0 and 1 are 'id self' and 'SEL _cmd' respectively
|
||||
auto counter = 2;
|
||||
forEach ([&] (auto& arg) { [invocation setArgument: &arg atIndex: counter++]; }, args...);
|
||||
|
||||
[invocation invokeWithTarget: input];
|
||||
|
||||
return getResult (invocation, detail::Tag<Result>{});
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return Result();
|
||||
};
|
||||
}
|
||||
|
||||
template <typename Signature>
|
||||
void addPassthroughMethodWithSignature (Signature signature)
|
||||
{
|
||||
addMethod (Signature::sel(), makePassthroughCallback (signature, signature));
|
||||
}
|
||||
|
||||
static UIAccessibilityElement* getContainer (id self)
|
||||
{
|
||||
return getIvar<UIAccessibilityElement*> (self, "container");
|
||||
}
|
||||
|
||||
static UIViewComponentPeer* getPeer (id self)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return static_cast<UIViewComponentPeer*> (handler->getComponent().getPeer());
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
static JuceTextView* getPeerTextInput (id self)
|
||||
{
|
||||
if (auto* peer = getPeer (self))
|
||||
return peer->hiddenTextInput.get();
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AccessibilityElement)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
AccessibilityElement::Holder accessibilityElement;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AccessibilityNativeImpl)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
AccessibilityNativeHandle* AccessibilityHandler::getNativeImplementation() const
|
||||
{
|
||||
return (AccessibilityNativeHandle*) nativeImpl->getAccessibilityElement();
|
||||
}
|
||||
|
||||
static bool areAnyAccessibilityClientsActive()
|
||||
{
|
||||
return UIAccessibilityIsVoiceOverRunning();
|
||||
}
|
||||
|
||||
static void sendAccessibilityEvent (UIAccessibilityNotifications notification, id argument)
|
||||
{
|
||||
if (! areAnyAccessibilityClientsActive())
|
||||
return;
|
||||
|
||||
jassert (notification != UIAccessibilityNotifications{});
|
||||
|
||||
UIAccessibilityPostNotification (notification, argument);
|
||||
}
|
||||
|
||||
void detail::AccessibilityHelpers::notifyAccessibilityEvent (const AccessibilityHandler& handler, Event eventType)
|
||||
{
|
||||
auto notification = [eventType]
|
||||
{
|
||||
switch (eventType)
|
||||
{
|
||||
case Event::elementCreated:
|
||||
case Event::elementDestroyed:
|
||||
case Event::elementMovedOrResized:
|
||||
case Event::focusChanged: return UIAccessibilityLayoutChangedNotification;
|
||||
|
||||
case Event::windowOpened:
|
||||
case Event::windowClosed: return UIAccessibilityScreenChangedNotification;
|
||||
}
|
||||
|
||||
return UIAccessibilityNotifications{};
|
||||
}();
|
||||
|
||||
if (notification != UIAccessibilityNotifications{})
|
||||
{
|
||||
const bool moveToHandler = (eventType == Event::focusChanged && handler.hasFocus (false));
|
||||
|
||||
sendAccessibilityEvent (notification,
|
||||
moveToHandler ? static_cast<id> (handler.getNativeImplementation()) : nil);
|
||||
}
|
||||
}
|
||||
|
||||
void AccessibilityHandler::notifyAccessibilityEvent (AccessibilityEvent eventType) const
|
||||
{
|
||||
auto notification = [eventType]
|
||||
{
|
||||
switch (eventType)
|
||||
{
|
||||
case AccessibilityEvent::textSelectionChanged:
|
||||
case AccessibilityEvent::rowSelectionChanged:
|
||||
case AccessibilityEvent::textChanged:
|
||||
case AccessibilityEvent::valueChanged:
|
||||
case AccessibilityEvent::titleChanged: break;
|
||||
|
||||
case AccessibilityEvent::structureChanged: return UIAccessibilityLayoutChangedNotification;
|
||||
}
|
||||
|
||||
return UIAccessibilityNotifications{};
|
||||
}();
|
||||
|
||||
if (notification != UIAccessibilityNotifications{})
|
||||
sendAccessibilityEvent (notification, static_cast<id> (getNativeImplementation()));
|
||||
}
|
||||
|
||||
void AccessibilityHandler::postAnnouncement (const String& announcementString, AnnouncementPriority)
|
||||
{
|
||||
sendAccessibilityEvent (UIAccessibilityAnnouncementNotification, juceStringToNS (announcementString));
|
||||
}
|
||||
|
||||
bool AccessibilityHandler::areAnyAccessibilityClientsActive()
|
||||
{
|
||||
return juce::areAnyAccessibilityClientsActive();
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,947 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
static void juceFreeAccessibilityPlatformSpecificData (NSAccessibilityElement<NSAccessibility>*) {}
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#define JUCE_NATIVE_ACCESSIBILITY_INCLUDED 1
|
||||
|
||||
//==============================================================================
|
||||
class AccessibilityHandler::AccessibilityNativeImpl
|
||||
{
|
||||
public:
|
||||
explicit AccessibilityNativeImpl (AccessibilityHandler& handler)
|
||||
: accessibilityElement (AccessibilityElement::create (handler))
|
||||
{
|
||||
}
|
||||
|
||||
NSAccessibilityElement<NSAccessibility>* getAccessibilityElement() const noexcept
|
||||
{
|
||||
return accessibilityElement.get();
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
class AccessibilityElement final : public AccessibleObjCClass<NSAccessibilityElement<NSAccessibility>>
|
||||
{
|
||||
public:
|
||||
static Holder create (AccessibilityHandler& handler)
|
||||
{
|
||||
static AccessibilityElement cls;
|
||||
Holder element ([cls.createInstance() init]);
|
||||
object_setInstanceVariable (element.get(), "handler", &handler);
|
||||
return element;
|
||||
}
|
||||
|
||||
private:
|
||||
AccessibilityElement()
|
||||
{
|
||||
addMethod (@selector (accessibilityNotifiesWhenDestroyed), [] (id, SEL) { return YES; });
|
||||
addMethod (@selector (isAccessibilityElement), getIsAccessibilityElement);
|
||||
|
||||
addMethod (@selector (isAccessibilityEnabled), [] (id self, SEL) -> BOOL
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return handler->getComponent().isEnabled();
|
||||
|
||||
return NO;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityWindow), getAccessibilityWindow);
|
||||
addMethod (@selector (accessibilityTopLevelUIElement), getAccessibilityWindow);
|
||||
addMethod (@selector (accessibilityChildren), getAccessibilityChildren);
|
||||
addMethod (@selector (isAccessibilityModal), getIsAccessibilityModal);
|
||||
|
||||
addMethod (@selector (accessibilityFocusedUIElement), [] (id self, SEL) -> id
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (auto* modal = Component::getCurrentlyModalComponent())
|
||||
{
|
||||
const auto& handlerComponent = handler->getComponent();
|
||||
|
||||
if (! handlerComponent.isParentOf (modal)
|
||||
&& handlerComponent.isCurrentlyBlockedByAnotherModalComponent())
|
||||
{
|
||||
if (auto* modalHandler = modal->getAccessibilityHandler())
|
||||
{
|
||||
if (auto* focusChild = modalHandler->getChildFocus())
|
||||
return static_cast<id> (focusChild->getNativeImplementation());
|
||||
|
||||
return static_cast<id> (modalHandler->getNativeImplementation());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (auto* focusChild = handler->getChildFocus())
|
||||
return static_cast<id> (focusChild->getNativeImplementation());
|
||||
}
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityHitTest:), [] (id self, SEL, NSPoint point) -> id
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (auto* child = handler->getChildAt (roundToIntPoint (flippedScreenPoint (point))))
|
||||
return static_cast<id> (child->getNativeImplementation());
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityParent), [] (id self, SEL) -> id
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (auto* parentHandler = handler->getParent())
|
||||
return NSAccessibilityUnignoredAncestor (static_cast<id> (parentHandler->getNativeImplementation()));
|
||||
|
||||
return NSAccessibilityUnignoredAncestor (static_cast<id> (handler->getComponent().getWindowHandle()));
|
||||
}
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (isAccessibilityFocused), [] (id self, SEL)
|
||||
{
|
||||
return [[self accessibilityWindow] accessibilityFocusedUIElement] == self;
|
||||
});
|
||||
|
||||
addMethod (@selector (setAccessibilityFocused:), [] (id self, SEL, BOOL focused)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (focused)
|
||||
{
|
||||
const WeakReference<Component> safeComponent (&handler->getComponent());
|
||||
|
||||
performActionIfSupported (self, AccessibilityActionType::focus);
|
||||
|
||||
if (safeComponent != nullptr)
|
||||
handler->grabFocus();
|
||||
}
|
||||
else
|
||||
{
|
||||
handler->giveAwayFocus();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityFrame), [] (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return flippedScreenRect (makeCGRect (handler->getComponent().getScreenBounds()));
|
||||
|
||||
return NSZeroRect;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityRole), [] (id self, SEL) -> NSAccessibilityRole
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
switch (handler->getRole())
|
||||
{
|
||||
case AccessibilityRole::popupMenu:
|
||||
case AccessibilityRole::tooltip:
|
||||
case AccessibilityRole::splashScreen:
|
||||
case AccessibilityRole::dialogWindow:
|
||||
case AccessibilityRole::window: return NSAccessibilityWindowRole;
|
||||
|
||||
case AccessibilityRole::tableHeader:
|
||||
case AccessibilityRole::unspecified:
|
||||
case AccessibilityRole::group: return NSAccessibilityGroupRole;
|
||||
|
||||
case AccessibilityRole::label:
|
||||
case AccessibilityRole::staticText: return NSAccessibilityStaticTextRole;
|
||||
|
||||
case AccessibilityRole::tree:
|
||||
case AccessibilityRole::list: return NSAccessibilityOutlineRole;
|
||||
|
||||
case AccessibilityRole::listItem:
|
||||
case AccessibilityRole::treeItem: return NSAccessibilityRowRole;
|
||||
|
||||
case AccessibilityRole::button: return NSAccessibilityButtonRole;
|
||||
case AccessibilityRole::toggleButton: return NSAccessibilityCheckBoxRole;
|
||||
case AccessibilityRole::radioButton: return NSAccessibilityRadioButtonRole;
|
||||
case AccessibilityRole::comboBox: return NSAccessibilityPopUpButtonRole;
|
||||
case AccessibilityRole::image: return NSAccessibilityImageRole;
|
||||
case AccessibilityRole::slider: return NSAccessibilitySliderRole;
|
||||
case AccessibilityRole::editableText: return NSAccessibilityTextAreaRole;
|
||||
case AccessibilityRole::menuItem: return NSAccessibilityMenuItemRole;
|
||||
case AccessibilityRole::menuBar: return NSAccessibilityMenuRole;
|
||||
case AccessibilityRole::table: return NSAccessibilityOutlineRole;
|
||||
case AccessibilityRole::column: return NSAccessibilityColumnRole;
|
||||
case AccessibilityRole::row: return NSAccessibilityRowRole;
|
||||
case AccessibilityRole::cell: return NSAccessibilityCellRole;
|
||||
case AccessibilityRole::hyperlink: return NSAccessibilityLinkRole;
|
||||
case AccessibilityRole::progressBar: return NSAccessibilityProgressIndicatorRole;
|
||||
case AccessibilityRole::scrollBar: return NSAccessibilityScrollBarRole;
|
||||
|
||||
case AccessibilityRole::ignored: break;
|
||||
}
|
||||
|
||||
return NSAccessibilityUnknownRole;
|
||||
}
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilitySubrole), [] (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (auto* textInterface = getTextInterface (self))
|
||||
if (textInterface->isDisplayingProtectedText())
|
||||
return NSAccessibilitySecureTextFieldSubrole;
|
||||
|
||||
const auto handlerRole = handler->getRole();
|
||||
|
||||
if (handlerRole == AccessibilityRole::window) return NSAccessibilityStandardWindowSubrole;
|
||||
if (handlerRole == AccessibilityRole::dialogWindow) return NSAccessibilityDialogSubrole;
|
||||
if (handlerRole == AccessibilityRole::tooltip
|
||||
|| handlerRole == AccessibilityRole::splashScreen) return NSAccessibilityFloatingWindowSubrole;
|
||||
if (handlerRole == AccessibilityRole::toggleButton) return NSAccessibilityToggleSubrole;
|
||||
if (handlerRole == AccessibilityRole::treeItem
|
||||
|| handlerRole == AccessibilityRole::listItem) return NSAccessibilityOutlineRowSubrole;
|
||||
if (handlerRole == AccessibilityRole::row && getCellInterface (self) != nullptr) return NSAccessibilityTableRowSubrole;
|
||||
|
||||
const auto& handlerComponent = handler->getComponent();
|
||||
|
||||
if (auto* documentWindow = handlerComponent.findParentComponentOfClass<DocumentWindow>())
|
||||
{
|
||||
if (handlerRole == AccessibilityRole::button)
|
||||
{
|
||||
if (&handlerComponent == documentWindow->getCloseButton()) return NSAccessibilityCloseButtonSubrole;
|
||||
if (&handlerComponent == documentWindow->getMinimiseButton()) return NSAccessibilityMinimizeButtonSubrole;
|
||||
if (&handlerComponent == documentWindow->getMaximiseButton()) return NSAccessibilityFullScreenButtonSubrole;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NSAccessibilityUnknownRole;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityLabel), [] (id self, SEL) -> NSString*
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return juceStringToNS (handler->getDescription());
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityValue), [] (id self, SEL) -> id
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (! handler->getCurrentState().isCheckable())
|
||||
return getAccessibilityValueFromInterfaces (*handler);
|
||||
|
||||
const auto checked = handler->getCurrentState().isChecked();
|
||||
|
||||
if ( handler->getRole() == AccessibilityRole::toggleButton
|
||||
|| handler->getRole() == AccessibilityRole::radioButton)
|
||||
{
|
||||
return checked ? @YES : @NO;
|
||||
}
|
||||
|
||||
return juceStringToNS (checked ? TRANS ("On") : TRANS ("Off"));
|
||||
}
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityTitle), getAccessibilityTitle);
|
||||
addMethod (@selector (accessibilityHelp), getAccessibilityHelp);
|
||||
addMethod (@selector (setAccessibilityValue:), setAccessibilityValue);
|
||||
|
||||
addMethod (@selector (accessibilitySelectedChildren), [] (id self, SEL)
|
||||
{
|
||||
return getSelectedChildren ([self accessibilityChildren]);
|
||||
});
|
||||
|
||||
addMethod (@selector (setAccessibilitySelectedChildren:), [] (id self, SEL, NSArray* selected)
|
||||
{
|
||||
setSelectedChildren ([self accessibilityChildren], selected);
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityOrientation), [] (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return handler->getComponent().getBounds().toFloat().getAspectRatio() > 1.0f
|
||||
? NSAccessibilityOrientationHorizontal
|
||||
: NSAccessibilityOrientationVertical;
|
||||
|
||||
return NSAccessibilityOrientationUnknown;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityInsertionPointLineNumber), [] (id self, SEL) -> NSInteger
|
||||
{
|
||||
if (auto* textInterface = getTextInterface (self))
|
||||
return [self accessibilityLineForIndex: textInterface->getTextInsertionOffset()];
|
||||
|
||||
return 0;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityVisibleCharacterRange), [] (id self, SEL)
|
||||
{
|
||||
if (auto* textInterface = getTextInterface (self))
|
||||
return juceRangeToNS ({ 0, textInterface->getTotalNumCharacters() });
|
||||
|
||||
return NSMakeRange (0, 0);
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityNumberOfCharacters), [] (id self, SEL)
|
||||
{
|
||||
if (auto* textInterface = getTextInterface (self))
|
||||
return textInterface->getTotalNumCharacters();
|
||||
|
||||
return 0;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilitySelectedText), [] (id self, SEL) -> NSString*
|
||||
{
|
||||
if (auto* textInterface = getTextInterface (self))
|
||||
return juceStringToNS (textInterface->getText (textInterface->getSelection()));
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilitySelectedTextRange), [] (id self, SEL)
|
||||
{
|
||||
if (auto* textInterface = getTextInterface (self))
|
||||
{
|
||||
const auto currentSelection = textInterface->getSelection();
|
||||
|
||||
if (currentSelection.isEmpty())
|
||||
return NSMakeRange ((NSUInteger) textInterface->getTextInsertionOffset(), 0);
|
||||
|
||||
return juceRangeToNS (currentSelection);
|
||||
}
|
||||
|
||||
return NSMakeRange (0, 0);
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityAttributedStringForRange:), [] (id self, SEL, NSRange range) -> NSAttributedString*
|
||||
{
|
||||
NSString* string = [self accessibilityStringForRange: range];
|
||||
|
||||
if (string != nil)
|
||||
return [[[NSAttributedString alloc] initWithString: string] autorelease];
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityRangeForLine:), [] (id self, SEL, NSInteger line)
|
||||
{
|
||||
if (auto* textInterface = getTextInterface (self))
|
||||
{
|
||||
auto text = textInterface->getText ({ 0, textInterface->getTotalNumCharacters() });
|
||||
auto lines = StringArray::fromLines (text);
|
||||
|
||||
if (line < lines.size())
|
||||
{
|
||||
auto lineText = lines[(int) line];
|
||||
auto start = text.indexOf (lineText);
|
||||
|
||||
if (start >= 0)
|
||||
return NSMakeRange ((NSUInteger) start, (NSUInteger) lineText.length());
|
||||
}
|
||||
}
|
||||
|
||||
return NSMakeRange (0, 0);
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityStringForRange:), [] (id self, SEL, NSRange range) -> NSString*
|
||||
{
|
||||
if (auto* textInterface = getTextInterface (self))
|
||||
return juceStringToNS (textInterface->getText (nsRangeToJuce (range)));
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityRangeForPosition:), [] (id self, SEL, NSPoint position)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (auto* textInterface = handler->getTextInterface())
|
||||
{
|
||||
auto screenPoint = roundToIntPoint (flippedScreenPoint (position));
|
||||
|
||||
if (handler->getComponent().getScreenBounds().contains (screenPoint))
|
||||
{
|
||||
auto offset = textInterface->getOffsetAtPoint (screenPoint);
|
||||
|
||||
if (offset >= 0)
|
||||
return NSMakeRange ((NSUInteger) offset, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NSMakeRange (0, 0);
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityRangeForIndex:), [] (id self, SEL, NSInteger index)
|
||||
{
|
||||
if (auto* textInterface = getTextInterface (self))
|
||||
if (isPositiveAndBelow (index, textInterface->getTotalNumCharacters()))
|
||||
return NSMakeRange ((NSUInteger) index, 1);
|
||||
|
||||
return NSMakeRange (0, 0);
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityFrameForRange:), [] (id self, SEL, NSRange range)
|
||||
{
|
||||
if (auto* textInterface = getTextInterface (self))
|
||||
return flippedScreenRect (makeCGRect (textInterface->getTextBounds (nsRangeToJuce (range)).getBounds()));
|
||||
|
||||
return NSZeroRect;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityLineForIndex:), [] (id self, SEL, NSInteger index)
|
||||
{
|
||||
if (auto* textInterface = getTextInterface (self))
|
||||
{
|
||||
auto text = textInterface->getText ({ 0, (int) index });
|
||||
|
||||
if (! text.isEmpty())
|
||||
return StringArray::fromLines (text).size() - 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
});
|
||||
|
||||
addMethod (@selector (setAccessibilitySelectedTextRange:), [] (id self, SEL, NSRange selectedRange)
|
||||
{
|
||||
if (auto* textInterface = getTextInterface (self))
|
||||
textInterface->setSelection (nsRangeToJuce (selectedRange));
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityRows), [] (id self, SEL) -> NSArray*
|
||||
{
|
||||
if (auto* tableInterface = getTableInterface (self))
|
||||
{
|
||||
auto* rows = [[NSMutableArray new] autorelease];
|
||||
|
||||
for (int row = 0, numRows = tableInterface->getNumRows(); row < numRows; ++row)
|
||||
{
|
||||
if (auto* rowHandler = tableInterface->getRowHandler (row))
|
||||
{
|
||||
[rows addObject: static_cast<id> (rowHandler->getNativeImplementation())];
|
||||
}
|
||||
else
|
||||
{
|
||||
[rows addObject: [NSAccessibilityElement accessibilityElementWithRole: NSAccessibilityRowRole
|
||||
frame: NSZeroRect
|
||||
label: @"Offscreen Row"
|
||||
parent: self]];
|
||||
}
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilitySelectedRows), [] (id self, SEL)
|
||||
{
|
||||
return getSelectedChildren ([self accessibilityRows]);
|
||||
});
|
||||
|
||||
addMethod (@selector (setAccessibilitySelectedRows:), [] (id self, SEL, NSArray* selected)
|
||||
{
|
||||
setSelectedChildren ([self accessibilityRows], selected);
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityHeader), [] (id self, SEL) -> id
|
||||
{
|
||||
if (auto* tableInterface = getTableInterface (self))
|
||||
if (auto* handler = tableInterface->getHeaderHandler())
|
||||
return static_cast<id> (handler->getNativeImplementation());
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityRowCount), getAccessibilityRowCount);
|
||||
addMethod (@selector (accessibilityColumnCount), getAccessibilityColumnCount);
|
||||
addMethod (@selector (accessibilityRowIndexRange), getAccessibilityRowIndexRange);
|
||||
addMethod (@selector (accessibilityColumnIndexRange), getAccessibilityColumnIndexRange);
|
||||
|
||||
addMethod (@selector (accessibilityIndex), [] (id self, SEL) -> NSInteger
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (auto* tableHandler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (handler, &AccessibilityHandler::getTableInterface))
|
||||
{
|
||||
if (auto* tableInterface = tableHandler->getTableInterface())
|
||||
{
|
||||
NSAccessibilityRole handlerRole = [self accessibilityRole];
|
||||
|
||||
if ([handlerRole isEqual: NSAccessibilityRowRole])
|
||||
if (const auto span = tableInterface->getRowSpan (*handler))
|
||||
return span->begin;
|
||||
|
||||
if ([handlerRole isEqual: NSAccessibilityColumnRole])
|
||||
if (const auto span = tableInterface->getColumnSpan (*handler))
|
||||
return span->begin;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityDisclosureLevel), [] (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
if (auto* cellInterface = handler->getCellInterface())
|
||||
return cellInterface->getDisclosureLevel();
|
||||
|
||||
return 0;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityDisclosedRows), [] (id self, SEL) -> id
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (auto* cellInterface = handler->getCellInterface())
|
||||
{
|
||||
const auto rows = cellInterface->getDisclosedRows();
|
||||
auto* result = [NSMutableArray arrayWithCapacity: rows.size()];
|
||||
|
||||
for (const auto& row : rows)
|
||||
{
|
||||
if (row != nullptr)
|
||||
[result addObject: static_cast<id> (row->getNativeImplementation())];
|
||||
else
|
||||
[result addObject: [NSAccessibilityElement accessibilityElementWithRole: NSAccessibilityRowRole
|
||||
frame: NSZeroRect
|
||||
label: @"Offscreen Row"
|
||||
parent: self]];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return nil;
|
||||
});
|
||||
|
||||
addMethod (@selector (isAccessibilityExpanded), [] (id self, SEL) -> BOOL
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
return handler->getCurrentState().isExpanded();
|
||||
|
||||
return NO;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityPerformIncrement), accessibilityPerformIncrement);
|
||||
addMethod (@selector (accessibilityPerformDecrement), accessibilityPerformDecrement);
|
||||
addMethod (@selector (accessibilityPerformDelete), [] (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
if (hasEditableText (*handler))
|
||||
{
|
||||
handler->getTextInterface()->setText ({});
|
||||
return YES;
|
||||
}
|
||||
|
||||
if (auto* valueInterface = handler->getValueInterface())
|
||||
{
|
||||
if (! valueInterface->isReadOnly())
|
||||
{
|
||||
valueInterface->setValue ({});
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NO;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityPerformPress), accessibilityPerformPress);
|
||||
|
||||
addMethod (@selector (accessibilityPerformShowMenu), [] (id self, SEL)
|
||||
{
|
||||
return performActionIfSupported (self, AccessibilityActionType::showMenu);
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityPerformRaise), [] (id self, SEL)
|
||||
{
|
||||
[self setAccessibilityFocused: YES]; return YES;
|
||||
});
|
||||
|
||||
addMethod (@selector (isAccessibilitySelectorAllowed:), [] (id self, SEL, SEL selector) -> BOOL
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
const auto handlerRole = handler->getRole();
|
||||
const auto currentState = handler->getCurrentState();
|
||||
|
||||
for (auto textSelector : { @selector (accessibilityInsertionPointLineNumber),
|
||||
@selector (accessibilityVisibleCharacterRange),
|
||||
@selector (accessibilityNumberOfCharacters),
|
||||
@selector (accessibilitySelectedText),
|
||||
@selector (accessibilitySelectedTextRange),
|
||||
@selector (accessibilityAttributedStringForRange:),
|
||||
@selector (accessibilityRangeForLine:),
|
||||
@selector (accessibilityStringForRange:),
|
||||
@selector (accessibilityRangeForPosition:),
|
||||
@selector (accessibilityRangeForIndex:),
|
||||
@selector (accessibilityFrameForRange:),
|
||||
@selector (accessibilityLineForIndex:),
|
||||
@selector (setAccessibilitySelectedTextRange:) })
|
||||
{
|
||||
if (selector == textSelector)
|
||||
return handler->getTextInterface() != nullptr;
|
||||
}
|
||||
|
||||
for (auto tableSelector : { @selector (accessibilityRowCount),
|
||||
@selector (accessibilityRows),
|
||||
@selector (accessibilitySelectedRows),
|
||||
@selector (accessibilityColumnCount),
|
||||
@selector (accessibilityHeader) })
|
||||
{
|
||||
if (selector == tableSelector)
|
||||
return handler->getTableInterface() != nullptr;
|
||||
}
|
||||
|
||||
for (auto cellSelector : { @selector (accessibilityRowIndexRange),
|
||||
@selector (accessibilityColumnIndexRange),
|
||||
@selector (accessibilityIndex),
|
||||
@selector (accessibilityDisclosureLevel) })
|
||||
{
|
||||
if (selector == cellSelector)
|
||||
return handler->getCellInterface() != nullptr;
|
||||
}
|
||||
|
||||
for (auto valueSelector : { @selector (accessibilityValue),
|
||||
@selector (setAccessibilityValue:),
|
||||
@selector (accessibilityPerformDelete),
|
||||
@selector (accessibilityPerformIncrement),
|
||||
@selector (accessibilityPerformDecrement) })
|
||||
{
|
||||
if (selector != valueSelector)
|
||||
continue;
|
||||
|
||||
auto* valueInterface = handler->getValueInterface();
|
||||
|
||||
if (selector == @selector (accessibilityValue))
|
||||
return valueInterface != nullptr
|
||||
|| hasEditableText (*handler)
|
||||
|| currentState.isCheckable();
|
||||
|
||||
auto hasEditableValue = [valueInterface] { return valueInterface != nullptr && ! valueInterface->isReadOnly(); };
|
||||
|
||||
if (selector == @selector (setAccessibilityValue:)
|
||||
|| selector == @selector (accessibilityPerformDelete))
|
||||
return hasEditableValue() || hasEditableText (*handler);
|
||||
|
||||
auto isRanged = [valueInterface] { return valueInterface != nullptr && valueInterface->getRange().isValid(); };
|
||||
|
||||
if (selector == @selector (accessibilityPerformIncrement)
|
||||
|| selector == @selector (accessibilityPerformDecrement))
|
||||
return hasEditableValue() && isRanged();
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
for (auto actionSelector : { @selector (accessibilityPerformPress),
|
||||
@selector (accessibilityPerformShowMenu),
|
||||
@selector (accessibilityPerformRaise),
|
||||
@selector (setAccessibilityFocused:) })
|
||||
{
|
||||
if (selector != actionSelector)
|
||||
continue;
|
||||
|
||||
if (selector == @selector (accessibilityPerformPress))
|
||||
return (handler->getCurrentState().isCheckable() && handler->getActions().contains (AccessibilityActionType::toggle))
|
||||
|| handler->getActions().contains (AccessibilityActionType::press);
|
||||
|
||||
if (selector == @selector (accessibilityPerformShowMenu))
|
||||
return handler->getActions().contains (AccessibilityActionType::showMenu);
|
||||
|
||||
if (selector == @selector (accessibilityPerformRaise))
|
||||
return [[self accessibilityRole] isEqual: NSAccessibilityWindowRole];
|
||||
|
||||
if (selector == @selector (setAccessibilityFocused:))
|
||||
return currentState.isFocusable();
|
||||
}
|
||||
|
||||
if (selector == @selector (accessibilitySelectedChildren))
|
||||
return handlerRole == AccessibilityRole::popupMenu;
|
||||
|
||||
if (selector == @selector (accessibilityOrientation))
|
||||
return handlerRole == AccessibilityRole::scrollBar;
|
||||
|
||||
if (selector == @selector (isAccessibilityExpanded))
|
||||
return currentState.isExpandable();
|
||||
|
||||
return sendSuperclassMessage<BOOL> (self, @selector (isAccessibilitySelectorAllowed:), selector);
|
||||
}
|
||||
|
||||
return NO;
|
||||
});
|
||||
|
||||
addMethod (@selector (accessibilityChildrenInNavigationOrder), getAccessibilityChildren);
|
||||
|
||||
registerClass();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
static bool isSelectable (AccessibleState state) noexcept
|
||||
{
|
||||
return state.isSelectable() || state.isMultiSelectable();
|
||||
}
|
||||
|
||||
static NSArray* getSelectedChildren (NSArray* children)
|
||||
{
|
||||
NSMutableArray* selected = [[NSMutableArray new] autorelease];
|
||||
|
||||
for (id child in children)
|
||||
{
|
||||
if (auto* handler = getHandler (child))
|
||||
{
|
||||
const auto currentState = handler->getCurrentState();
|
||||
|
||||
if (isSelectable (currentState) && currentState.isSelected())
|
||||
[selected addObject: child];
|
||||
}
|
||||
}
|
||||
|
||||
return selected;
|
||||
}
|
||||
|
||||
static void setSelected (id item, bool selected)
|
||||
{
|
||||
auto* handler = getHandler (item);
|
||||
|
||||
if (handler == nullptr)
|
||||
return;
|
||||
|
||||
const auto currentState = handler->getCurrentState();
|
||||
|
||||
if (isSelectable (currentState))
|
||||
{
|
||||
if (currentState.isSelected() != selected)
|
||||
handler->getActions().invoke (AccessibilityActionType::toggle);
|
||||
}
|
||||
else if (currentState.isFocusable())
|
||||
{
|
||||
[item setAccessibilityFocused: selected];
|
||||
}
|
||||
}
|
||||
|
||||
static void setSelectedChildren (NSArray* children, NSArray* selected)
|
||||
{
|
||||
for (id child in children)
|
||||
setSelected (child, [selected containsObject: child]);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
static id getAccessibilityWindow (id self, SEL)
|
||||
{
|
||||
return [[self accessibilityParent] accessibilityWindow];
|
||||
}
|
||||
|
||||
static NSArray* getAccessibilityChildren (id self, SEL)
|
||||
{
|
||||
if (auto* handler = getHandler (self))
|
||||
{
|
||||
auto children = handler->getChildren();
|
||||
|
||||
auto* accessibleChildren = [NSMutableArray arrayWithCapacity: (NSUInteger) children.size()];
|
||||
|
||||
for (auto* childHandler : children)
|
||||
[accessibleChildren addObject: static_cast<id> (childHandler->getNativeImplementation())];
|
||||
|
||||
if (id nativeChild = static_cast<id> (AccessibilityHandler::getNativeChildForComponent (handler->getComponent())))
|
||||
{
|
||||
// Having both native and non-native children would require implementing an
|
||||
// ordering. However, this situation doesn't occur with any of our current
|
||||
// use-cases.
|
||||
jassert ([accessibleChildren count] == 0);
|
||||
|
||||
if ([nativeChild isAccessibilityElement])
|
||||
[accessibleChildren addObject:nativeChild];
|
||||
else if (auto* childrenOfChild = [nativeChild accessibilityChildren]; childrenOfChild != nil)
|
||||
[accessibleChildren addObjectsFromArray:(NSArray* _Nonnull) childrenOfChild];
|
||||
}
|
||||
|
||||
return accessibleChildren;
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AccessibilityElement)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
AccessibilityElement::Holder accessibilityElement;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AccessibilityNativeImpl)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
AccessibilityNativeHandle* AccessibilityHandler::getNativeImplementation() const
|
||||
{
|
||||
return (AccessibilityNativeHandle*) nativeImpl->getAccessibilityElement();
|
||||
}
|
||||
|
||||
static bool areAnyAccessibilityClientsActive()
|
||||
{
|
||||
const String voiceOverKeyString ("voiceOverOnOffKey");
|
||||
const String applicationIDString ("com.apple.universalaccess");
|
||||
|
||||
CFUniquePtr<CFStringRef> cfKey (voiceOverKeyString.toCFString());
|
||||
CFUniquePtr<CFStringRef> cfID (applicationIDString.toCFString());
|
||||
|
||||
CFUniquePtr<CFPropertyListRef> value (CFPreferencesCopyAppValue (cfKey.get(), cfID.get()));
|
||||
|
||||
if (value != nullptr)
|
||||
return CFBooleanGetValue ((CFBooleanRef) value.get());
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static void sendAccessibilityEvent (id accessibilityElement,
|
||||
NSAccessibilityNotificationName notification,
|
||||
NSDictionary* userInfo)
|
||||
{
|
||||
jassert (notification != NSAccessibilityNotificationName{});
|
||||
|
||||
NSAccessibilityPostNotificationWithUserInfo (accessibilityElement, notification, userInfo);
|
||||
}
|
||||
|
||||
static void sendHandlerNotification (const AccessibilityHandler& handler,
|
||||
NSAccessibilityNotificationName notification)
|
||||
{
|
||||
if (! areAnyAccessibilityClientsActive() || notification == NSAccessibilityNotificationName{})
|
||||
return;
|
||||
|
||||
if (id accessibilityElement = static_cast<id> (handler.getNativeImplementation()))
|
||||
{
|
||||
sendAccessibilityEvent (accessibilityElement, notification,
|
||||
(notification == NSAccessibilityLayoutChangedNotification
|
||||
? @{ NSAccessibilityUIElementsKey: @[ accessibilityElement ] }
|
||||
: nil));
|
||||
}
|
||||
}
|
||||
|
||||
void detail::AccessibilityHelpers::notifyAccessibilityEvent (const AccessibilityHandler& handler, Event eventType)
|
||||
{
|
||||
auto notification = [eventType]
|
||||
{
|
||||
switch (eventType)
|
||||
{
|
||||
case Event::elementCreated: return NSAccessibilityCreatedNotification;
|
||||
case Event::elementDestroyed: return NSAccessibilityUIElementDestroyedNotification;
|
||||
case Event::elementMovedOrResized: return NSAccessibilityLayoutChangedNotification;
|
||||
case Event::focusChanged: return NSAccessibilityFocusedUIElementChangedNotification;
|
||||
case Event::windowOpened: return NSAccessibilityWindowCreatedNotification;
|
||||
case Event::windowClosed: break;
|
||||
}
|
||||
|
||||
return NSAccessibilityNotificationName{};
|
||||
}();
|
||||
|
||||
sendHandlerNotification (handler, notification);
|
||||
}
|
||||
|
||||
void AccessibilityHandler::notifyAccessibilityEvent (AccessibilityEvent eventType) const
|
||||
{
|
||||
auto notification = [eventType]
|
||||
{
|
||||
switch (eventType)
|
||||
{
|
||||
case AccessibilityEvent::textSelectionChanged: return NSAccessibilitySelectedTextChangedNotification;
|
||||
case AccessibilityEvent::rowSelectionChanged: return NSAccessibilitySelectedRowsChangedNotification;
|
||||
|
||||
case AccessibilityEvent::textChanged:
|
||||
case AccessibilityEvent::valueChanged: return NSAccessibilityValueChangedNotification;
|
||||
case AccessibilityEvent::titleChanged: return NSAccessibilityTitleChangedNotification;
|
||||
case AccessibilityEvent::structureChanged: return NSAccessibilityLayoutChangedNotification;
|
||||
}
|
||||
|
||||
return NSAccessibilityNotificationName{};
|
||||
}();
|
||||
|
||||
sendHandlerNotification (*this, notification);
|
||||
}
|
||||
|
||||
void AccessibilityHandler::postAnnouncement (const String& announcementString, AnnouncementPriority priority)
|
||||
{
|
||||
if (! areAnyAccessibilityClientsActive())
|
||||
return;
|
||||
|
||||
auto nsPriority = [priority]
|
||||
{
|
||||
// The below doesn't get noticed by the @available check above
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wunguarded-availability")
|
||||
|
||||
switch (priority)
|
||||
{
|
||||
case AnnouncementPriority::low: return NSAccessibilityPriorityLow;
|
||||
case AnnouncementPriority::medium: return NSAccessibilityPriorityMedium;
|
||||
case AnnouncementPriority::high: return NSAccessibilityPriorityHigh;
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return NSAccessibilityPriorityLow;
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}();
|
||||
|
||||
sendAccessibilityEvent (static_cast<id> ([NSApp mainWindow]),
|
||||
NSAccessibilityAnnouncementRequestedNotification,
|
||||
@{ NSAccessibilityAnnouncementKey: juceStringToNS (announcementString),
|
||||
NSAccessibilityPriorityKey: @(nsPriority) });
|
||||
}
|
||||
|
||||
bool AccessibilityHandler::areAnyAccessibilityClientsActive()
|
||||
{
|
||||
return juce::areAnyAccessibilityClientsActive();
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,350 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#define JUCE_NATIVE_ACCESSIBILITY_INCLUDED 1
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
|
||||
//==============================================================================
|
||||
struct WindowsAccessibility
|
||||
{
|
||||
WindowsAccessibility() = delete;
|
||||
|
||||
static long getUiaRootObjectId()
|
||||
{
|
||||
return static_cast<long> (UiaRootObjectId);
|
||||
}
|
||||
|
||||
static bool handleWmGetObject (AccessibilityHandler* handler, WPARAM wParam, LPARAM lParam, LRESULT* res)
|
||||
{
|
||||
if (isStartingUpOrShuttingDown() || (handler == nullptr || ! isHandlerValid (*handler)))
|
||||
return false;
|
||||
|
||||
if (auto* uiaWrapper = WindowsUIAWrapper::getInstance())
|
||||
{
|
||||
ComSmartPtr<IRawElementProviderSimple> provider;
|
||||
handler->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (provider.resetAndGetPointerAddress()));
|
||||
|
||||
if (! uiaWrapper->isProviderDisconnecting (provider))
|
||||
*res = uiaWrapper->returnRawElementProvider ((HWND) handler->getComponent().getWindowHandle(), wParam, lParam, provider);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static void revokeUIAMapEntriesForWindow (HWND hwnd)
|
||||
{
|
||||
if (auto* uiaWrapper = WindowsUIAWrapper::getInstanceWithoutCreating())
|
||||
uiaWrapper->returnRawElementProvider (hwnd, 0, 0, nullptr);
|
||||
}
|
||||
|
||||
static bool isStartingUpOrShuttingDown()
|
||||
{
|
||||
if (auto* app = JUCEApplicationBase::getInstance())
|
||||
if (app->isInitialising())
|
||||
return true;
|
||||
|
||||
if (auto* mm = MessageManager::getInstanceWithoutCreating())
|
||||
if (mm->hasStopMessageBeenSent())
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool isHandlerValid (const AccessibilityHandler& handler)
|
||||
{
|
||||
if (auto* provider = handler.getNativeImplementation())
|
||||
return provider->isElementValid();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool areAnyAccessibilityClientsActive()
|
||||
{
|
||||
const auto areClientsListening = []
|
||||
{
|
||||
if (auto* uiaWrapper = WindowsUIAWrapper::getInstanceWithoutCreating())
|
||||
return uiaWrapper->clientsAreListening() != 0;
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const auto isScreenReaderRunning = []
|
||||
{
|
||||
BOOL isRunning = FALSE;
|
||||
SystemParametersInfo (SPI_GETSCREENREADER, 0, (PVOID) &isRunning, 0);
|
||||
|
||||
return isRunning != 0;
|
||||
};
|
||||
|
||||
return areClientsListening() || isScreenReaderRunning();
|
||||
}
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class AccessibilityHandler::AccessibilityNativeImpl
|
||||
{
|
||||
public:
|
||||
explicit AccessibilityNativeImpl (AccessibilityHandler& owner)
|
||||
: accessibilityElement (new AccessibilityNativeHandle (owner), IncrementRef::no)
|
||||
{
|
||||
++providerCount;
|
||||
}
|
||||
|
||||
~AccessibilityNativeImpl()
|
||||
{
|
||||
ComSmartPtr<IRawElementProviderSimple> provider;
|
||||
accessibilityElement->QueryInterface (IID_PPV_ARGS (provider.resetAndGetPointerAddress()));
|
||||
|
||||
accessibilityElement->invalidateElement();
|
||||
--providerCount;
|
||||
|
||||
if (auto* uiaWrapper = WindowsUIAWrapper::getInstanceWithoutCreating())
|
||||
{
|
||||
uiaWrapper->disconnectProvider (provider);
|
||||
|
||||
if (providerCount == 0)
|
||||
uiaWrapper->disconnectAllProviders();
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
ComSmartPtr<AccessibilityNativeHandle> accessibilityElement;
|
||||
static int providerCount;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AccessibilityNativeImpl)
|
||||
};
|
||||
|
||||
int AccessibilityHandler::AccessibilityNativeImpl::providerCount = 0;
|
||||
|
||||
//==============================================================================
|
||||
AccessibilityNativeHandle* AccessibilityHandler::getNativeImplementation() const
|
||||
{
|
||||
return nativeImpl->accessibilityElement;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
void getProviderWithCheckedWrapper (const AccessibilityHandler& handler, Callback&& callback)
|
||||
{
|
||||
if (! WindowsAccessibility::areAnyAccessibilityClientsActive()
|
||||
|| WindowsAccessibility::isStartingUpOrShuttingDown()
|
||||
|| ! WindowsAccessibility::isHandlerValid (handler))
|
||||
return;
|
||||
|
||||
if (auto* uiaWrapper = WindowsUIAWrapper::getInstanceWithoutCreating())
|
||||
{
|
||||
ComSmartPtr<IRawElementProviderSimple> provider;
|
||||
handler.getNativeImplementation()->QueryInterface (IID_PPV_ARGS (provider.resetAndGetPointerAddress()));
|
||||
|
||||
callback (uiaWrapper, provider);
|
||||
}
|
||||
}
|
||||
|
||||
void sendAccessibilityAutomationEvent (const AccessibilityHandler& handler, EVENTID event)
|
||||
{
|
||||
jassert (event != EVENTID{});
|
||||
|
||||
getProviderWithCheckedWrapper (handler, [event] (WindowsUIAWrapper* uiaWrapper, ComSmartPtr<IRawElementProviderSimple>& provider)
|
||||
{
|
||||
uiaWrapper->raiseAutomationEvent (provider, event);
|
||||
});
|
||||
}
|
||||
|
||||
void sendAccessibilityPropertyChangedEvent (const AccessibilityHandler& handler, PROPERTYID property, VARIANT newValue)
|
||||
{
|
||||
jassert (property != PROPERTYID{});
|
||||
|
||||
getProviderWithCheckedWrapper (handler, [property, newValue] (WindowsUIAWrapper* uiaWrapper, ComSmartPtr<IRawElementProviderSimple>& provider)
|
||||
{
|
||||
VARIANT oldValue;
|
||||
VariantHelpers::clear (&oldValue);
|
||||
|
||||
uiaWrapper->raiseAutomationPropertyChangedEvent (provider, property, oldValue, newValue);
|
||||
});
|
||||
}
|
||||
|
||||
void detail::AccessibilityHelpers::notifyAccessibilityEvent (const AccessibilityHandler& handler, Event eventType)
|
||||
{
|
||||
if (eventType == Event::elementCreated
|
||||
|| eventType == Event::elementDestroyed)
|
||||
{
|
||||
if (auto* parent = handler.getParent())
|
||||
sendAccessibilityAutomationEvent (*parent, UIA_LayoutInvalidatedEventId);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (eventType == Event::windowOpened
|
||||
|| eventType == Event::windowClosed)
|
||||
{
|
||||
if (auto* peer = handler.getComponent().getPeer())
|
||||
if ((peer->getStyleFlags() & ComponentPeer::windowHasTitleBar) == 0)
|
||||
return;
|
||||
}
|
||||
|
||||
auto event = [eventType]() -> EVENTID
|
||||
{
|
||||
switch (eventType)
|
||||
{
|
||||
case Event::focusChanged: return UIA_AutomationFocusChangedEventId;
|
||||
case Event::windowOpened: return UIA_Window_WindowOpenedEventId;
|
||||
case Event::windowClosed: return UIA_Window_WindowClosedEventId;
|
||||
case Event::elementCreated:
|
||||
case Event::elementDestroyed:
|
||||
case Event::elementMovedOrResized: break;
|
||||
}
|
||||
|
||||
return {};
|
||||
}();
|
||||
|
||||
if (event != EVENTID{})
|
||||
sendAccessibilityAutomationEvent (handler, event);
|
||||
}
|
||||
|
||||
void AccessibilityHandler::notifyAccessibilityEvent (AccessibilityEvent eventType) const
|
||||
{
|
||||
if (eventType == AccessibilityEvent::titleChanged)
|
||||
{
|
||||
VARIANT newValue;
|
||||
VariantHelpers::setString (getTitle(), &newValue);
|
||||
|
||||
sendAccessibilityPropertyChangedEvent (*this, UIA_NamePropertyId, newValue);
|
||||
return;
|
||||
}
|
||||
|
||||
if (eventType == AccessibilityEvent::valueChanged)
|
||||
{
|
||||
if (getCurrentState().isCheckable())
|
||||
{
|
||||
VARIANT newValue;
|
||||
VariantHelpers::setInt (getCurrentState().isChecked() ? ToggleState_On
|
||||
: ToggleState_Off,
|
||||
&newValue);
|
||||
|
||||
sendAccessibilityPropertyChangedEvent (*this, UIA_ToggleToggleStatePropertyId, newValue);
|
||||
}
|
||||
|
||||
if (auto* valueInterface = getValueInterface())
|
||||
{
|
||||
const auto propertyType = getRole() == AccessibilityRole::slider ? UIA_RangeValueValuePropertyId
|
||||
: UIA_ValueValuePropertyId;
|
||||
|
||||
const auto value = getRole() == AccessibilityRole::slider
|
||||
? VariantHelpers::getWithValue (valueInterface->getCurrentValue())
|
||||
: VariantHelpers::getWithValue (valueInterface->getCurrentValueAsString());
|
||||
|
||||
sendAccessibilityPropertyChangedEvent (*this, propertyType, value);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
auto event = [eventType]() -> EVENTID
|
||||
{
|
||||
switch (eventType)
|
||||
{
|
||||
case AccessibilityEvent::textSelectionChanged: return UIA_Text_TextSelectionChangedEventId;
|
||||
case AccessibilityEvent::textChanged: return UIA_Text_TextChangedEventId;
|
||||
case AccessibilityEvent::structureChanged: return UIA_StructureChangedEventId;
|
||||
case AccessibilityEvent::rowSelectionChanged: return UIA_SelectionItem_ElementSelectedEventId;
|
||||
case AccessibilityEvent::titleChanged:
|
||||
case AccessibilityEvent::valueChanged: break;
|
||||
}
|
||||
|
||||
return {};
|
||||
}();
|
||||
|
||||
if (event != EVENTID{})
|
||||
sendAccessibilityAutomationEvent (*this, event);
|
||||
}
|
||||
|
||||
struct SpVoiceWrapper final : public DeletedAtShutdown
|
||||
{
|
||||
SpVoiceWrapper()
|
||||
{
|
||||
[[maybe_unused]] auto hr = voice.CoCreateInstance (CLSID_SpVoice);
|
||||
|
||||
jassert (SUCCEEDED (hr));
|
||||
}
|
||||
|
||||
~SpVoiceWrapper() override
|
||||
{
|
||||
clearSingletonInstance();
|
||||
}
|
||||
|
||||
ComSmartPtr<ISpVoice> voice;
|
||||
|
||||
JUCE_DECLARE_SINGLETON_INLINE (SpVoiceWrapper, false)
|
||||
};
|
||||
|
||||
|
||||
void AccessibilityHandler::postAnnouncement (const String& announcementString, AnnouncementPriority priority)
|
||||
{
|
||||
if (! areAnyAccessibilityClientsActive())
|
||||
return;
|
||||
|
||||
if (auto* sharedVoice = SpVoiceWrapper::getInstance())
|
||||
{
|
||||
auto voicePriority = [priority]
|
||||
{
|
||||
switch (priority)
|
||||
{
|
||||
case AnnouncementPriority::low: return SPVPRI_OVER;
|
||||
case AnnouncementPriority::medium: return SPVPRI_NORMAL;
|
||||
case AnnouncementPriority::high: return SPVPRI_ALERT;
|
||||
}
|
||||
|
||||
jassertfalse;
|
||||
return SPVPRI_OVER;
|
||||
}();
|
||||
|
||||
sharedVoice->voice->SetPriority (voicePriority);
|
||||
sharedVoice->voice->Speak (announcementString.toWideCharPointer(), SPF_ASYNC, nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
bool AccessibilityHandler::areAnyAccessibilityClientsActive()
|
||||
{
|
||||
return WindowsAccessibility::areAnyAccessibilityClientsActive();
|
||||
}
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
} // namespace juce
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class UIAExpandCollapseProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<IExpandCollapseProvider>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT Expand() override
|
||||
{
|
||||
return invokeShowMenu();
|
||||
}
|
||||
|
||||
JUCE_COMRESULT Collapse() override
|
||||
{
|
||||
return invokeShowMenu();
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_ExpandCollapseState (ExpandCollapseState* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
*pRetVal = getHandler().getCurrentState().isExpanded()
|
||||
? ExpandCollapseState_Expanded
|
||||
: ExpandCollapseState_Collapsed;
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
JUCE_COMRESULT invokeShowMenu()
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
const auto& handler = getHandler();
|
||||
|
||||
if (handler.getActions().invoke (AccessibilityActionType::showMenu))
|
||||
{
|
||||
sendAccessibilityAutomationEvent (handler, handler.getCurrentState().isExpanded()
|
||||
? UIA_MenuOpenedEventId
|
||||
: UIA_MenuClosedEventId);
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIAExpandCollapseProvider)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,167 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class UIAGridItemProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<IGridItemProvider, ITableItemProvider>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT get_Row (int* pRetVal) override
|
||||
{
|
||||
return withTableSpan (pRetVal,
|
||||
&AccessibilityTableInterface::getRowSpan,
|
||||
&AccessibilityTableInterface::Span::begin);
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_Column (int* pRetVal) override
|
||||
{
|
||||
return withTableSpan (pRetVal,
|
||||
&AccessibilityTableInterface::getColumnSpan,
|
||||
&AccessibilityTableInterface::Span::begin);
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_RowSpan (int* pRetVal) override
|
||||
{
|
||||
return withTableSpan (pRetVal,
|
||||
&AccessibilityTableInterface::getRowSpan,
|
||||
&AccessibilityTableInterface::Span::num);
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_ColumnSpan (int* pRetVal) override
|
||||
{
|
||||
return withTableSpan (pRetVal,
|
||||
&AccessibilityTableInterface::getColumnSpan,
|
||||
&AccessibilityTableInterface::Span::num);
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_ContainingGrid (IRawElementProviderSimple** pRetVal) override
|
||||
{
|
||||
return withTableInterface (pRetVal, [&] (const AccessibilityHandler& tableHandler)
|
||||
{
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
tableHandler.getNativeImplementation()->QueryInterface (IID_PPV_ARGS (pRetVal));
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetRowHeaderItems (SAFEARRAY**) override
|
||||
{
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetColumnHeaderItems (SAFEARRAY** pRetVal) override
|
||||
{
|
||||
return withTableInterface (pRetVal, [&] (const AccessibilityHandler& tableHandler)
|
||||
{
|
||||
if (auto* tableInterface = tableHandler.getTableInterface())
|
||||
{
|
||||
if (const auto column = tableInterface->getColumnSpan (getHandler()))
|
||||
{
|
||||
if (auto* header = tableInterface->getHeaderHandler())
|
||||
{
|
||||
const auto children = header->getChildren();
|
||||
|
||||
if (isPositiveAndBelow (column->begin, children.size()))
|
||||
{
|
||||
ComSmartPtr<IRawElementProviderSimple> provider;
|
||||
|
||||
if (auto* child = children[(size_t) column->begin])
|
||||
{
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
if (child->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (provider.resetAndGetPointerAddress())) == S_OK && provider != nullptr)
|
||||
{
|
||||
SafeArrayHandle result { SafeArrayCreateVector (VT_UNKNOWN, 0, 1) };
|
||||
|
||||
if (result == nullptr)
|
||||
return false;
|
||||
|
||||
if (LONG index = 0; FAILED (SafeArrayPutElement (result.get(), &index, provider)))
|
||||
return false;
|
||||
|
||||
*pRetVal = result.release();
|
||||
return true;
|
||||
}
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
private:
|
||||
template <typename Value, typename Callback>
|
||||
JUCE_COMRESULT withTableInterface (Value* pRetVal, Callback&& callback) const
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]() -> HRESULT
|
||||
{
|
||||
if (auto* handler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (&getHandler(), &AccessibilityHandler::getTableInterface))
|
||||
if (handler->getTableInterface() != nullptr && callback (*handler))
|
||||
return S_OK;
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT withTableSpan (int* pRetVal,
|
||||
Optional<AccessibilityTableInterface::Span> (AccessibilityTableInterface::* getSpan) (const AccessibilityHandler&) const,
|
||||
int AccessibilityTableInterface::Span::* spanMember) const
|
||||
{
|
||||
return withTableInterface (pRetVal, [&] (const AccessibilityHandler& handler)
|
||||
{
|
||||
if (const auto span = ((handler.getTableInterface())->*getSpan) (getHandler()))
|
||||
{
|
||||
*pRetVal = (*span).*spanMember;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIAGridItemProvider)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,162 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class UIAGridProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<IGridProvider, ITableProvider>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT GetItem (int row, int column, IRawElementProviderSimple** pRetVal) override
|
||||
{
|
||||
return withTableInterface (pRetVal, [&] (const AccessibilityTableInterface& tableInterface)
|
||||
{
|
||||
if (! isPositiveAndBelow (row, tableInterface.getNumRows())
|
||||
|| ! isPositiveAndBelow (column, tableInterface.getNumColumns()))
|
||||
return E_INVALIDARG;
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
|
||||
if (auto* cellHandler = tableInterface.getCellHandler (row, column))
|
||||
{
|
||||
cellHandler->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (pRetVal));
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
if (auto* rowHandler = tableInterface.getRowHandler (row))
|
||||
{
|
||||
rowHandler->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (pRetVal));
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
return E_FAIL;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_RowCount (int* pRetVal) override
|
||||
{
|
||||
return withTableInterface (pRetVal, [&] (const AccessibilityTableInterface& tableInterface)
|
||||
{
|
||||
*pRetVal = tableInterface.getNumRows();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_ColumnCount (int* pRetVal) override
|
||||
{
|
||||
return withTableInterface (pRetVal, [&] (const AccessibilityTableInterface& tableInterface)
|
||||
{
|
||||
*pRetVal = tableInterface.getNumColumns();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetRowHeaders (SAFEARRAY**) override
|
||||
{
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetColumnHeaders (SAFEARRAY** pRetVal) override
|
||||
{
|
||||
return withTableInterface (pRetVal, [&] (const AccessibilityTableInterface& tableInterface)
|
||||
{
|
||||
auto* header = tableInterface.getHeaderHandler();
|
||||
|
||||
if (header == nullptr)
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
|
||||
const auto children = header->getChildren();
|
||||
|
||||
SafeArrayHandle result { SafeArrayCreateVector (VT_UNKNOWN, 0, (ULONG) children.size()) };
|
||||
|
||||
if (result == nullptr)
|
||||
return E_FAIL;
|
||||
|
||||
LONG index = 0;
|
||||
|
||||
for (const auto& child : children)
|
||||
{
|
||||
ComSmartPtr<IRawElementProviderSimple> provider;
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
if (child != nullptr)
|
||||
child->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (provider.resetAndGetPointerAddress()));
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
if (provider == nullptr)
|
||||
return E_FAIL;
|
||||
|
||||
if (FAILED (SafeArrayPutElement (result.get(), &index, provider)))
|
||||
return E_FAIL;
|
||||
|
||||
++index;
|
||||
}
|
||||
|
||||
*pRetVal = result.release();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_RowOrColumnMajor (RowOrColumnMajor* pRetVal) override
|
||||
{
|
||||
*pRetVal = RowOrColumnMajor_RowMajor;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename Value, typename Callback>
|
||||
JUCE_COMRESULT withTableInterface (Value* pRetVal, Callback&& callback) const
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]() -> HRESULT
|
||||
{
|
||||
if (auto* tableHandler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (&getHandler(), &AccessibilityHandler::getTableInterface))
|
||||
if (auto* tableInterface = tableHandler->getTableInterface())
|
||||
return callback (*tableInterface);
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
});
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIAGridProvider)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,168 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class SafeArrayHandle
|
||||
{
|
||||
public:
|
||||
SafeArrayHandle() = default;
|
||||
|
||||
explicit SafeArrayHandle (SAFEARRAY* x) : ptr (x) {}
|
||||
|
||||
SafeArrayHandle (const SafeArrayHandle& x) = delete;
|
||||
SafeArrayHandle& operator= (const SafeArrayHandle& x) = delete;
|
||||
|
||||
SafeArrayHandle (SafeArrayHandle&& x) noexcept : ptr (std::exchange (x.ptr, {})) {}
|
||||
SafeArrayHandle& operator= (SafeArrayHandle&& x) noexcept
|
||||
{
|
||||
SafeArrayHandle tmp { std::move (x) };
|
||||
std::swap (tmp.ptr, ptr);
|
||||
return *this;
|
||||
}
|
||||
|
||||
~SafeArrayHandle()
|
||||
{
|
||||
if (ptr != nullptr)
|
||||
SafeArrayDestroy (ptr);
|
||||
}
|
||||
|
||||
SAFEARRAY* release()
|
||||
{
|
||||
return std::exchange (ptr, {});
|
||||
}
|
||||
|
||||
[[nodiscard]] SAFEARRAY* get() const
|
||||
{
|
||||
return ptr;
|
||||
}
|
||||
|
||||
bool operator== (std::nullptr_t) const { return ptr == nullptr; }
|
||||
bool operator!= (std::nullptr_t) const { return ptr != nullptr; }
|
||||
|
||||
private:
|
||||
SAFEARRAY* ptr = nullptr;
|
||||
};
|
||||
|
||||
namespace VariantHelpers
|
||||
{
|
||||
namespace Detail
|
||||
{
|
||||
template <typename Fn, typename ValueType>
|
||||
VARIANT getWithValueGeneric (Fn&& setter, ValueType value)
|
||||
{
|
||||
VARIANT result{};
|
||||
setter (value, &result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
inline void clear (VARIANT* variant)
|
||||
{
|
||||
variant->vt = VT_EMPTY;
|
||||
}
|
||||
|
||||
inline void setInt (int value, VARIANT* variant)
|
||||
{
|
||||
variant->vt = VT_I4;
|
||||
variant->lVal = value;
|
||||
}
|
||||
|
||||
inline void setBool (bool value, VARIANT* variant)
|
||||
{
|
||||
variant->vt = VT_BOOL;
|
||||
variant->boolVal = value ? -1 : 0;
|
||||
}
|
||||
|
||||
inline void setString (const String& value, VARIANT* variant)
|
||||
{
|
||||
variant->vt = VT_BSTR;
|
||||
variant->bstrVal = SysAllocString ((const OLECHAR*) value.toWideCharPointer());
|
||||
}
|
||||
|
||||
inline void setDouble (double value, VARIANT* variant)
|
||||
{
|
||||
variant->vt = VT_R8;
|
||||
variant->dblVal = value;
|
||||
}
|
||||
|
||||
inline VARIANT getWithValue (double value) { return Detail::getWithValueGeneric (&setDouble, value); }
|
||||
inline VARIANT getWithValue (const String& value) { return Detail::getWithValueGeneric (&setString, value); }
|
||||
}
|
||||
|
||||
inline JUCE_COMRESULT addHandlersToArray (const std::vector<const AccessibilityHandler*>& handlers, SAFEARRAY** pRetVal)
|
||||
{
|
||||
auto numHandlers = handlers.size();
|
||||
|
||||
SafeArrayHandle result { SafeArrayCreateVector (VT_UNKNOWN, 0, (ULONG) numHandlers) };
|
||||
|
||||
if (result == nullptr)
|
||||
return E_FAIL;
|
||||
|
||||
for (LONG i = 0; i < (LONG) numHandlers; ++i)
|
||||
{
|
||||
auto* handler = handlers[(size_t) i];
|
||||
|
||||
if (handler == nullptr)
|
||||
continue;
|
||||
|
||||
ComSmartPtr<IRawElementProviderSimple> provider;
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
handler->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (provider.resetAndGetPointerAddress()));
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
if (FAILED (SafeArrayPutElement (result.get(), &i, provider)))
|
||||
return E_FAIL;
|
||||
}
|
||||
|
||||
*pRetVal = result.release();
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
template <typename Value, typename Object, typename Callback>
|
||||
JUCE_COMRESULT withCheckedComArgs (Value* pRetVal, Object& handle, Callback&& callback)
|
||||
{
|
||||
if (pRetVal == nullptr)
|
||||
return E_INVALIDARG;
|
||||
|
||||
*pRetVal = Value{};
|
||||
|
||||
if (! handle.isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
return callback();
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class UIAInvokeProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<IInvokeProvider>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT Invoke() override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
const auto& handler = getHandler();
|
||||
|
||||
if (handler.getActions().invoke (AccessibilityActionType::press))
|
||||
{
|
||||
if (isElementValid())
|
||||
sendAccessibilityAutomationEvent (handler, UIA_Invoke_InvokedEventId);
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIAInvokeProvider)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class UIAProviderBase
|
||||
{
|
||||
public:
|
||||
explicit UIAProviderBase (AccessibilityNativeHandle* nativeHandleIn)
|
||||
: nativeHandle (nativeHandleIn, IncrementRef::yes)
|
||||
{
|
||||
}
|
||||
|
||||
bool isElementValid() const
|
||||
{
|
||||
if (nativeHandle != nullptr)
|
||||
return nativeHandle->isElementValid();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
const AccessibilityHandler& getHandler() const
|
||||
{
|
||||
return nativeHandle->getHandler();
|
||||
}
|
||||
|
||||
private:
|
||||
ComSmartPtr<AccessibilityNativeHandle> nativeHandle;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIAProviderBase)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
void sendAccessibilityAutomationEvent (const AccessibilityHandler&, EVENTID);
|
||||
void sendAccessibilityPropertyChangedEvent (const AccessibilityHandler&, PROPERTYID, VARIANT);
|
||||
} // namespace juce
|
||||
|
||||
#include "juce_UIAProviderBase_windows.h"
|
||||
#include "juce_UIAExpandCollapseProvider_windows.h"
|
||||
#include "juce_UIAGridItemProvider_windows.h"
|
||||
#include "juce_UIAGridProvider_windows.h"
|
||||
#include "juce_UIAInvokeProvider_windows.h"
|
||||
#include "juce_UIARangeValueProvider_windows.h"
|
||||
#include "juce_UIASelectionProvider_windows.h"
|
||||
#include "juce_UIATextProvider_windows.h"
|
||||
#include "juce_UIAToggleProvider_windows.h"
|
||||
#include "juce_UIATransformProvider_windows.h"
|
||||
#include "juce_UIAValueProvider_windows.h"
|
||||
#include "juce_UIAWindowProvider_windows.h"
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class UIARangeValueProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<IRangeValueProvider>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT SetValue (double val) override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
const auto& handler = getHandler();
|
||||
|
||||
if (auto* valueInterface = handler.getValueInterface())
|
||||
{
|
||||
auto range = valueInterface->getRange();
|
||||
|
||||
if (range.isValid())
|
||||
{
|
||||
if (val < range.getMinimumValue() || val > range.getMaximumValue())
|
||||
return E_INVALIDARG;
|
||||
|
||||
if (! valueInterface->isReadOnly())
|
||||
{
|
||||
valueInterface->setValue (val);
|
||||
|
||||
VARIANT newValue;
|
||||
VariantHelpers::setDouble (valueInterface->getCurrentValue(), &newValue);
|
||||
sendAccessibilityPropertyChangedEvent (handler, UIA_RangeValueValuePropertyId, newValue);
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_Value (double* pRetVal) override
|
||||
{
|
||||
return withValueInterface (pRetVal, [] (const AccessibilityValueInterface& valueInterface)
|
||||
{
|
||||
return valueInterface.getCurrentValue();
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_IsReadOnly (BOOL* pRetVal) override
|
||||
{
|
||||
return withValueInterface (pRetVal, [] (const AccessibilityValueInterface& valueInterface)
|
||||
{
|
||||
return valueInterface.isReadOnly();
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_Maximum (double* pRetVal) override
|
||||
{
|
||||
return withValueInterface (pRetVal, [] (const AccessibilityValueInterface& valueInterface)
|
||||
{
|
||||
return valueInterface.getRange().getMaximumValue();
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_Minimum (double* pRetVal) override
|
||||
{
|
||||
return withValueInterface (pRetVal, [] (const AccessibilityValueInterface& valueInterface)
|
||||
{
|
||||
return valueInterface.getRange().getMinimumValue();
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_LargeChange (double* pRetVal) override
|
||||
{
|
||||
return get_SmallChange (pRetVal);
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_SmallChange (double* pRetVal) override
|
||||
{
|
||||
return withValueInterface (pRetVal, [] (const AccessibilityValueInterface& valueInterface)
|
||||
{
|
||||
return valueInterface.getRange().getInterval();
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename Value, typename Callback>
|
||||
JUCE_COMRESULT withValueInterface (Value* pRetVal, Callback&& callback) const
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]() -> HRESULT
|
||||
{
|
||||
if (auto* valueInterface = getHandler().getValueInterface())
|
||||
{
|
||||
if (valueInterface->getRange().isValid())
|
||||
{
|
||||
*pRetVal = callback (*valueInterface);
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
});
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIARangeValueProvider)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
|
||||
//==============================================================================
|
||||
class UIASelectionItemProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<ISelectionItemProvider>
|
||||
{
|
||||
public:
|
||||
explicit UIASelectionItemProvider (AccessibilityNativeHandle* handle)
|
||||
: UIAProviderBase (handle),
|
||||
isRadioButton (getHandler().getRole() == AccessibilityRole::radioButton)
|
||||
{
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT AddToSelection() override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
const auto& handler = getHandler();
|
||||
|
||||
if (isRadioButton)
|
||||
{
|
||||
handler.getActions().invoke (AccessibilityActionType::press);
|
||||
sendAccessibilityAutomationEvent (handler, UIA_SelectionItem_ElementSelectedEventId);
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
handler.getActions().invoke (AccessibilityActionType::toggle);
|
||||
handler.getActions().invoke (AccessibilityActionType::press);
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_IsSelected (BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
const auto state = getHandler().getCurrentState();
|
||||
*pRetVal = isRadioButton ? state.isChecked() : state.isSelected();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_SelectionContainer (IRawElementProviderSimple** pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
if (! isRadioButton)
|
||||
if (auto* parent = getHandler().getParent())
|
||||
parent->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (pRetVal));
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT RemoveFromSelection() override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
if (! isRadioButton)
|
||||
{
|
||||
const auto& handler = getHandler();
|
||||
|
||||
if (handler.getCurrentState().isSelected())
|
||||
getHandler().getActions().invoke (AccessibilityActionType::toggle);
|
||||
}
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT Select() override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
AddToSelection();
|
||||
|
||||
if (isElementValid() && ! isRadioButton)
|
||||
{
|
||||
const auto& handler = getHandler();
|
||||
|
||||
if (auto* parent = handler.getParent())
|
||||
for (auto* child : parent->getChildren())
|
||||
if (child != &handler && child->getCurrentState().isSelected())
|
||||
child->getActions().invoke (AccessibilityActionType::toggle);
|
||||
}
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
private:
|
||||
const bool isRadioButton;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIASelectionItemProvider)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class UIASelectionProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<ISelectionProvider2>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT QueryInterface (REFIID iid, void** result) override
|
||||
{
|
||||
if (iid == __uuidof (IUnknown) || iid == __uuidof (ISelectionProvider))
|
||||
return castToType<ISelectionProvider> (result);
|
||||
|
||||
if (iid == __uuidof (ISelectionProvider2))
|
||||
return castToType<ISelectionProvider2> (result);
|
||||
|
||||
*result = nullptr;
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT get_CanSelectMultiple (BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
*pRetVal = isMultiSelectable();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_IsSelectionRequired (BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
*pRetVal = getSelectedChildren().size() > 0 && ! isMultiSelectable();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetSelection (SAFEARRAY** pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
return addHandlersToArray (getSelectedChildren(), pRetVal);
|
||||
});
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT get_FirstSelectedItem (IRawElementProviderSimple** pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
auto selectedChildren = getSelectedChildren();
|
||||
|
||||
if (! selectedChildren.empty())
|
||||
selectedChildren.front()->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (pRetVal));
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_LastSelectedItem (IRawElementProviderSimple** pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
auto selectedChildren = getSelectedChildren();
|
||||
|
||||
if (! selectedChildren.empty())
|
||||
selectedChildren.back()->getNativeImplementation()->QueryInterface (IID_PPV_ARGS (pRetVal));
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_CurrentSelectedItem (IRawElementProviderSimple** pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
get_FirstSelectedItem (pRetVal);
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_ItemCount (int* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
*pRetVal = (int) getSelectedChildren().size();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
bool isMultiSelectable() const noexcept
|
||||
{
|
||||
return getHandler().getCurrentState().isMultiSelectable();
|
||||
}
|
||||
|
||||
std::vector<const AccessibilityHandler*> getSelectedChildren() const
|
||||
{
|
||||
std::vector<const AccessibilityHandler*> selectedHandlers;
|
||||
|
||||
for (auto* child : getHandler().getComponent().getChildren())
|
||||
if (auto* handler = child->getAccessibilityHandler())
|
||||
if (handler->getCurrentState().isSelected())
|
||||
selectedHandlers.push_back (handler);
|
||||
|
||||
return selectedHandlers;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIASelectionProvider)
|
||||
};
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,620 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class UIATextProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<ITextProvider2>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT QueryInterface (REFIID iid, void** result) override
|
||||
{
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
|
||||
if (iid == __uuidof (IUnknown) || iid == __uuidof (ITextProvider))
|
||||
return castToType<ITextProvider> (result);
|
||||
|
||||
if (iid == __uuidof (ITextProvider2))
|
||||
return castToType<ITextProvider2> (result);
|
||||
|
||||
*result = nullptr;
|
||||
return E_NOINTERFACE;
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT get_DocumentRange (ITextRangeProvider** pRetVal) override
|
||||
{
|
||||
return withTextInterface (pRetVal, [&] (const AccessibilityTextInterface& textInterface)
|
||||
{
|
||||
*pRetVal = new UIATextRangeProvider (*this, { 0, textInterface.getTotalNumCharacters() });
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_SupportedTextSelection (SupportedTextSelection* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
*pRetVal = SupportedTextSelection_Single;
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetSelection (SAFEARRAY** pRetVal) override
|
||||
{
|
||||
return withTextInterface (pRetVal, [&] (const AccessibilityTextInterface& textInterface)
|
||||
{
|
||||
SafeArrayHandle result { SafeArrayCreateVector (VT_UNKNOWN, 0, 1) };
|
||||
|
||||
if (result == nullptr)
|
||||
return E_FAIL;
|
||||
|
||||
auto selection = textInterface.getSelection();
|
||||
auto hasSelection = ! selection.isEmpty();
|
||||
auto cursorPos = textInterface.getTextInsertionOffset();
|
||||
|
||||
ComSmartPtr rangeProvider { new UIATextRangeProvider (*this,
|
||||
{ hasSelection ? selection.getStart() : cursorPos,
|
||||
hasSelection ? selection.getEnd() : cursorPos }),
|
||||
IncrementRef::no };
|
||||
|
||||
if (LONG pos = 0; FAILED (SafeArrayPutElement (result.get(), &pos, static_cast<IUnknown*> (rangeProvider))))
|
||||
return E_FAIL;
|
||||
|
||||
*pRetVal = result.release();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetVisibleRanges (SAFEARRAY** pRetVal) override
|
||||
{
|
||||
return withTextInterface (pRetVal, [&] (const AccessibilityTextInterface& textInterface)
|
||||
{
|
||||
SafeArrayHandle result { SafeArrayCreateVector (VT_UNKNOWN, 0, 1) };
|
||||
|
||||
if (result == nullptr)
|
||||
return E_FAIL;
|
||||
|
||||
ComSmartPtr rangeProvider { new UIATextRangeProvider (*this, { 0, textInterface.getTotalNumCharacters() }),
|
||||
IncrementRef::no };
|
||||
|
||||
if (LONG pos = 0; FAILED (SafeArrayPutElement (result.get(), &pos, static_cast<IUnknown*> (rangeProvider))))
|
||||
return E_FAIL;
|
||||
|
||||
*pRetVal = result.release();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT RangeFromChild (IRawElementProviderSimple*, ITextRangeProvider** pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, []
|
||||
{
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT RangeFromPoint (UiaPoint point, ITextRangeProvider** pRetVal) override
|
||||
{
|
||||
return withTextInterface (pRetVal, [&] (const AccessibilityTextInterface& textInterface)
|
||||
{
|
||||
auto offset = textInterface.getOffsetAtPoint ({ roundToInt (point.x), roundToInt (point.y) });
|
||||
|
||||
if (offset > 0)
|
||||
*pRetVal = new UIATextRangeProvider (*this, { offset, offset });
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT GetCaretRange (BOOL* isActive, ITextRangeProvider** pRetVal) override
|
||||
{
|
||||
return withTextInterface (pRetVal, [&] (const AccessibilityTextInterface& textInterface)
|
||||
{
|
||||
*isActive = getHandler().hasFocus (false);
|
||||
|
||||
auto cursorPos = textInterface.getTextInsertionOffset();
|
||||
*pRetVal = new UIATextRangeProvider (*this, { cursorPos, cursorPos });
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT RangeFromAnnotation (IRawElementProviderSimple*, ITextRangeProvider** pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, []
|
||||
{
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
template <typename Value, typename Callback>
|
||||
JUCE_COMRESULT withTextInterface (Value* pRetVal, Callback&& callback) const
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]() -> HRESULT
|
||||
{
|
||||
if (auto* textInterface = getHandler().getTextInterface())
|
||||
return callback (*textInterface);
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
});
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
class UIATextRangeProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<ITextRangeProvider>
|
||||
{
|
||||
public:
|
||||
UIATextRangeProvider (UIATextProvider& textProvider, Range<int> range)
|
||||
: UIAProviderBase (textProvider.getHandler().getNativeImplementation()),
|
||||
owner (&textProvider, IncrementRef::yes),
|
||||
selectionRange (range)
|
||||
{
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
Range<int> getSelectionRange() const noexcept { return selectionRange; }
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT AddToSelection() override
|
||||
{
|
||||
return Select();
|
||||
}
|
||||
|
||||
JUCE_COMRESULT Clone (ITextRangeProvider** pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
*pRetVal = new UIATextRangeProvider (*owner, selectionRange);
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT Compare (ITextRangeProvider* range, BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
*pRetVal = (selectionRange == static_cast<UIATextRangeProvider*> (range)->getSelectionRange());
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT CompareEndpoints (TextPatternRangeEndpoint endpoint,
|
||||
ITextRangeProvider* targetRange,
|
||||
TextPatternRangeEndpoint targetEndpoint,
|
||||
int* pRetVal) override
|
||||
{
|
||||
if (targetRange == nullptr)
|
||||
return E_INVALIDARG;
|
||||
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
auto offset = (endpoint == TextPatternRangeEndpoint_Start ? selectionRange.getStart()
|
||||
: selectionRange.getEnd());
|
||||
|
||||
auto otherRange = static_cast<UIATextRangeProvider*> (targetRange)->getSelectionRange();
|
||||
auto otherOffset = (targetEndpoint == TextPatternRangeEndpoint_Start ? otherRange.getStart()
|
||||
: otherRange.getEnd());
|
||||
|
||||
*pRetVal = offset - otherOffset;
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT ExpandToEnclosingUnit (TextUnit unit) override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
if (auto* textInterface = owner->getHandler().getTextInterface())
|
||||
{
|
||||
using ATH = AccessibilityTextHelpers;
|
||||
|
||||
const auto boundaryType = getBoundaryType (unit);
|
||||
const auto start = ATH::findTextBoundary (*textInterface,
|
||||
selectionRange.getStart(),
|
||||
boundaryType,
|
||||
ATH::Direction::backwards,
|
||||
ATH::IncludeThisBoundary::yes,
|
||||
ATH::IncludeWhitespaceAfterWords::no);
|
||||
|
||||
const auto end = ATH::findTextBoundary (*textInterface,
|
||||
start,
|
||||
boundaryType,
|
||||
ATH::Direction::forwards,
|
||||
ATH::IncludeThisBoundary::no,
|
||||
ATH::IncludeWhitespaceAfterWords::yes);
|
||||
|
||||
selectionRange = Range<int> (start, end);
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT FindAttribute (TEXTATTRIBUTEID, VARIANT, BOOL, ITextRangeProvider** pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, []
|
||||
{
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT FindText (BSTR text, BOOL backward, BOOL ignoreCase,
|
||||
ITextRangeProvider** pRetVal) override
|
||||
{
|
||||
return owner->withTextInterface (pRetVal, [&] (const AccessibilityTextInterface& textInterface)
|
||||
{
|
||||
auto selectionText = textInterface.getText (selectionRange);
|
||||
String textToSearchFor (text);
|
||||
|
||||
auto offset = (backward ? (ignoreCase ? selectionText.lastIndexOfIgnoreCase (textToSearchFor) : selectionText.lastIndexOf (textToSearchFor))
|
||||
: (ignoreCase ? selectionText.indexOfIgnoreCase (textToSearchFor) : selectionText.indexOf (textToSearchFor)));
|
||||
|
||||
if (offset != -1)
|
||||
*pRetVal = new UIATextRangeProvider (*owner, { offset, offset + textToSearchFor.length() });
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetAttributeValue (TEXTATTRIBUTEID attributeId, VARIANT* pRetVal) override
|
||||
{
|
||||
return owner->withTextInterface (pRetVal, [&] (const AccessibilityTextInterface& textInterface)
|
||||
{
|
||||
VariantHelpers::clear (pRetVal);
|
||||
|
||||
switch (attributeId)
|
||||
{
|
||||
case UIA_IsReadOnlyAttributeId:
|
||||
{
|
||||
VariantHelpers::setBool (textInterface.isReadOnly(), pRetVal);
|
||||
break;
|
||||
}
|
||||
|
||||
case UIA_CaretPositionAttributeId:
|
||||
{
|
||||
auto cursorPos = textInterface.getTextInsertionOffset();
|
||||
|
||||
auto caretPos = [&]
|
||||
{
|
||||
if (cursorPos == 0)
|
||||
return CaretPosition_BeginningOfLine;
|
||||
|
||||
if (cursorPos == textInterface.getTotalNumCharacters())
|
||||
return CaretPosition_EndOfLine;
|
||||
|
||||
return CaretPosition_Unknown;
|
||||
}();
|
||||
|
||||
VariantHelpers::setInt (caretPos, pRetVal);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetBoundingRectangles (SAFEARRAY** pRetVal) override
|
||||
{
|
||||
return owner->withTextInterface (pRetVal, [&] (const AccessibilityTextInterface& textInterface)
|
||||
{
|
||||
auto rectangleList = textInterface.getTextBounds (selectionRange);
|
||||
auto numRectangles = rectangleList.getNumRectangles();
|
||||
|
||||
SafeArrayHandle result { SafeArrayCreateVector (VT_R8, 0, 4 * (ULONG) numRectangles) };
|
||||
|
||||
if (result == nullptr)
|
||||
return E_FAIL;
|
||||
|
||||
if (numRectangles > 0)
|
||||
{
|
||||
double* doubleArr = nullptr;
|
||||
|
||||
if (FAILED (SafeArrayAccessData (result.get(), reinterpret_cast<void**> (&doubleArr))))
|
||||
return E_FAIL;
|
||||
|
||||
for (int i = 0; i < numRectangles; ++i)
|
||||
{
|
||||
auto r = Desktop::getInstance().getDisplays().logicalToPhysical (rectangleList.getRectangle (i));
|
||||
|
||||
doubleArr[i * 4] = r.getX();
|
||||
doubleArr[i * 4 + 1] = r.getY();
|
||||
doubleArr[i * 4 + 2] = r.getWidth();
|
||||
doubleArr[i * 4 + 3] = r.getHeight();
|
||||
}
|
||||
|
||||
if (FAILED (SafeArrayUnaccessData (result.get())))
|
||||
return E_FAIL;
|
||||
}
|
||||
|
||||
*pRetVal = result.release();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetChildren (SAFEARRAY** pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
SafeArrayHandle result { SafeArrayCreateVector (VT_UNKNOWN, 0, 0) };
|
||||
|
||||
if (result == nullptr)
|
||||
return E_FAIL;
|
||||
|
||||
*pRetVal = result.release();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetEnclosingElement (IRawElementProviderSimple** pRetVal) override
|
||||
{
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
getHandler().getNativeImplementation()->QueryInterface (IID_PPV_ARGS (pRetVal));
|
||||
return S_OK;
|
||||
});
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetText (int maxLength, BSTR* pRetVal) override
|
||||
{
|
||||
return owner->withTextInterface (pRetVal, [&] (const AccessibilityTextInterface& textInterface)
|
||||
{
|
||||
auto text = textInterface.getText (selectionRange);
|
||||
|
||||
if (maxLength >= 0 && text.length() > maxLength)
|
||||
text = text.substring (0, maxLength);
|
||||
|
||||
*pRetVal = SysAllocString ((const OLECHAR*) text.toWideCharPointer());
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT Move (TextUnit unit, int count, int* pRetVal) override
|
||||
{
|
||||
return owner->withTextInterface (pRetVal, [&] (const AccessibilityTextInterface& textInterface)
|
||||
{
|
||||
using ATH = AccessibilityTextHelpers;
|
||||
|
||||
const auto boundaryType = getBoundaryType (unit);
|
||||
const auto previousUnitBoundary = ATH::findTextBoundary (textInterface,
|
||||
selectionRange.getStart(),
|
||||
boundaryType,
|
||||
ATH::Direction::backwards,
|
||||
ATH::IncludeThisBoundary::yes,
|
||||
ATH::IncludeWhitespaceAfterWords::no);
|
||||
|
||||
auto numMoved = 0;
|
||||
auto movedEndpoint = previousUnitBoundary;
|
||||
|
||||
for (; numMoved < std::abs (count); ++numMoved)
|
||||
{
|
||||
const auto nextEndpoint = ATH::findTextBoundary (textInterface,
|
||||
movedEndpoint,
|
||||
boundaryType,
|
||||
count > 0 ? ATH::Direction::forwards : ATH::Direction::backwards,
|
||||
ATH::IncludeThisBoundary::no,
|
||||
count > 0 ? ATH::IncludeWhitespaceAfterWords::yes : ATH::IncludeWhitespaceAfterWords::no);
|
||||
|
||||
if (nextEndpoint == movedEndpoint)
|
||||
break;
|
||||
|
||||
movedEndpoint = nextEndpoint;
|
||||
}
|
||||
|
||||
*pRetVal = numMoved;
|
||||
|
||||
ExpandToEnclosingUnit (unit);
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT MoveEndpointByRange (TextPatternRangeEndpoint endpoint,
|
||||
ITextRangeProvider* targetRange,
|
||||
TextPatternRangeEndpoint targetEndpoint) override
|
||||
{
|
||||
if (targetRange == nullptr)
|
||||
return E_INVALIDARG;
|
||||
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
if (owner->getHandler().getTextInterface() != nullptr)
|
||||
{
|
||||
auto otherRange = static_cast<UIATextRangeProvider*> (targetRange)->getSelectionRange();
|
||||
auto targetPoint = (targetEndpoint == TextPatternRangeEndpoint_Start ? otherRange.getStart()
|
||||
: otherRange.getEnd());
|
||||
|
||||
setEndpointChecked (endpoint, targetPoint);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT MoveEndpointByUnit (TextPatternRangeEndpoint endpoint,
|
||||
TextUnit unit,
|
||||
int count,
|
||||
int* pRetVal) override
|
||||
{
|
||||
return owner->withTextInterface (pRetVal, [&] (const AccessibilityTextInterface& textInterface)
|
||||
{
|
||||
if (count == 0 || textInterface.getTotalNumCharacters() == 0)
|
||||
return S_OK;
|
||||
|
||||
const auto endpointToMove = (endpoint == TextPatternRangeEndpoint_Start ? selectionRange.getStart()
|
||||
: selectionRange.getEnd());
|
||||
|
||||
using ATH = AccessibilityTextHelpers;
|
||||
|
||||
const auto direction = (count > 0 ? ATH::Direction::forwards
|
||||
: ATH::Direction::backwards);
|
||||
|
||||
const auto boundaryType = getBoundaryType (unit);
|
||||
auto movedEndpoint = endpointToMove;
|
||||
|
||||
int numMoved = 0;
|
||||
for (; numMoved < std::abs (count); ++numMoved)
|
||||
{
|
||||
auto nextEndpoint = ATH::findTextBoundary (textInterface,
|
||||
movedEndpoint,
|
||||
boundaryType,
|
||||
direction,
|
||||
ATH::IncludeThisBoundary::no,
|
||||
direction == ATH::Direction::forwards ? ATH::IncludeWhitespaceAfterWords::yes
|
||||
: ATH::IncludeWhitespaceAfterWords::no);
|
||||
|
||||
if (nextEndpoint == movedEndpoint)
|
||||
break;
|
||||
|
||||
movedEndpoint = nextEndpoint;
|
||||
}
|
||||
|
||||
*pRetVal = numMoved;
|
||||
|
||||
setEndpointChecked (endpoint, movedEndpoint);
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT RemoveFromSelection() override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
if (auto* textInterface = owner->getHandler().getTextInterface())
|
||||
{
|
||||
textInterface->setSelection ({});
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT ScrollIntoView (BOOL) override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT Select() override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
if (auto* textInterface = owner->getHandler().getTextInterface())
|
||||
{
|
||||
textInterface->setSelection ({});
|
||||
textInterface->setSelection (selectionRange);
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
private:
|
||||
static AccessibilityTextHelpers::BoundaryType getBoundaryType (TextUnit unit)
|
||||
{
|
||||
switch (unit)
|
||||
{
|
||||
case TextUnit_Character:
|
||||
return AccessibilityTextHelpers::BoundaryType::character;
|
||||
|
||||
case TextUnit_Format:
|
||||
case TextUnit_Word:
|
||||
return AccessibilityTextHelpers::BoundaryType::word;
|
||||
|
||||
case TextUnit_Line:
|
||||
return AccessibilityTextHelpers::BoundaryType::line;
|
||||
|
||||
case TextUnit_Paragraph:
|
||||
case TextUnit_Page:
|
||||
case TextUnit_Document:
|
||||
return AccessibilityTextHelpers::BoundaryType::document;
|
||||
};
|
||||
|
||||
jassertfalse;
|
||||
return AccessibilityTextHelpers::BoundaryType::character;
|
||||
}
|
||||
|
||||
void setEndpointChecked (TextPatternRangeEndpoint endpoint, int newEndpoint)
|
||||
{
|
||||
if (endpoint == TextPatternRangeEndpoint_Start)
|
||||
{
|
||||
if (selectionRange.getEnd() < newEndpoint)
|
||||
selectionRange.setEnd (newEndpoint);
|
||||
|
||||
selectionRange.setStart (newEndpoint);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (selectionRange.getStart() > newEndpoint)
|
||||
selectionRange.setStart (newEndpoint);
|
||||
|
||||
selectionRange.setEnd (newEndpoint);
|
||||
}
|
||||
}
|
||||
|
||||
ComSmartPtr<UIATextProvider> owner;
|
||||
Range<int> selectionRange;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIATextRangeProvider)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIATextProvider)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class UIAToggleProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<IToggleProvider>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT Toggle() override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
const auto& handler = getHandler();
|
||||
|
||||
if (handler.getActions().invoke (AccessibilityActionType::toggle)
|
||||
|| handler.getActions().invoke (AccessibilityActionType::press))
|
||||
{
|
||||
VARIANT newValue;
|
||||
VariantHelpers::setInt (getCurrentToggleState(), &newValue);
|
||||
|
||||
sendAccessibilityPropertyChangedEvent (handler, UIA_ToggleToggleStatePropertyId, newValue);
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_ToggleState (ToggleState* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
*pRetVal = getCurrentToggleState();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
ToggleState getCurrentToggleState() const
|
||||
{
|
||||
return getHandler().getCurrentState().isChecked() ? ToggleState_On
|
||||
: ToggleState_Off;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIAToggleProvider)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class UIATransformProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<ITransformProvider>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT Move (double x, double y) override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
if (auto* peer = getPeer())
|
||||
{
|
||||
RECT rect;
|
||||
GetWindowRect ((HWND) peer->getNativeHandle(), &rect);
|
||||
|
||||
rect.left = roundToInt (x);
|
||||
rect.top = roundToInt (y);
|
||||
|
||||
auto bounds = Rectangle<int>::leftTopRightBottom (rect.left, rect.top, rect.right, rect.bottom);
|
||||
|
||||
peer->setBounds (Desktop::getInstance().getDisplays().physicalToLogical (bounds),
|
||||
peer->isFullScreen());
|
||||
}
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT Resize (double width, double height) override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
if (auto* peer = getPeer())
|
||||
{
|
||||
auto scale = peer->getPlatformScaleFactor();
|
||||
|
||||
peer->getComponent().setSize (roundToInt (width / scale),
|
||||
roundToInt (height / scale));
|
||||
}
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT Rotate (double) override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_CanMove (BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
*pRetVal = true;
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_CanResize (BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
if (auto* peer = getPeer())
|
||||
*pRetVal = ((peer->getStyleFlags() & ComponentPeer::windowIsResizable) != 0);
|
||||
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_CanRotate (BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
*pRetVal = false;
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
ComponentPeer* getPeer() const
|
||||
{
|
||||
return getHandler().getComponent().getPeer();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIATransformProvider)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class UIAValueProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<IValueProvider>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT SetValue (LPCWSTR val) override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
const auto& handler = getHandler();
|
||||
auto& valueInterface = *handler.getValueInterface();
|
||||
|
||||
if (valueInterface.isReadOnly())
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
|
||||
valueInterface.setValueAsString (String (val));
|
||||
|
||||
VARIANT newValue;
|
||||
VariantHelpers::setString (valueInterface.getCurrentValueAsString(), &newValue);
|
||||
|
||||
sendAccessibilityPropertyChangedEvent (handler, UIA_ValueValuePropertyId, newValue);
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_Value (BSTR* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
auto currentValueString = getHandler().getValueInterface()->getCurrentValueAsString();
|
||||
|
||||
*pRetVal = SysAllocString ((const OLECHAR*) currentValueString.toWideCharPointer());
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_IsReadOnly (BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]
|
||||
{
|
||||
*pRetVal = getHandler().getValueInterface()->isReadOnly();
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIAValueProvider)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,203 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class UIAWindowProvider : public UIAProviderBase,
|
||||
public ComBaseClassHelper<IWindowProvider>
|
||||
{
|
||||
public:
|
||||
using UIAProviderBase::UIAProviderBase;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_COMRESULT SetVisualState (WindowVisualState state) override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
if (auto* peer = getPeer())
|
||||
{
|
||||
switch (state)
|
||||
{
|
||||
case WindowVisualState_Maximized:
|
||||
peer->setFullScreen (true);
|
||||
break;
|
||||
|
||||
case WindowVisualState_Minimized:
|
||||
peer->setMinimised (true);
|
||||
break;
|
||||
|
||||
case WindowVisualState_Normal:
|
||||
peer->setFullScreen (false);
|
||||
peer->setMinimised (false);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT Close() override
|
||||
{
|
||||
if (! isElementValid())
|
||||
return (HRESULT) UIA_E_ELEMENTNOTAVAILABLE;
|
||||
|
||||
if (auto* peer = getPeer())
|
||||
{
|
||||
peer->handleUserClosingWindow();
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT WaitForInputIdle (int, BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, []
|
||||
{
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_CanMaximize (BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]() -> HRESULT
|
||||
{
|
||||
if (auto* peer = getPeer())
|
||||
{
|
||||
*pRetVal = (peer->getStyleFlags() & ComponentPeer::windowHasMaximiseButton) != 0;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_CanMinimize (BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]() -> HRESULT
|
||||
{
|
||||
if (auto* peer = getPeer())
|
||||
{
|
||||
*pRetVal = (peer->getStyleFlags() & ComponentPeer::windowHasMinimiseButton) != 0;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_IsModal (BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]() -> HRESULT
|
||||
{
|
||||
if (auto* peer = getPeer())
|
||||
{
|
||||
*pRetVal = peer->getComponent().isCurrentlyModal();
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_WindowVisualState (WindowVisualState* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]() -> HRESULT
|
||||
{
|
||||
if (auto* peer = getPeer())
|
||||
{
|
||||
if (peer->isFullScreen())
|
||||
*pRetVal = WindowVisualState_Maximized;
|
||||
else if (peer->isMinimised())
|
||||
*pRetVal = WindowVisualState_Minimized;
|
||||
else
|
||||
*pRetVal = WindowVisualState_Normal;
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_WindowInteractionState (WindowInteractionState* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]() -> HRESULT
|
||||
{
|
||||
if (auto* peer = getPeer())
|
||||
{
|
||||
*pRetVal = peer->getComponent().isCurrentlyBlockedByAnotherModalComponent()
|
||||
? WindowInteractionState::WindowInteractionState_BlockedByModalWindow
|
||||
: WindowInteractionState::WindowInteractionState_Running;
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
});
|
||||
}
|
||||
|
||||
JUCE_COMRESULT get_IsTopmost (BOOL* pRetVal) override
|
||||
{
|
||||
return withCheckedComArgs (pRetVal, *this, [&]() -> HRESULT
|
||||
{
|
||||
if (auto* peer = getPeer())
|
||||
{
|
||||
*pRetVal = peer->isFocused();
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
ComponentPeer* getPeer() const
|
||||
{
|
||||
return getHandler().getComponent().getPeer();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIAWindowProvider)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class WindowsUIAWrapper : public DeletedAtShutdown
|
||||
{
|
||||
public:
|
||||
bool isLoaded() const noexcept
|
||||
{
|
||||
return uiaReturnRawElementProvider != nullptr
|
||||
&& uiaHostProviderFromHwnd != nullptr
|
||||
&& uiaRaiseAutomationPropertyChangedEvent != nullptr
|
||||
&& uiaRaiseAutomationEvent != nullptr
|
||||
&& uiaClientsAreListening != nullptr
|
||||
&& uiaDisconnectProvider != nullptr
|
||||
&& uiaDisconnectAllProviders != nullptr;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
LRESULT returnRawElementProvider (HWND hwnd, WPARAM wParam, LPARAM lParam, IRawElementProviderSimple* provider)
|
||||
{
|
||||
return uiaReturnRawElementProvider != nullptr ? uiaReturnRawElementProvider (hwnd, wParam, lParam, provider)
|
||||
: (LRESULT) nullptr;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT hostProviderFromHwnd (HWND hwnd, IRawElementProviderSimple** provider)
|
||||
{
|
||||
return uiaHostProviderFromHwnd != nullptr ? uiaHostProviderFromHwnd (hwnd, provider)
|
||||
: (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT raiseAutomationPropertyChangedEvent (IRawElementProviderSimple* provider, PROPERTYID propID, VARIANT oldValue, VARIANT newValue)
|
||||
{
|
||||
return uiaRaiseAutomationPropertyChangedEvent != nullptr ? uiaRaiseAutomationPropertyChangedEvent (provider, propID, oldValue, newValue)
|
||||
: (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT raiseAutomationEvent (IRawElementProviderSimple* provider, EVENTID eventID)
|
||||
{
|
||||
return uiaRaiseAutomationEvent != nullptr ? uiaRaiseAutomationEvent (provider, eventID)
|
||||
: (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
BOOL clientsAreListening()
|
||||
{
|
||||
return uiaClientsAreListening != nullptr ? uiaClientsAreListening()
|
||||
: false;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT disconnectProvider (IRawElementProviderSimple* provider)
|
||||
{
|
||||
if (uiaDisconnectProvider != nullptr)
|
||||
{
|
||||
const ScopedValueSetter<IRawElementProviderSimple*> disconnectingProviderSetter (disconnectingProvider, provider);
|
||||
return uiaDisconnectProvider (provider);
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT disconnectAllProviders()
|
||||
{
|
||||
if (! JUCEApplicationBase::isStandaloneApp())
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
|
||||
if (uiaDisconnectAllProviders != nullptr)
|
||||
{
|
||||
const ScopedValueSetter<bool> disconnectingAllProvidersSetter (disconnectingAllProviders, true);
|
||||
return uiaDisconnectAllProviders();
|
||||
}
|
||||
|
||||
return (HRESULT) UIA_E_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
bool isProviderDisconnecting (IRawElementProviderSimple* provider)
|
||||
{
|
||||
return disconnectingProvider == provider || disconnectingAllProviders;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_SINGLETON_SINGLETHREADED_MINIMAL_INLINE (WindowsUIAWrapper)
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
WindowsUIAWrapper()
|
||||
{
|
||||
// force UIA COM library initialisation here to prevent an exception when calling methods from SendMessage()
|
||||
if (isLoaded())
|
||||
returnRawElementProvider (nullptr, 0, 0, nullptr);
|
||||
else
|
||||
jassertfalse; // UIAutomationCore could not be loaded!
|
||||
}
|
||||
|
||||
~WindowsUIAWrapper()
|
||||
{
|
||||
disconnectAllProviders();
|
||||
|
||||
if (uiaHandle != nullptr)
|
||||
::FreeLibrary (uiaHandle);
|
||||
|
||||
clearSingletonInstance();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
template <typename FuncType>
|
||||
static FuncType getUiaFunction (HMODULE module, LPCSTR funcName)
|
||||
{
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wcast-function-type")
|
||||
return (FuncType) GetProcAddress (module, funcName);
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
using UiaReturnRawElementProviderFunc = LRESULT (WINAPI*) (HWND, WPARAM, LPARAM, IRawElementProviderSimple*);
|
||||
using UiaHostProviderFromHwndFunc = HRESULT (WINAPI*) (HWND, IRawElementProviderSimple**);
|
||||
using UiaRaiseAutomationPropertyChangedEventFunc = HRESULT (WINAPI*) (IRawElementProviderSimple*, PROPERTYID, VARIANT, VARIANT);
|
||||
using UiaRaiseAutomationEventFunc = HRESULT (WINAPI*) (IRawElementProviderSimple*, EVENTID);
|
||||
using UiaClientsAreListeningFunc = BOOL (WINAPI*) ();
|
||||
using UiaDisconnectProviderFunc = HRESULT (WINAPI*) (IRawElementProviderSimple*);
|
||||
using UiaDisconnectAllProvidersFunc = HRESULT (WINAPI*) ();
|
||||
|
||||
HMODULE uiaHandle = ::LoadLibraryA ("UIAutomationCore.dll");
|
||||
UiaReturnRawElementProviderFunc uiaReturnRawElementProvider = getUiaFunction<UiaReturnRawElementProviderFunc> (uiaHandle, "UiaReturnRawElementProvider");
|
||||
UiaHostProviderFromHwndFunc uiaHostProviderFromHwnd = getUiaFunction<UiaHostProviderFromHwndFunc> (uiaHandle, "UiaHostProviderFromHwnd");
|
||||
UiaRaiseAutomationPropertyChangedEventFunc uiaRaiseAutomationPropertyChangedEvent = getUiaFunction<UiaRaiseAutomationPropertyChangedEventFunc> (uiaHandle, "UiaRaiseAutomationPropertyChangedEvent");
|
||||
UiaRaiseAutomationEventFunc uiaRaiseAutomationEvent = getUiaFunction<UiaRaiseAutomationEventFunc> (uiaHandle, "UiaRaiseAutomationEvent");
|
||||
UiaClientsAreListeningFunc uiaClientsAreListening = getUiaFunction<UiaClientsAreListeningFunc> (uiaHandle, "UiaClientsAreListening");
|
||||
UiaDisconnectProviderFunc uiaDisconnectProvider = getUiaFunction<UiaDisconnectProviderFunc> (uiaHandle, "UiaDisconnectProvider");
|
||||
UiaDisconnectAllProvidersFunc uiaDisconnectAllProviders = getUiaFunction<UiaDisconnectAllProvidersFunc> (uiaHandle, "UiaDisconnectAllProviders");
|
||||
|
||||
IRawElementProviderSimple* disconnectingProvider = nullptr;
|
||||
bool disconnectingAllProviders = false;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsUIAWrapper)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large.
Load diff
+62
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
package com.rmsl.juce;
|
||||
|
||||
import android.database.Cursor;
|
||||
import android.database.MatrixCursor;
|
||||
|
||||
import java.lang.String;
|
||||
|
||||
public final class JuceContentProviderCursor extends MatrixCursor
|
||||
{
|
||||
public JuceContentProviderCursor (long hostToUse, String[] columnNames)
|
||||
{
|
||||
super (columnNames);
|
||||
|
||||
host = hostToUse;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close ()
|
||||
{
|
||||
super.close ();
|
||||
|
||||
contentSharerCursorClosed (host);
|
||||
}
|
||||
|
||||
private native void contentSharerCursorClosed (long host);
|
||||
|
||||
private long host;
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
package com.rmsl.juce;
|
||||
|
||||
import android.os.FileObserver;
|
||||
|
||||
import java.lang.String;
|
||||
|
||||
public final class JuceContentProviderFileObserver extends FileObserver
|
||||
{
|
||||
public JuceContentProviderFileObserver (long hostToUse, String path, int mask)
|
||||
{
|
||||
super (path, mask);
|
||||
host = hostToUse;
|
||||
}
|
||||
|
||||
public void onEvent (int event, String path)
|
||||
{
|
||||
contentSharerFileObserverEvent (host, event, path);
|
||||
}
|
||||
|
||||
private long host;
|
||||
|
||||
private native void contentSharerFileObserverEvent (long host, int event, String path);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
package com.rmsl.juce;
|
||||
|
||||
import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
|
||||
import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
|
||||
import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.content.Intent;
|
||||
import android.view.View;
|
||||
|
||||
//==============================================================================
|
||||
public class JuceActivity extends Activity
|
||||
{
|
||||
private native void appNewIntent (Intent intent);
|
||||
private native void appOnResume();
|
||||
|
||||
@SuppressWarnings ("deprecation")
|
||||
private void initEdgeToEdge()
|
||||
{
|
||||
if (Build.VERSION.SDK_INT < 35)
|
||||
{
|
||||
View decorView = getWindow().getDecorView();
|
||||
|
||||
final int flags = Build.VERSION.SDK_INT < 30
|
||||
? ( SYSTEM_UI_FLAG_LAYOUT_STABLE
|
||||
| SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
|
||||
| SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
|
||||
: 0;
|
||||
|
||||
decorView.setSystemUiVisibility (decorView.getSystemUiVisibility() | flags);
|
||||
}
|
||||
|
||||
if (30 <= Build.VERSION.SDK_INT)
|
||||
getWindow().setDecorFitsSystemWindows (false);
|
||||
|
||||
if (29 <= Build.VERSION.SDK_INT)
|
||||
{
|
||||
if (Build.VERSION.SDK_INT < 35)
|
||||
getWindow().setStatusBarContrastEnforced (false);
|
||||
|
||||
getWindow().setNavigationBarContrastEnforced (false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate (Bundle savedInstanceState)
|
||||
{
|
||||
initEdgeToEdge();
|
||||
|
||||
super.onCreate (savedInstanceState);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onNewIntent (Intent intent)
|
||||
{
|
||||
super.onNewIntent (intent);
|
||||
setIntent (intent);
|
||||
|
||||
appNewIntent (intent);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume()
|
||||
{
|
||||
super.onResume();
|
||||
appOnResume();
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
package com.rmsl.juce;
|
||||
|
||||
import android.content.ContentProvider;
|
||||
import android.content.ContentValues;
|
||||
import android.content.res.AssetFileDescriptor;
|
||||
import android.content.res.Resources;
|
||||
import android.database.Cursor;
|
||||
import android.database.MatrixCursor;
|
||||
import android.net.Uri;
|
||||
import android.os.FileObserver;
|
||||
import android.os.ParcelFileDescriptor;
|
||||
|
||||
import java.lang.String;
|
||||
|
||||
public final class JuceSharingContentProvider extends ContentProvider
|
||||
{
|
||||
private Object lock = new Object ();
|
||||
|
||||
private native Cursor contentSharerQuery (Uri uri, String[] projection);
|
||||
private native AssetFileDescriptor contentSharerOpenFile (Uri uri, String mode);
|
||||
private native String[] contentSharerGetStreamTypes (Uri uri, String mimeTypeFilter);
|
||||
|
||||
@Override
|
||||
public boolean onCreate ()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Cursor query (Uri url, String[] projection, String selection,
|
||||
String[] selectionArgs, String sortOrder)
|
||||
{
|
||||
synchronized (lock)
|
||||
{
|
||||
return contentSharerQuery (url, projection);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Uri insert (Uri uri, ContentValues values)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int update (Uri uri, ContentValues values, String selection,
|
||||
String[] selectionArgs)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int delete (Uri uri, String selection, String[] selectionArgs)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getType (Uri uri)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetFileDescriptor openAssetFile (Uri uri, String mode)
|
||||
{
|
||||
synchronized (lock)
|
||||
{
|
||||
return contentSharerOpenFile (uri, mode);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ParcelFileDescriptor openFile (Uri uri, String mode)
|
||||
{
|
||||
synchronized (lock)
|
||||
{
|
||||
AssetFileDescriptor result = contentSharerOpenFile (uri, mode);
|
||||
|
||||
if (result != null)
|
||||
return result.getParcelFileDescriptor ();
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String[] getStreamTypes (Uri uri, String mimeTypeFilter)
|
||||
{
|
||||
synchronized (lock)
|
||||
{
|
||||
return contentSharerGetStreamTypes (uri, mimeTypeFilter);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
package com.rmsl.juce;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
//==============================================================================
|
||||
public class Receiver extends BroadcastReceiver
|
||||
{
|
||||
@Override
|
||||
public void onReceive (Context context, Intent intent)
|
||||
{
|
||||
onBroadcastResultNative (intent.getIntExtra ("com.rmsl.juce.JUCE_REQUEST_CODE", 0));
|
||||
}
|
||||
|
||||
private native void onBroadcastResultNative (int requestCode);
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
// The CoreGraphicsMetalLayerRenderer requires macOS 10.14 and iOS 12.
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wunguarded-availability", "-Wunguarded-availability-new")
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class CoreGraphicsMetalLayerRenderer
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
static auto create()
|
||||
{
|
||||
ObjCObjectHandle<id<MTLDevice>> device { MTLCreateSystemDefaultDevice() };
|
||||
return rawToUniquePtr (device != nullptr ? new CoreGraphicsMetalLayerRenderer (device)
|
||||
: nullptr);
|
||||
}
|
||||
|
||||
~CoreGraphicsMetalLayerRenderer()
|
||||
{
|
||||
if (memoryBlitCommandBuffer != nullptr)
|
||||
{
|
||||
stopGpuCommandSubmission = true;
|
||||
[memoryBlitCommandBuffer.get() waitUntilCompleted];
|
||||
}
|
||||
}
|
||||
|
||||
/* Returns any regions that weren't redrawn, and which should be retried next frame. */
|
||||
template <typename Callback>
|
||||
[[nodiscard]] RectangleList<float> drawRectangleList (CAMetalLayer* layer,
|
||||
float scaleFactor,
|
||||
Callback&& drawRectWithContext,
|
||||
RectangleList<float> dirtyRegions,
|
||||
const bool renderSync)
|
||||
{
|
||||
layer.presentsWithTransaction = renderSync;
|
||||
|
||||
if (memoryBlitCommandBuffer != nullptr)
|
||||
{
|
||||
switch ([memoryBlitCommandBuffer.get() status])
|
||||
{
|
||||
case MTLCommandBufferStatusNotEnqueued:
|
||||
case MTLCommandBufferStatusEnqueued:
|
||||
case MTLCommandBufferStatusCommitted:
|
||||
case MTLCommandBufferStatusScheduled:
|
||||
// If we haven't finished blitting the CPU texture to the GPU then
|
||||
// report that we have been unable to draw anything.
|
||||
return dirtyRegions;
|
||||
case MTLCommandBufferStatusCompleted:
|
||||
case MTLCommandBufferStatusError:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
layer.contentsScale = scaleFactor;
|
||||
|
||||
const auto drawableSizeTransform = CGAffineTransformMakeScale (layer.contentsScale, layer.contentsScale);
|
||||
const auto transformedFrameSize = CGSizeApplyAffineTransform (layer.bounds.size, drawableSizeTransform);
|
||||
|
||||
if (CGSizeEqualToSize (transformedFrameSize, CGSizeZero))
|
||||
return dirtyRegions;
|
||||
|
||||
if (resources == nullptr || ! CGSizeEqualToSize (layer.drawableSize, transformedFrameSize))
|
||||
{
|
||||
layer.drawableSize = transformedFrameSize;
|
||||
resources = std::make_unique<Resources> (device.get(), layer);
|
||||
dirtyRegions.clear();
|
||||
dirtyRegions.add (convertToRectFloat (layer.bounds));
|
||||
}
|
||||
|
||||
auto gpuTexture = resources->getGpuTexture();
|
||||
|
||||
if (gpuTexture == nullptr)
|
||||
{
|
||||
jassertfalse;
|
||||
return dirtyRegions;
|
||||
}
|
||||
|
||||
auto cgContext = resources->getCGContext();
|
||||
|
||||
for (auto rect : dirtyRegions)
|
||||
{
|
||||
const auto cgRect = convertToCGRect (rect);
|
||||
|
||||
CGContextSaveGState (cgContext);
|
||||
|
||||
CGContextClipToRect (cgContext, cgRect);
|
||||
drawRectWithContext (cgContext, cgRect);
|
||||
|
||||
CGContextRestoreGState (cgContext);
|
||||
}
|
||||
|
||||
resources->signalBufferModifiedByCpu();
|
||||
|
||||
auto sharedTexture = resources->getSharedTexture();
|
||||
|
||||
if (sharedTexture == nullptr)
|
||||
{
|
||||
jassertfalse;
|
||||
return dirtyRegions;
|
||||
}
|
||||
|
||||
auto encodeBlit = [] (id<MTLCommandBuffer> commandBuffer,
|
||||
id<MTLTexture> source,
|
||||
id<MTLTexture> destination)
|
||||
{
|
||||
auto blitCommandEncoder = [commandBuffer blitCommandEncoder];
|
||||
[blitCommandEncoder copyFromTexture: source
|
||||
sourceSlice: 0
|
||||
sourceLevel: 0
|
||||
sourceOrigin: MTLOrigin{}
|
||||
sourceSize: MTLSize { source.width, source.height, 1 }
|
||||
toTexture: destination
|
||||
destinationSlice: 0
|
||||
destinationLevel: 0
|
||||
destinationOrigin: MTLOrigin{}];
|
||||
[blitCommandEncoder endEncoding];
|
||||
};
|
||||
|
||||
if (renderSync)
|
||||
{
|
||||
@autoreleasepool
|
||||
{
|
||||
id<CAMetalDrawable> drawable = [layer nextDrawable];
|
||||
|
||||
if (drawable == nullptr)
|
||||
return dirtyRegions;
|
||||
|
||||
id<MTLCommandBuffer> commandBuffer = [commandQueue.get() commandBuffer];
|
||||
encodeBlit (commandBuffer, sharedTexture, drawable.texture);
|
||||
|
||||
[commandBuffer commit];
|
||||
[commandBuffer waitUntilScheduled];
|
||||
[drawable present];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Command buffers are usually considered temporary, and are automatically released by
|
||||
// the operating system when the rendering pipeline is finished. However, we want to keep
|
||||
// this one alive so that we can wait for pipeline completion in the destructor.
|
||||
memoryBlitCommandBuffer.reset ([[commandQueue.get() commandBuffer] retain]);
|
||||
|
||||
encodeBlit (memoryBlitCommandBuffer.get(), sharedTexture, gpuTexture);
|
||||
|
||||
[memoryBlitCommandBuffer.get() addScheduledHandler: ^(id<MTLCommandBuffer>)
|
||||
{
|
||||
// We're on a Metal thread, so we can make a blocking nextDrawable call
|
||||
// without stalling the message thread.
|
||||
|
||||
// Check if we can do an early exit.
|
||||
if (stopGpuCommandSubmission)
|
||||
return;
|
||||
|
||||
@autoreleasepool
|
||||
{
|
||||
id<CAMetalDrawable> drawable = [layer nextDrawable];
|
||||
|
||||
if (drawable == nullptr)
|
||||
return;
|
||||
|
||||
id<MTLCommandBuffer> presentationCommandBuffer = [commandQueue.get() commandBuffer];
|
||||
|
||||
encodeBlit (presentationCommandBuffer, gpuTexture, drawable.texture);
|
||||
|
||||
[presentationCommandBuffer addScheduledHandler: ^(id<MTLCommandBuffer>)
|
||||
{
|
||||
[drawable present];
|
||||
}];
|
||||
|
||||
[presentationCommandBuffer commit];
|
||||
}
|
||||
}];
|
||||
|
||||
[memoryBlitCommandBuffer.get() commit];
|
||||
}
|
||||
|
||||
dirtyRegions.clear();
|
||||
return dirtyRegions;
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
explicit CoreGraphicsMetalLayerRenderer (ObjCObjectHandle<id<MTLDevice>> mtlDevice)
|
||||
: device (mtlDevice),
|
||||
commandQueue ([device.get() newCommandQueue])
|
||||
{
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
static auto alignTo (size_t n, size_t alignment)
|
||||
{
|
||||
return ((n + alignment - 1) / alignment) * alignment;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
class GpuTexturePool
|
||||
{
|
||||
public:
|
||||
GpuTexturePool (id<MTLDevice> metalDevice, MTLTextureDescriptor* descriptor)
|
||||
{
|
||||
for (auto& t : textureCache)
|
||||
t.reset ((descriptor.width != 0 && descriptor.height != 0) ? [metalDevice newTextureWithDescriptor: descriptor]
|
||||
: nullptr);
|
||||
}
|
||||
|
||||
id<MTLTexture> take() const
|
||||
{
|
||||
auto iter = std::find_if (textureCache.begin(), textureCache.end(),
|
||||
[] (const ObjCObjectHandle<id<MTLTexture>>& t) { return [t.get() retainCount] == 1; });
|
||||
return iter == textureCache.end() ? nullptr : (*iter).get();
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<ObjCObjectHandle<id<MTLTexture>>, 3> textureCache;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GpuTexturePool)
|
||||
JUCE_DECLARE_NON_MOVEABLE (GpuTexturePool)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class Resources
|
||||
{
|
||||
static auto getResourceStorageMode()
|
||||
{
|
||||
#if JUCE_MAC && JUCE_INTEL
|
||||
return MTLResourceStorageModeManaged;
|
||||
#else
|
||||
return MTLResourceStorageModeShared;
|
||||
#endif
|
||||
}
|
||||
|
||||
static auto getStorageMode()
|
||||
{
|
||||
#if JUCE_MAC && JUCE_INTEL
|
||||
return MTLStorageModeManaged;
|
||||
#else
|
||||
return MTLStorageModeShared;
|
||||
#endif
|
||||
}
|
||||
|
||||
public:
|
||||
Resources (id<MTLDevice> metalDevice, CAMetalLayer* layer)
|
||||
{
|
||||
const auto bytesPerRow = alignTo ((size_t) layer.drawableSize.width * 4, 256);
|
||||
|
||||
const auto allocationSize = cpuRenderMemory.ensureSize (bytesPerRow * (size_t) layer.drawableSize.height);
|
||||
|
||||
buffer.reset ([metalDevice newBufferWithBytesNoCopy: cpuRenderMemory.get()
|
||||
length: allocationSize
|
||||
options: getResourceStorageMode()
|
||||
deallocator: nullptr]);
|
||||
|
||||
auto* textureDesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat: layer.pixelFormat
|
||||
width: (NSUInteger) layer.drawableSize.width
|
||||
height: (NSUInteger) layer.drawableSize.height
|
||||
mipmapped: NO];
|
||||
textureDesc.storageMode = getStorageMode();
|
||||
textureDesc.usage = MTLTextureUsageShaderRead;
|
||||
|
||||
sharedTexture.reset ([buffer.get() newTextureWithDescriptor: textureDesc
|
||||
offset: 0
|
||||
bytesPerRow: bytesPerRow]);
|
||||
|
||||
cgContext.reset (CGBitmapContextCreate (cpuRenderMemory.get(),
|
||||
(size_t) layer.drawableSize.width,
|
||||
(size_t) layer.drawableSize.height,
|
||||
8, // Bits per component
|
||||
bytesPerRow,
|
||||
CGColorSpaceCreateWithName (kCGColorSpaceSRGB),
|
||||
(uint32_t) kCGImageAlphaPremultipliedFirst | (uint32_t) kCGBitmapByteOrder32Host));
|
||||
|
||||
CGContextTranslateCTM (cgContext.get(), 0, layer.drawableSize.height);
|
||||
CGContextScaleCTM (cgContext.get(), layer.contentsScale, -layer.contentsScale);
|
||||
|
||||
textureDesc.storageMode = MTLStorageModePrivate;
|
||||
gpuTexturePool = std::make_unique<GpuTexturePool> (metalDevice, textureDesc);
|
||||
}
|
||||
|
||||
CGContextRef getCGContext() const noexcept { return cgContext.get(); }
|
||||
id<MTLTexture> getSharedTexture() const noexcept { return sharedTexture.get(); }
|
||||
id<MTLTexture> getGpuTexture() noexcept { return gpuTexturePool == nullptr ? nullptr : gpuTexturePool->take(); }
|
||||
|
||||
void signalBufferModifiedByCpu()
|
||||
{
|
||||
#if JUCE_MAC && JUCE_INTEL
|
||||
[buffer.get() didModifyRange: { 0, buffer.get().length }];
|
||||
#endif
|
||||
}
|
||||
|
||||
private:
|
||||
class AlignedMemory
|
||||
{
|
||||
public:
|
||||
AlignedMemory() = default;
|
||||
|
||||
void* get()
|
||||
{
|
||||
return allocation != nullptr ? allocation->data : nullptr;
|
||||
}
|
||||
|
||||
size_t ensureSize (size_t newSize)
|
||||
{
|
||||
const auto alignedSize = alignTo (newSize, pagesize);
|
||||
|
||||
if (alignedSize > size)
|
||||
{
|
||||
size = std::max (alignedSize, alignTo ((size_t) ((float) size * growthFactor), pagesize));
|
||||
allocation = std::make_unique<AllocationWrapper> (pagesize, size);
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr float growthFactor = 1.3f;
|
||||
|
||||
const size_t pagesize = (size_t) getpagesize();
|
||||
|
||||
struct AllocationWrapper
|
||||
{
|
||||
AllocationWrapper (size_t alignment, size_t allocationSize)
|
||||
{
|
||||
if (posix_memalign (&data, alignment, allocationSize) != 0)
|
||||
jassertfalse;
|
||||
}
|
||||
|
||||
~AllocationWrapper()
|
||||
{
|
||||
::free (data);
|
||||
}
|
||||
|
||||
void* data = nullptr;
|
||||
};
|
||||
|
||||
std::unique_ptr<AllocationWrapper> allocation;
|
||||
size_t size = 0;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlignedMemory)
|
||||
JUCE_DECLARE_NON_MOVEABLE (AlignedMemory)
|
||||
};
|
||||
|
||||
AlignedMemory cpuRenderMemory;
|
||||
|
||||
detail::ContextPtr cgContext;
|
||||
|
||||
ObjCObjectHandle<id<MTLBuffer>> buffer;
|
||||
ObjCObjectHandle<id<MTLTexture>> sharedTexture;
|
||||
std::unique_ptr<GpuTexturePool> gpuTexturePool;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Resources)
|
||||
JUCE_DECLARE_NON_MOVEABLE (Resources)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
std::unique_ptr<Resources> resources;
|
||||
|
||||
ObjCObjectHandle<id<MTLDevice>> device;
|
||||
ObjCObjectHandle<id<MTLCommandQueue>> commandQueue;
|
||||
ObjCObjectHandle<id<MTLCommandBuffer>> memoryBlitCommandBuffer;
|
||||
|
||||
std::atomic<bool> stopGpuCommandSubmission { false };
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsMetalLayerRenderer)
|
||||
JUCE_DECLARE_NON_MOVEABLE (CoreGraphicsMetalLayerRenderer)
|
||||
};
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,970 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
// This byte-code is generated from native/java/app/com/rmsl/juce/JuceContentProviderCursor.java with min sdk version 16
|
||||
// See juce_core/native/java/README.txt on how to generate this byte-code.
|
||||
static const uint8 javaJuceContentProviderCursor[] =
|
||||
{31,139,8,8,191,114,161,94,0,3,106,97,118,97,74,117,99,101,67,111,110,116,101,110,116,80,114,111,118,105,100,101,114,67,117,
|
||||
114,115,111,114,46,100,101,120,0,117,147,177,111,211,64,20,198,223,157,157,148,150,54,164,192,208,14,64,144,16,18,67,235,138,2,
|
||||
75,40,162,10,44,150,65,149,2,25,218,233,176,173,198,37,241,69,182,19,121,96,160,21,136,37,19,98,234,80,85,149,152,88,24,248,
|
||||
3,24,146,63,130,141,137,129,13,169,99,7,190,203,157,33,18,194,210,207,247,222,229,189,239,157,206,95,130,48,159,91,91,191,75,227,
|
||||
60,200,143,134,239,247,151,62,189,43,175,127,249,246,235,241,215,241,112,231,231,193,237,135,22,81,143,136,242,214,157,139,
|
||||
100,158,99,78,84,37,189,95,2,159,129,13,70,128,129,83,179,127,102,242,27,120,157,129,71,224,16,156,128,143,96,12,126,128,69,232,
|
||||
93,6,75,224,10,184,14,238,129,13,224,130,16,188,4,3,174,245,44,51,79,205,152,53,171,101,206,86,54,241,27,20,206,152,120,136,
|
||||
248,156,137,63,32,134,12,45,76,206,166,187,148,230,28,169,125,62,201,249,159,156,209,188,201,23,77,93,241,187,122,134,38,40,225,
|
||||
52,42,124,197,245,252,94,141,104,147,182,113,95,21,76,208,83,222,114,125,86,89,101,168,109,162,162,183,134,46,86,249,71,215,
|
||||
158,228,54,149,239,71,113,148,61,32,230,210,85,183,239,135,13,25,103,97,156,109,37,114,16,5,97,210,232,39,169,76,86,247,196,64,
|
||||
208,53,79,196,65,34,163,192,9,68,38,94,136,52,116,158,136,44,137,114,93,84,167,91,158,47,187,78,210,77,59,206,30,164,156,255,
|
||||
234,213,137,181,136,183,92,178,90,174,135,192,163,75,59,158,154,225,116,68,188,235,52,33,26,239,214,169,228,119,100,26,210,121,
|
||||
95,118,250,221,248,169,232,134,41,45,251,90,176,217,22,73,33,215,80,101,1,217,109,153,102,52,171,222,207,228,115,52,218,89,
|
||||
59,74,233,38,191,48,63,83,217,88,161,85,194,178,141,139,224,184,28,190,255,218,30,113,126,192,201,98,223,249,130,185,27,54,181,
|
||||
22,222,227,83,254,43,60,49,50,235,180,15,11,47,150,167,252,200,106,186,95,121,146,85,255,122,134,215,180,190,242,169,101,106,
|
||||
212,119,165,154,238,157,124,243,170,142,213,255,224,55,143,234,50,200,64,3,0,0,0,0};
|
||||
|
||||
// This byte-code is generated from native/java/app/com/rmsl/juce/JuceContentProviderFileObserver.java with min sdk version 16
|
||||
// See juce_core/native/java/README.txt on how to generate this byte-code.
|
||||
static const uint8 javaJuceContentProviderFileObserver[] =
|
||||
{31,139,8,8,194,122,161,94,0,3,106,97,118,97,74,117,99,101,67,111,110,116,101,110,116,80,114,111,118,105,100,101,114,70,105,
|
||||
108,101,79,98,115,101,114,118,101,114,46,100,101,120,0,133,147,205,107,19,65,24,198,223,249,72,98,171,46,105,235,69,16,201,65,81,
|
||||
68,221,136,10,66,84,144,250,65,194,130,197,212,32,5,15,155,100,104,182,38,187,97,119,141,241,32,126,30,196,147,23,79,246,216,
|
||||
131,120,202,77,169,80,212,191,64,193,66,143,30,60,138,255,130,62,179,51,165,219,147,129,223,188,239,188,239,204,179,179,179,79,
|
||||
186,106,60,93,61,123,158,54,159,255,248,112,97,210,120,124,98,237,251,177,7,109,245,115,253,225,198,159,47,243,171,135,198,130,
|
||||
104,72,68,227,214,185,89,178,191,45,78,116,128,76,189,8,62,3,169,235,128,129,61,204,204,203,204,204,171,24,142,99,207,2,226,
|
||||
4,124,4,159,192,6,248,5,254,130,42,250,87,193,13,224,129,91,224,14,184,11,30,129,23,224,21,120,3,222,130,53,240,158,27,125,110,
|
||||
159,95,176,231,41,233,51,216,249,75,44,152,178,249,107,228,211,54,95,69,190,215,230,239,144,11,40,57,153,150,200,222,81,100,
|
||||
170,166,190,47,139,68,51,185,200,237,93,8,27,191,218,66,17,138,186,54,225,230,44,195,42,209,149,194,18,238,206,201,58,250,121,
|
||||
235,182,215,172,160,191,200,137,159,113,172,158,204,246,50,251,62,38,151,89,103,251,29,139,23,131,48,72,47,19,171,19,107,208,
|
||||
145,198,253,142,154,143,194,84,133,233,66,28,141,130,174,138,175,7,125,117,179,157,168,120,164,226,211,43,254,200,167,131,158,
|
||||
31,118,227,40,232,186,81,226,230,219,53,114,189,78,52,112,227,65,210,119,87,32,229,254,71,175,70,179,158,150,116,251,126,184,
|
||||
236,54,211,56,8,151,107,196,90,36,90,117,143,100,171,97,70,175,142,2,134,195,29,35,213,236,249,241,110,161,107,35,148,169,160,
|
||||
178,32,123,81,146,210,148,30,23,163,219,137,34,57,240,147,123,84,138,66,179,76,14,253,180,71,50,237,5,9,29,21,229,185,153,146,
|
||||
115,233,20,157,228,206,92,201,89,194,21,113,70,156,61,125,34,191,113,246,12,223,143,253,198,101,237,183,223,133,229,226,182,103,
|
||||
121,206,183,34,231,93,153,243,111,129,118,60,92,164,29,31,179,138,217,175,189,204,202,102,141,246,24,175,24,125,237,111,97,
|
||||
215,104,15,80,197,236,205,252,81,54,185,254,255,252,3,243,31,208,130,120,3,0,0,0,0};
|
||||
|
||||
//==============================================================================
|
||||
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
|
||||
FIELD (authority, "authority", "Ljava/lang/String;")
|
||||
|
||||
DECLARE_JNI_CLASS (AndroidProviderInfo, "android/content/pm/ProviderInfo")
|
||||
#undef JNI_CLASS_MEMBERS
|
||||
|
||||
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
|
||||
METHOD (constructor, "<init>", "(Landroid/os/ParcelFileDescriptor;JJ)V") \
|
||||
METHOD (createInputStream, "createInputStream", "()Ljava/io/FileInputStream;") \
|
||||
METHOD (getLength, "getLength", "()J")
|
||||
|
||||
DECLARE_JNI_CLASS (AssetFileDescriptor, "android/content/res/AssetFileDescriptor")
|
||||
#undef JNI_CLASS_MEMBERS
|
||||
|
||||
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
|
||||
METHOD (close, "close", "()V")
|
||||
|
||||
DECLARE_JNI_CLASS (JavaCloseable, "java/io/Closeable")
|
||||
#undef JNI_CLASS_MEMBERS
|
||||
|
||||
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
|
||||
STATICMETHOD (open, "open", "(Ljava/io/File;I)Landroid/os/ParcelFileDescriptor;")
|
||||
|
||||
DECLARE_JNI_CLASS (ParcelFileDescriptor, "android/os/ParcelFileDescriptor")
|
||||
#undef JNI_CLASS_MEMBERS
|
||||
|
||||
//==============================================================================
|
||||
class AndroidContentSharerCursor
|
||||
{
|
||||
public:
|
||||
AndroidContentSharerCursor (JNIEnv* env,
|
||||
const LocalRef<jobject>& contentProvider,
|
||||
const LocalRef<jobjectArray>& resultColumns,
|
||||
std::function<void (AndroidContentSharerCursor&)> onCloseIn)
|
||||
: onClose (std::move (onCloseIn)),
|
||||
cursor (GlobalRef (LocalRef<jobject> (env->NewObject (JuceContentProviderCursor,
|
||||
JuceContentProviderCursor.constructor,
|
||||
reinterpret_cast<jlong> (this),
|
||||
resultColumns.get()))))
|
||||
{
|
||||
// the content provider must be created first
|
||||
jassert (contentProvider.get() != nullptr);
|
||||
}
|
||||
|
||||
jobject getNativeCursor() const { return cursor.get(); }
|
||||
|
||||
void addRow (LocalRef<jobjectArray>& values)
|
||||
{
|
||||
auto* env = getEnv();
|
||||
|
||||
env->CallVoidMethod (cursor.get(), JuceContentProviderCursor.addRow, values.get());
|
||||
}
|
||||
|
||||
private:
|
||||
static void cursorClosed (JNIEnv*, AndroidContentSharerCursor& t)
|
||||
{
|
||||
MessageManager::callAsync ([&t]
|
||||
{
|
||||
NullCheckedInvocation::invoke (t.onClose, t);
|
||||
});
|
||||
}
|
||||
|
||||
std::function<void (AndroidContentSharerCursor&)> onClose;
|
||||
GlobalRef cursor;
|
||||
|
||||
//==============================================================================
|
||||
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
|
||||
METHOD (addRow, "addRow", "([Ljava/lang/Object;)V") \
|
||||
METHOD (constructor, "<init>", "(J[Ljava/lang/String;)V") \
|
||||
CALLBACK (generatedCallback<&AndroidContentSharerCursor::cursorClosed>, "contentSharerCursorClosed", "(J)V") \
|
||||
|
||||
DECLARE_JNI_CLASS_WITH_BYTECODE (JuceContentProviderCursor, "com/rmsl/juce/JuceContentProviderCursor", 24, javaJuceContentProviderCursor)
|
||||
#undef JNI_CLASS_MEMBERS
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class AndroidContentSharerFileObserver
|
||||
{
|
||||
public:
|
||||
AndroidContentSharerFileObserver (JNIEnv* env,
|
||||
const LocalRef<jobject>& contentProvider,
|
||||
const File& filepathToUse,
|
||||
std::function<void()> onCloseIn)
|
||||
: onClose (std::move (onCloseIn)),
|
||||
filepath (filepathToUse),
|
||||
fileObserver (GlobalRef (LocalRef<jobject> (env->NewObject (JuceContentProviderFileObserver,
|
||||
JuceContentProviderFileObserver.constructor,
|
||||
reinterpret_cast<jlong> (this),
|
||||
javaString (filepath.getFullPathName()).get(),
|
||||
open | access | closeWrite | closeNoWrite))))
|
||||
{
|
||||
// the content provider must be created first
|
||||
jassert (contentProvider.get() != nullptr);
|
||||
|
||||
env->CallVoidMethod (fileObserver, JuceContentProviderFileObserver.startWatching);
|
||||
}
|
||||
|
||||
void onFileEvent (int event, const LocalRef<jstring>&)
|
||||
{
|
||||
if (event == open)
|
||||
{
|
||||
++numOpenedHandles;
|
||||
}
|
||||
else if (event == access)
|
||||
{
|
||||
fileWasRead = true;
|
||||
}
|
||||
else if (event == closeNoWrite || event == closeWrite)
|
||||
{
|
||||
--numOpenedHandles;
|
||||
|
||||
// numOpenedHandles may get negative if we don't receive open handle event
|
||||
if (fileWasRead && numOpenedHandles <= 0)
|
||||
{
|
||||
MessageManager::callAsync ([fo = fileObserver, oc = onClose]
|
||||
{
|
||||
getEnv()->CallVoidMethod (fo, JuceContentProviderFileObserver.stopWatching);
|
||||
NullCheckedInvocation::invoke (oc);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr int open = 32;
|
||||
static constexpr int access = 1;
|
||||
static constexpr int closeWrite = 8;
|
||||
static constexpr int closeNoWrite = 16;
|
||||
|
||||
std::function<void()> onClose;
|
||||
bool fileWasRead = false;
|
||||
int numOpenedHandles = 0;
|
||||
|
||||
File filepath;
|
||||
GlobalRef fileObserver;
|
||||
|
||||
//==============================================================================
|
||||
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
|
||||
METHOD (constructor, "<init>", "(JLjava/lang/String;I)V") \
|
||||
METHOD (startWatching, "startWatching", "()V") \
|
||||
METHOD (stopWatching, "stopWatching", "()V") \
|
||||
CALLBACK (generatedCallback<&AndroidContentSharerFileObserver::onFileEventCallback>, "contentSharerFileObserverEvent", "(JILjava/lang/String;)V") \
|
||||
|
||||
DECLARE_JNI_CLASS_WITH_BYTECODE (JuceContentProviderFileObserver, "com/rmsl/juce/JuceContentProviderFileObserver", 24, javaJuceContentProviderFileObserver)
|
||||
#undef JNI_CLASS_MEMBERS
|
||||
|
||||
static void onFileEventCallback (JNIEnv*, AndroidContentSharerFileObserver& t, jint event, jstring path)
|
||||
{
|
||||
t.onFileEvent (event, LocalRef<jstring> (path));
|
||||
}
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class ContentSharerGlobalImpl
|
||||
{
|
||||
public:
|
||||
static ContentSharerGlobalImpl& getInstance()
|
||||
{
|
||||
static ContentSharerGlobalImpl result;
|
||||
return result;
|
||||
}
|
||||
|
||||
const String packageName = juceString (LocalRef<jstring> ((jstring) getEnv()->CallObjectMethod (getAppContext().get(),
|
||||
AndroidContext.getPackageName)));
|
||||
const String uriBase = "content://" + packageName + ".sharingcontentprovider/";
|
||||
|
||||
std::unique_ptr<ActivityLauncher> sharePreparedFiles (const std::map<String, File>& fileForUriIn,
|
||||
const StringArray& mimeTypes,
|
||||
std::function<void (bool)> callback)
|
||||
{
|
||||
// This function should be called from the main thread, but must not race with singleton
|
||||
// access from other threads.
|
||||
const ScopedLock lock { mutex };
|
||||
|
||||
if (! isContentSharingEnabled())
|
||||
{
|
||||
// You need to enable "Content Sharing" in Projucer's Android exporter.
|
||||
jassertfalse;
|
||||
NullCheckedInvocation::invoke (callback, false);
|
||||
return {};
|
||||
}
|
||||
|
||||
auto* env = getEnv();
|
||||
|
||||
fileForUri.insert (fileForUriIn.begin(), fileForUriIn.end());
|
||||
|
||||
const auto* action = fileForUriIn.size() == 1 ? "android.intent.action.SEND"
|
||||
: "android.intent.action.SEND_MULTIPLE";
|
||||
|
||||
LocalRef<jobject> intent (env->NewObject (AndroidIntent, AndroidIntent.constructor));
|
||||
LocalRef { env->CallObjectMethod (intent, AndroidIntent.setAction, javaString (action).get()) };
|
||||
|
||||
LocalRef { env->CallObjectMethod (intent,
|
||||
AndroidIntent.setType,
|
||||
javaString (getCommonMimeType (mimeTypes)).get()) };
|
||||
|
||||
constexpr jint grantReadUriPermission = 1;
|
||||
constexpr jint grantPrefixUriPermission = 128;
|
||||
|
||||
LocalRef { env->CallObjectMethod (intent,
|
||||
AndroidIntent.setFlags,
|
||||
grantReadUriPermission | grantPrefixUriPermission) };
|
||||
|
||||
if (fileForUriIn.size() == 1)
|
||||
{
|
||||
const auto uri = fileForUriIn.begin()->first;
|
||||
LocalRef<jobject> androidUri { env->CallStaticObjectMethod (AndroidUri, AndroidUri.parse, javaString (uri).get()) };
|
||||
LocalRef { env->CallObjectMethod (intent,
|
||||
AndroidIntent.putExtraParcelable,
|
||||
javaString ("android.intent.extra.STREAM").get(),
|
||||
androidUri.get()) };
|
||||
}
|
||||
else
|
||||
{
|
||||
LocalRef<jobject> fileUris (env->NewObject (JavaArrayList, JavaArrayList.constructor, fileForUriIn.size()));
|
||||
|
||||
for (const auto& pair : fileForUriIn)
|
||||
{
|
||||
env->CallBooleanMethod (fileUris,
|
||||
JavaArrayList.add,
|
||||
env->CallStaticObjectMethod (AndroidUri,
|
||||
AndroidUri.parse,
|
||||
javaString (pair.first).get()));
|
||||
}
|
||||
|
||||
LocalRef { env->CallObjectMethod (intent,
|
||||
AndroidIntent.putParcelableArrayListExtra,
|
||||
javaString ("android.intent.extra.STREAM").get(),
|
||||
fileUris.get()) };
|
||||
}
|
||||
|
||||
return doIntent (intent, callback);
|
||||
}
|
||||
|
||||
std::unique_ptr<ActivityLauncher> shareText (const String& text,
|
||||
std::function<void (bool)> callback)
|
||||
{
|
||||
// This function should be called from the main thread, but must not race with singleton
|
||||
// access from other threads.
|
||||
const ScopedLock lock { mutex };
|
||||
|
||||
if (! isContentSharingEnabled())
|
||||
{
|
||||
// You need to enable "Content Sharing" in Projucer's Android exporter.
|
||||
jassertfalse;
|
||||
NullCheckedInvocation::invoke (callback, false);
|
||||
return {};
|
||||
}
|
||||
|
||||
auto* env = getEnv();
|
||||
|
||||
LocalRef<jobject> intent (env->NewObject (AndroidIntent, AndroidIntent.constructor));
|
||||
LocalRef { env->CallObjectMethod (intent,
|
||||
AndroidIntent.setAction,
|
||||
javaString ("android.intent.action.SEND").get()) };
|
||||
LocalRef { env->CallObjectMethod (intent,
|
||||
AndroidIntent.putExtra,
|
||||
javaString ("android.intent.extra.TEXT").get(),
|
||||
javaString (text).get()) };
|
||||
LocalRef { env->CallObjectMethod (intent, AndroidIntent.setType, javaString ("text/plain").get()) };
|
||||
|
||||
return doIntent (intent, callback);
|
||||
}
|
||||
|
||||
static void onBroadcastResultReceive (JNIEnv*, jobject, int requestCode)
|
||||
{
|
||||
getInstance().sharingFinished (requestCode, true);
|
||||
}
|
||||
|
||||
static jobject JNICALL contentSharerQuery (JNIEnv*, jobject contentProvider, jobject uri, jobjectArray projection)
|
||||
{
|
||||
return getInstance().query (LocalRef<jobject> (static_cast<jobject> (contentProvider)),
|
||||
LocalRef<jobject> (static_cast<jobject> (uri)),
|
||||
LocalRef<jobjectArray> (static_cast<jobjectArray> (projection)));
|
||||
}
|
||||
|
||||
static jobject JNICALL contentSharerOpenFile (JNIEnv*, jobject contentProvider, jobject uri, jstring mode)
|
||||
{
|
||||
return getInstance().openFile (LocalRef<jobject> (static_cast<jobject> (contentProvider)),
|
||||
LocalRef<jobject> (static_cast<jobject> (uri)),
|
||||
LocalRef<jstring> (static_cast<jstring> (mode)));
|
||||
}
|
||||
|
||||
static jobjectArray JNICALL contentSharerGetStreamTypes (JNIEnv*, jobject /*contentProvider*/, jobject uri, jstring mimeTypeFilter)
|
||||
{
|
||||
return getInstance().getStreamTypes (LocalRef (uri, IncrementRef::yes),
|
||||
LocalRef (mimeTypeFilter, IncrementRef::yes));
|
||||
}
|
||||
|
||||
private:
|
||||
ContentSharerGlobalImpl() = default;
|
||||
|
||||
LocalRef<jobject> makeChooser (const LocalRef<jobject>& intent, int request) const
|
||||
{
|
||||
auto* env = getEnv();
|
||||
|
||||
const auto text = javaString ("Choose share target");
|
||||
|
||||
constexpr jint FLAG_UPDATE_CURRENT = 0x08000000;
|
||||
constexpr jint FLAG_IMMUTABLE = 0x04000000;
|
||||
|
||||
const auto context = getAppContext();
|
||||
|
||||
LocalRef<jclass> klass { env->FindClass ("com/rmsl/juce/Receiver") };
|
||||
const LocalRef<jobject> replyIntent (env->NewObject (AndroidIntent, AndroidIntent.constructorWithContextAndClass, context.get(), klass.get()));
|
||||
LocalRef { getEnv()->CallObjectMethod (replyIntent,
|
||||
AndroidIntent.putExtraInt,
|
||||
javaString ("com.rmsl.juce.JUCE_REQUEST_CODE").get(),
|
||||
request) };
|
||||
|
||||
const auto flags = FLAG_UPDATE_CURRENT | FLAG_IMMUTABLE;
|
||||
const LocalRef<jobject> pendingIntent (env->CallStaticObjectMethod (AndroidPendingIntent,
|
||||
AndroidPendingIntent.getBroadcast,
|
||||
context.get(),
|
||||
request,
|
||||
replyIntent.get(),
|
||||
flags));
|
||||
|
||||
return LocalRef<jobject> (env->CallStaticObjectMethod (AndroidIntent,
|
||||
AndroidIntent.createChooserWithSender,
|
||||
intent.get(),
|
||||
text.get(),
|
||||
LocalRef { env->CallObjectMethod (pendingIntent,
|
||||
AndroidPendingIntent.getIntentSender) }.get()));
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
jobject openFile (const LocalRef<jobject>& contentProvider,
|
||||
const LocalRef<jobject>& uri,
|
||||
[[maybe_unused]] const LocalRef<jstring>& mode)
|
||||
{
|
||||
// This function can be called from multiple threads.
|
||||
const ScopedLock lock { mutex };
|
||||
|
||||
auto* env = getEnv();
|
||||
|
||||
auto uriElements = getContentUriElements (env, uri);
|
||||
|
||||
if (uriElements.file == File())
|
||||
return nullptr;
|
||||
|
||||
return getAssetFileDescriptor (env, contentProvider, uriElements.file);
|
||||
}
|
||||
|
||||
jobject query (const LocalRef<jobject>& contentProvider,
|
||||
const LocalRef<jobject>& uri,
|
||||
const LocalRef<jobjectArray>& projection)
|
||||
{
|
||||
// This function can be called from multiple threads.
|
||||
const ScopedLock lock { mutex };
|
||||
|
||||
StringArray requestedColumns = javaStringArrayToJuce (projection);
|
||||
StringArray supportedColumns = getSupportedColumns();
|
||||
|
||||
StringArray resultColumns;
|
||||
|
||||
for (const auto& col : supportedColumns)
|
||||
{
|
||||
if (requestedColumns.contains (col))
|
||||
resultColumns.add (col);
|
||||
}
|
||||
|
||||
// Unsupported columns were queried, file sharing may fail.
|
||||
if (resultColumns.isEmpty())
|
||||
return nullptr;
|
||||
|
||||
auto resultJavaColumns = juceStringArrayToJava (resultColumns);
|
||||
|
||||
auto* env = getEnv();
|
||||
|
||||
const auto uriElements = getContentUriElements (env, uri);
|
||||
|
||||
const auto callback = [info = uriElements.file] (auto& ref)
|
||||
{
|
||||
auto& pimplCursors = ContentSharerGlobalImpl::getInstance().cursors;
|
||||
const auto iter = std::lower_bound (pimplCursors.begin(), pimplCursors.end(), &ref, [] (const auto& managed, const auto* ptr)
|
||||
{
|
||||
return managed.get() == ptr;
|
||||
});
|
||||
|
||||
if (iter != pimplCursors.end() && iter->get() == &ref)
|
||||
pimplCursors.erase (iter);
|
||||
};
|
||||
|
||||
auto [iter, inserted] = cursors.emplace (new AndroidContentSharerCursor (env,
|
||||
contentProvider,
|
||||
resultJavaColumns,
|
||||
callback));
|
||||
|
||||
if (uriElements.file == File())
|
||||
return (*iter)->getNativeCursor();
|
||||
|
||||
LocalRef<jobjectArray> values (env->NewObjectArray ((jsize) resultColumns.size(), JavaObject, nullptr));
|
||||
|
||||
for (int i = 0; i < resultColumns.size(); ++i)
|
||||
{
|
||||
if (resultColumns.getReference (i) == "_display_name")
|
||||
{
|
||||
env->SetObjectArrayElement (values, i, javaString (uriElements.filename).get());
|
||||
}
|
||||
else if (resultColumns.getReference (i) == "_size")
|
||||
{
|
||||
LocalRef<jobject> javaFile (env->NewObject (JavaFile,
|
||||
JavaFile.constructor,
|
||||
javaString (uriElements.file.getFullPathName()).get()));
|
||||
|
||||
jlong fileLength = env->CallLongMethod (javaFile, JavaFile.length);
|
||||
|
||||
env->SetObjectArrayElement (values, i, env->NewObject (JavaLong, JavaLong.constructor, fileLength));
|
||||
}
|
||||
}
|
||||
|
||||
(*iter)->addRow (values);
|
||||
return (*iter)->getNativeCursor();
|
||||
}
|
||||
|
||||
jobjectArray getStreamTypes (const LocalRef<jobject>& uri, const LocalRef<jstring>& mimeTypeFilter)
|
||||
{
|
||||
// This function can be called from multiple threads.
|
||||
const ScopedLock lock { mutex };
|
||||
|
||||
auto* env = getEnv();
|
||||
|
||||
auto extension = getContentUriElements (env, uri).filename.fromLastOccurrenceOf (".", false, true);
|
||||
|
||||
if (extension.isEmpty())
|
||||
return nullptr;
|
||||
|
||||
return juceStringArrayToJava (filterMimeTypes (detail::MimeTypeTable::getMimeTypesForFileExtension (extension),
|
||||
juceString (mimeTypeFilter.get()))).release();
|
||||
}
|
||||
|
||||
std::unique_ptr<ActivityLauncher> doIntent (const LocalRef<jobject>& intent,
|
||||
std::function<void (bool)> callback)
|
||||
{
|
||||
static std::atomic<int> lastRequest = 1003;
|
||||
const auto requestCode = lastRequest++;
|
||||
callbackForRequest.emplace (requestCode, callback);
|
||||
const auto chooser = makeChooser (intent, requestCode);
|
||||
|
||||
auto launcher = std::make_unique<ActivityLauncher> (chooser, requestCode);
|
||||
launcher->callback = [] (int request, int resultCode, LocalRef<jobject>)
|
||||
{
|
||||
ContentSharerGlobalImpl::getInstance().sharingFinished (request, resultCode == -1);
|
||||
};
|
||||
launcher->open();
|
||||
return launcher;
|
||||
}
|
||||
|
||||
void sharingFinished (int request, bool succeeded)
|
||||
{
|
||||
// This function should be called from the main thread, but must not race with singleton
|
||||
// access from other threads.
|
||||
const ScopedLock lock { mutex };
|
||||
|
||||
const auto iter = callbackForRequest.find (request);
|
||||
|
||||
if (iter == callbackForRequest.end())
|
||||
return;
|
||||
|
||||
const ScopeGuard scope { [&] { callbackForRequest.erase (iter); } };
|
||||
|
||||
if (iter->second == nullptr)
|
||||
return;
|
||||
|
||||
iter->second (succeeded);
|
||||
}
|
||||
|
||||
bool isContentSharingEnabled() const
|
||||
{
|
||||
auto* env = getEnv();
|
||||
|
||||
LocalRef<jobject> packageManager (env->CallObjectMethod (getAppContext().get(), AndroidContext.getPackageManager));
|
||||
|
||||
constexpr int getProviders = 8;
|
||||
LocalRef<jobject> packageInfo (env->CallObjectMethod (packageManager,
|
||||
AndroidPackageManager.getPackageInfo,
|
||||
javaString (packageName).get(),
|
||||
getProviders));
|
||||
LocalRef<jobjectArray> providers ((jobjectArray) env->GetObjectField (packageInfo,
|
||||
AndroidPackageInfo.providers));
|
||||
|
||||
if (providers == nullptr)
|
||||
return false;
|
||||
|
||||
auto sharingContentProviderAuthority = packageName + ".sharingcontentprovider";
|
||||
const int numProviders = env->GetArrayLength (providers.get());
|
||||
|
||||
for (int i = 0; i < numProviders; ++i)
|
||||
{
|
||||
LocalRef<jobject> providerInfo (env->GetObjectArrayElement (providers, i));
|
||||
LocalRef<jstring> authority ((jstring) env->GetObjectField (providerInfo, AndroidProviderInfo.authority));
|
||||
|
||||
if (juceString (authority) == sharingContentProviderAuthority)
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
struct ContentUriElements
|
||||
{
|
||||
String filename;
|
||||
File file;
|
||||
};
|
||||
|
||||
ContentUriElements getContentUriElements (JNIEnv* env, const LocalRef<jobject>& uri) const
|
||||
{
|
||||
const auto fullUri = juceString ((jstring) env->CallObjectMethod (uri.get(), AndroidUri.toString));
|
||||
|
||||
const auto filename = fullUri.fromLastOccurrenceOf ("/", false, true);
|
||||
|
||||
const auto iter = fileForUri.find (fullUri);
|
||||
const auto info = iter != fileForUri.end() ? iter->second : File{};
|
||||
|
||||
return { filename, info };
|
||||
}
|
||||
|
||||
static StringArray getSupportedColumns()
|
||||
{
|
||||
return StringArray ("_display_name", "_size");
|
||||
}
|
||||
|
||||
jobject getAssetFileDescriptor (JNIEnv* env, const LocalRef<jobject>& contentProvider, const File& filepath)
|
||||
{
|
||||
if (nonAssetFilePathsPendingShare.find (filepath) == nonAssetFilePathsPendingShare.end())
|
||||
{
|
||||
const auto onCloseCallback = [filepath]
|
||||
{
|
||||
ContentSharerGlobalImpl::getInstance().nonAssetFilePathsPendingShare.erase (filepath);
|
||||
};
|
||||
|
||||
auto observer = rawToUniquePtr (new AndroidContentSharerFileObserver (env,
|
||||
contentProvider,
|
||||
filepath,
|
||||
onCloseCallback));
|
||||
|
||||
nonAssetFilePathsPendingShare.emplace (filepath, std::move (observer));
|
||||
}
|
||||
|
||||
const LocalRef<jobject> javaFile (env->NewObject (JavaFile,
|
||||
JavaFile.constructor,
|
||||
javaString (filepath.getFullPathName()).get()));
|
||||
|
||||
constexpr int modeReadOnly = 268435456;
|
||||
LocalRef<jobject> parcelFileDescriptor (env->CallStaticObjectMethod (ParcelFileDescriptor,
|
||||
ParcelFileDescriptor.open,
|
||||
javaFile.get(),
|
||||
modeReadOnly));
|
||||
|
||||
if (jniCheckHasExceptionOccurredAndClear())
|
||||
{
|
||||
// Failed to create file descriptor. Have you provided a valid file path/resource name?
|
||||
jassertfalse;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jlong startOffset = 0;
|
||||
jlong unknownLength = -1;
|
||||
|
||||
assetFileDescriptors.add (GlobalRef (LocalRef<jobject> (env->NewObject (AssetFileDescriptor,
|
||||
AssetFileDescriptor.constructor,
|
||||
parcelFileDescriptor.get(),
|
||||
startOffset,
|
||||
unknownLength))));
|
||||
|
||||
return assetFileDescriptors.getReference (assetFileDescriptors.size() - 1).get();
|
||||
}
|
||||
|
||||
StringArray filterMimeTypes (const StringArray& mimeTypes, const String& filter)
|
||||
{
|
||||
String filterToUse (filter.removeCharacters ("*"));
|
||||
|
||||
if (filterToUse.isEmpty() || filterToUse == "/")
|
||||
return mimeTypes;
|
||||
|
||||
StringArray result;
|
||||
|
||||
for (const auto& type : mimeTypes)
|
||||
if (String (type).contains (filterToUse))
|
||||
result.add (type);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static String getCommonMimeType (const StringArray& mimeTypes)
|
||||
{
|
||||
if (mimeTypes.isEmpty())
|
||||
return "*/*";
|
||||
|
||||
auto commonMime = mimeTypes[0];
|
||||
bool lookForCommonGroup = false;
|
||||
|
||||
for (int i = 1; i < mimeTypes.size(); ++i)
|
||||
{
|
||||
if (mimeTypes[i] == commonMime)
|
||||
continue;
|
||||
|
||||
if (! lookForCommonGroup)
|
||||
{
|
||||
lookForCommonGroup = true;
|
||||
commonMime = commonMime.upToFirstOccurrenceOf ("/", true, false);
|
||||
}
|
||||
|
||||
if (! mimeTypes[i].startsWith (commonMime))
|
||||
return "*/*";
|
||||
}
|
||||
|
||||
return lookForCommonGroup ? commonMime + "*" : commonMime;
|
||||
}
|
||||
|
||||
CriticalSection mutex;
|
||||
Array<GlobalRef> assetFileDescriptors;
|
||||
std::map<File, std::unique_ptr<AndroidContentSharerFileObserver>> nonAssetFilePathsPendingShare;
|
||||
std::set<std::unique_ptr<AndroidContentSharerCursor>> cursors;
|
||||
std::map<String, File> fileForUri;
|
||||
std::map<int, std::function<void (bool)>> callbackForRequest;
|
||||
};
|
||||
|
||||
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
|
||||
CALLBACK (ContentSharerGlobalImpl::contentSharerQuery, "contentSharerQuery", "(Landroid/net/Uri;[Ljava/lang/String;)Landroid/database/Cursor;") \
|
||||
CALLBACK (ContentSharerGlobalImpl::contentSharerOpenFile, "contentSharerOpenFile", "(Landroid/net/Uri;Ljava/lang/String;)Landroid/content/res/AssetFileDescriptor;") \
|
||||
CALLBACK (ContentSharerGlobalImpl::contentSharerGetStreamTypes, "contentSharerGetStreamTypes", "(Landroid/net/Uri;Ljava/lang/String;)[Ljava/lang/String;") \
|
||||
|
||||
DECLARE_JNI_CLASS (JuceSharingContentProvider, "com/rmsl/juce/JuceSharingContentProvider")
|
||||
#undef JNI_CLASS_MEMBERS
|
||||
|
||||
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
|
||||
CALLBACK (ContentSharerGlobalImpl::onBroadcastResultReceive, "onBroadcastResultNative", "(I)V")
|
||||
|
||||
DECLARE_JNI_CLASS (AndroidReceiver, "com/rmsl/juce/Receiver")
|
||||
#undef JNI_CLASS_MEMBERS
|
||||
|
||||
//==============================================================================
|
||||
class AndroidContentSharerPrepareFilesTask final : private AsyncUpdater
|
||||
{
|
||||
public:
|
||||
AndroidContentSharerPrepareFilesTask (const Array<URL>& fileUrls,
|
||||
std::function<void (const std::map<String, File>&, const StringArray&)> onCompletionIn)
|
||||
: onCompletion (std::move (onCompletionIn)),
|
||||
task (std::async (std::launch::async, [this, fileUrls]
|
||||
{
|
||||
run (fileUrls);
|
||||
triggerAsyncUpdate();
|
||||
})) {}
|
||||
|
||||
~AndroidContentSharerPrepareFilesTask() override
|
||||
{
|
||||
task.wait();
|
||||
cancelPendingUpdate();
|
||||
}
|
||||
|
||||
private:
|
||||
const String packageName = ContentSharerGlobalImpl::getInstance().packageName;
|
||||
const String uriBase = ContentSharerGlobalImpl::getInstance().uriBase;
|
||||
|
||||
struct StreamCloser
|
||||
{
|
||||
explicit StreamCloser (const LocalRef<jobject>& streamToUse)
|
||||
: stream (GlobalRef (streamToUse))
|
||||
{
|
||||
}
|
||||
|
||||
~StreamCloser()
|
||||
{
|
||||
if (stream.get() != nullptr)
|
||||
getEnv()->CallVoidMethod (stream, JavaCloseable.close);
|
||||
}
|
||||
|
||||
GlobalRef stream;
|
||||
};
|
||||
|
||||
void handleAsyncUpdate() override
|
||||
{
|
||||
onCompletion (infoForUri, mimeTypes);
|
||||
}
|
||||
|
||||
void run (const Array<URL>& fileUrls)
|
||||
{
|
||||
auto* env = getEnv();
|
||||
|
||||
StringArray filePaths;
|
||||
|
||||
for (const auto& f : fileUrls)
|
||||
{
|
||||
const auto scheme = f.getScheme();
|
||||
|
||||
// Only "file://" scheme or no scheme (for files in app bundle) are allowed!
|
||||
jassert (scheme.isEmpty() || scheme == "file");
|
||||
|
||||
const auto fileToPrepare = [&]
|
||||
{
|
||||
if (! scheme.isEmpty())
|
||||
return f;
|
||||
|
||||
// Raw resource names need to be all lower case
|
||||
jassert (f.toString (true).toLowerCase() == f.toString (true));
|
||||
|
||||
// This will get us a file with file:// URI
|
||||
return copyAssetFileToTemporaryFile (env, f.toString (true));
|
||||
}();
|
||||
|
||||
if (fileToPrepare.isEmpty())
|
||||
continue;
|
||||
|
||||
const auto filepath = URL::removeEscapeChars (fileToPrepare.toString (true).fromFirstOccurrenceOf ("file://", false, false));
|
||||
|
||||
filePaths.add (filepath);
|
||||
}
|
||||
|
||||
std::vector<String> extensions;
|
||||
|
||||
for (const auto& filepath : filePaths)
|
||||
{
|
||||
const auto filename = filepath.fromLastOccurrenceOf ("/", false, true);
|
||||
extensions.push_back (filename.fromLastOccurrenceOf (".", false, true));
|
||||
}
|
||||
|
||||
std::set<String> mimes;
|
||||
|
||||
if (std::none_of (extensions.begin(), extensions.end(), [] (const String& s) { return s.isEmpty(); }))
|
||||
for (const auto& extension : extensions)
|
||||
for (const auto& mime : detail::MimeTypeTable::getMimeTypesForFileExtension (extension))
|
||||
mimes.insert (mime);
|
||||
|
||||
for (const auto& mime : mimes)
|
||||
mimeTypes.add (mime);
|
||||
|
||||
for (auto it = filePaths.begin(); it != filePaths.end(); ++it)
|
||||
{
|
||||
const auto filename = it->fromLastOccurrenceOf ("/", false, true);
|
||||
const auto contentString = uriBase + String (std::distance (filePaths.begin(), it)) + "/" + filename;
|
||||
infoForUri.emplace (contentString, *it);
|
||||
}
|
||||
}
|
||||
|
||||
URL copyAssetFileToTemporaryFile (JNIEnv* env, const String& filename)
|
||||
{
|
||||
LocalRef<jobject> resources (env->CallObjectMethod (getAppContext().get(), AndroidContext.getResources));
|
||||
int fileId = env->CallIntMethod (resources,
|
||||
AndroidResources.getIdentifier,
|
||||
javaString (filename).get(),
|
||||
javaString ("raw").get(),
|
||||
javaString (packageName).get());
|
||||
|
||||
// Raw resource not found. Please make sure that you include your file as a raw resource
|
||||
// and that you specify just the file name, without an extension.
|
||||
jassert (fileId != 0);
|
||||
|
||||
if (fileId == 0)
|
||||
return {};
|
||||
|
||||
LocalRef<jobject> assetFd (env->CallObjectMethod (resources,
|
||||
AndroidResources.openRawResourceFd,
|
||||
fileId));
|
||||
|
||||
StreamCloser inputStream (LocalRef<jobject> (env->CallObjectMethod (assetFd, AssetFileDescriptor.createInputStream)));
|
||||
|
||||
if (jniCheckHasExceptionOccurredAndClear())
|
||||
{
|
||||
// Failed to open file stream for resource
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
auto tempFile = File::createTempFile ({});
|
||||
tempFile.createDirectory();
|
||||
tempFile = tempFile.getChildFile (filename);
|
||||
|
||||
StreamCloser outputStream (LocalRef<jobject> (env->NewObject (JavaFileOutputStream,
|
||||
JavaFileOutputStream.constructor,
|
||||
javaString (tempFile.getFullPathName()).get())));
|
||||
|
||||
if (jniCheckHasExceptionOccurredAndClear())
|
||||
{
|
||||
// Failed to open file stream for temporary file
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
LocalRef<jbyteArray> buffer (env->NewByteArray (1024));
|
||||
int bytesRead = 0;
|
||||
|
||||
for (;;)
|
||||
{
|
||||
bytesRead = env->CallIntMethod (inputStream.stream, JavaFileInputStream.read, buffer.get());
|
||||
|
||||
if (jniCheckHasExceptionOccurredAndClear())
|
||||
{
|
||||
// Failed to read from resource file.
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
if (bytesRead < 0)
|
||||
break;
|
||||
|
||||
env->CallVoidMethod (outputStream.stream, JavaFileOutputStream.write, buffer.get(), 0, bytesRead);
|
||||
|
||||
if (jniCheckHasExceptionOccurredAndClear())
|
||||
{
|
||||
// Failed to write to temporary file.
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
return URL (tempFile);
|
||||
}
|
||||
|
||||
std::map<String, File> infoForUri;
|
||||
StringArray mimeTypes;
|
||||
std::function<void (const std::map<String, File>&, const StringArray&)> onCompletion;
|
||||
// This task is obtained from std::async(). Its destructor will block until the asynchronous
|
||||
// task has completed; as a result, we can guarantee that the async task will have finished
|
||||
// before the lifetimes of the other data members and base class end.
|
||||
std::future<void> task;
|
||||
};
|
||||
|
||||
auto detail::ScopedContentSharerInterface::shareFiles (const Array<URL>& urls, Component*) -> std::unique_ptr<ScopedContentSharerInterface>
|
||||
{
|
||||
class NativeScopedContentSharerInterface final : public detail::ScopedContentSharerInterface
|
||||
{
|
||||
public:
|
||||
explicit NativeScopedContentSharerInterface (Array<URL> f)
|
||||
: files (std::move (f)) {}
|
||||
|
||||
void runAsync (ContentSharer::Callback callback) override
|
||||
{
|
||||
// This lambda will only be called if the AndroidContentSharerPrepareFilesTask is still
|
||||
// alive. We know that our lifetime will end after the
|
||||
// AndroidContentSharerPrepareFilesTask, so there's no need to check that 'this' is
|
||||
// still valid inside the lambda.
|
||||
task.emplace (files, [this, callback] (const std::map<String, File>& infoForUri, const StringArray& mimeTypes)
|
||||
{
|
||||
launcher = ContentSharerGlobalImpl::getInstance().sharePreparedFiles (infoForUri, mimeTypes, [callback] (bool success)
|
||||
{
|
||||
callback (success, {});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
void close() override
|
||||
{
|
||||
// dismiss() doesn't close the sharesheet, and there doesn't seem to be any alternative
|
||||
// Maybe this will work in the future...
|
||||
launcher.reset();
|
||||
}
|
||||
|
||||
private:
|
||||
Array<URL> files;
|
||||
std::optional<AndroidContentSharerPrepareFilesTask> task;
|
||||
std::unique_ptr<ActivityLauncher> launcher;
|
||||
};
|
||||
|
||||
return std::make_unique<NativeScopedContentSharerInterface> (std::move (urls));
|
||||
}
|
||||
|
||||
auto detail::ScopedContentSharerInterface::shareText (const String& text, Component*) -> std::unique_ptr<ScopedContentSharerInterface>
|
||||
{
|
||||
class NativeScopedContentSharerInterface final : public detail::ScopedContentSharerInterface
|
||||
{
|
||||
public:
|
||||
explicit NativeScopedContentSharerInterface (String t)
|
||||
: text (std::move (t)) {}
|
||||
|
||||
void runAsync (ContentSharer::Callback callback) override
|
||||
{
|
||||
launcher = ContentSharerGlobalImpl::getInstance().shareText (text, [callback] (bool success)
|
||||
{
|
||||
callback (success, {});
|
||||
});
|
||||
}
|
||||
|
||||
void close() override
|
||||
{
|
||||
// dismiss() doesn't close the sharesheet, and there doesn't seem to be any alternative
|
||||
// Maybe this will work in the future...
|
||||
launcher.reset();
|
||||
}
|
||||
|
||||
private:
|
||||
String text;
|
||||
std::unique_ptr<ActivityLauncher> launcher;
|
||||
};
|
||||
|
||||
return std::make_unique<NativeScopedContentSharerInterface> (std::move (text));
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class NativeScopedContentSharerInterface final : public detail::ScopedContentSharerInterface,
|
||||
public detail::NativeModalWrapperComponent
|
||||
{
|
||||
public:
|
||||
NativeScopedContentSharerInterface (Component* parentIn, NSUniquePtr<NSArray> itemsIn)
|
||||
: parent (parentIn), items (std::move (itemsIn)) {}
|
||||
|
||||
void runAsync (std::function<void (bool, const String&)> callback) override
|
||||
{
|
||||
if ([items.get() count] == 0)
|
||||
{
|
||||
jassertfalse;
|
||||
NullCheckedInvocation::invoke (callback, false, "No valid items found for sharing.");
|
||||
return;
|
||||
}
|
||||
|
||||
controller.reset ([[UIActivityViewController alloc] initWithActivityItems: items.get()
|
||||
applicationActivities: nil]);
|
||||
|
||||
controller.get().excludedActivityTypes = nil;
|
||||
|
||||
controller.get().completionWithItemsHandler = ^([[maybe_unused]] UIActivityType type, BOOL completed,
|
||||
[[maybe_unused]] NSArray* returnedItems, NSError* error)
|
||||
{
|
||||
const auto errorDescription = error != nil ? nsStringToJuce ([error localizedDescription])
|
||||
: String();
|
||||
exitModalState (0);
|
||||
|
||||
NullCheckedInvocation::invoke (callback, completed && errorDescription.isEmpty(), errorDescription);
|
||||
};
|
||||
|
||||
displayNativeWindowModally (parent);
|
||||
|
||||
enterModalState (true, nullptr, false);
|
||||
}
|
||||
|
||||
void close() override
|
||||
{
|
||||
[controller.get() dismissViewControllerAnimated: YES completion: nil];
|
||||
}
|
||||
|
||||
private:
|
||||
UIViewController* getViewController() const override { return controller.get(); }
|
||||
|
||||
Component* parent = nullptr;
|
||||
NSUniquePtr<UIActivityViewController> controller;
|
||||
NSUniquePtr<NSArray> items;
|
||||
};
|
||||
|
||||
auto detail::ScopedContentSharerInterface::shareFiles (const Array<URL>& files, Component* parent) -> std::unique_ptr<ScopedContentSharerInterface>
|
||||
{
|
||||
NSUniquePtr<NSMutableArray> urls ([[NSMutableArray arrayWithCapacity: (NSUInteger) files.size()] retain]);
|
||||
|
||||
for (const auto& f : files)
|
||||
{
|
||||
NSString* nativeFilePath = nil;
|
||||
|
||||
if (f.isLocalFile())
|
||||
{
|
||||
nativeFilePath = juceStringToNS (f.getLocalFile().getFullPathName());
|
||||
}
|
||||
else
|
||||
{
|
||||
auto filePath = f.toString (false);
|
||||
|
||||
auto* fileDirectory = filePath.contains ("/")
|
||||
? juceStringToNS (filePath.upToLastOccurrenceOf ("/", false, false))
|
||||
: [NSString string];
|
||||
|
||||
auto fileName = juceStringToNS (filePath.fromLastOccurrenceOf ("/", false, false)
|
||||
.upToLastOccurrenceOf (".", false, false));
|
||||
|
||||
auto fileExt = juceStringToNS (filePath.fromLastOccurrenceOf (".", false, false));
|
||||
|
||||
if ([fileDirectory length] == NSUInteger (0))
|
||||
nativeFilePath = [[NSBundle mainBundle] pathForResource: fileName
|
||||
ofType: fileExt];
|
||||
else
|
||||
nativeFilePath = [[NSBundle mainBundle] pathForResource: fileName
|
||||
ofType: fileExt
|
||||
inDirectory: fileDirectory];
|
||||
}
|
||||
|
||||
if (nativeFilePath != nil)
|
||||
[urls.get() addObject: [NSURL fileURLWithPath: nativeFilePath]];
|
||||
}
|
||||
|
||||
return std::make_unique<NativeScopedContentSharerInterface> (parent, std::move (urls));
|
||||
}
|
||||
|
||||
auto detail::ScopedContentSharerInterface::shareText (const String& text, Component* parent) -> std::unique_ptr<ScopedContentSharerInterface>
|
||||
{
|
||||
NSUniquePtr<NSArray> array ([[NSArray arrayWithObject: juceStringToNS (text)] retain]);
|
||||
return std::make_unique<NativeScopedContentSharerInterface> (parent, std::move (array));
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,622 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
using WindowsScopedEvent = std::unique_ptr<std::remove_pointer_t<HANDLE>, FunctionPointerDestructor<CloseHandle>>;
|
||||
|
||||
//==============================================================================
|
||||
class SwapChain
|
||||
{
|
||||
public:
|
||||
SwapChain() = default;
|
||||
|
||||
HRESULT create (HWND hwnd, Rectangle<int> size, DxgiAdapter::Ptr adapter)
|
||||
{
|
||||
if (chain != nullptr || hwnd == nullptr)
|
||||
return S_OK;
|
||||
|
||||
auto dxgiFactory = directX->adapters.getFactory();
|
||||
|
||||
if (dxgiFactory == nullptr || adapter->direct3DDevice == nullptr)
|
||||
return E_FAIL;
|
||||
|
||||
buffer = nullptr;
|
||||
chain = nullptr;
|
||||
|
||||
// Make the waitable swap chain
|
||||
// Create the swap chain with premultiplied alpha support for transparent windows
|
||||
DXGI_SWAP_CHAIN_DESC1 swapChainDescription = {};
|
||||
swapChainDescription.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
swapChainDescription.Width = (UINT) size.getWidth();
|
||||
swapChainDescription.Height = (UINT) size.getHeight();
|
||||
swapChainDescription.SampleDesc.Count = 1;
|
||||
swapChainDescription.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
|
||||
swapChainDescription.BufferCount = 2;
|
||||
swapChainDescription.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
|
||||
swapChainDescription.Flags = swapChainFlags;
|
||||
|
||||
swapChainDescription.Scaling = DXGI_SCALING_STRETCH;
|
||||
swapChainDescription.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
|
||||
|
||||
if (const auto hr = dxgiFactory->CreateSwapChainForComposition (adapter->direct3DDevice,
|
||||
&swapChainDescription,
|
||||
nullptr,
|
||||
chain.resetAndGetPointerAddress());
|
||||
FAILED (hr))
|
||||
{
|
||||
return hr;
|
||||
}
|
||||
|
||||
ComSmartPtr<IDXGISwapChain2> chain2;
|
||||
if (const auto hr = chain.QueryInterface (chain2); FAILED (hr))
|
||||
return hr;
|
||||
|
||||
if (chain2 == nullptr)
|
||||
return E_FAIL;
|
||||
|
||||
chain2->SetMaximumFrameLatency (1);
|
||||
event.reset (chain2->GetFrameLatencyWaitableObject());
|
||||
|
||||
createBuffer (adapter);
|
||||
return buffer != nullptr ? S_OK : E_FAIL;
|
||||
}
|
||||
|
||||
bool canPaint() const
|
||||
{
|
||||
return chain != nullptr && buffer != nullptr;
|
||||
}
|
||||
|
||||
HRESULT resize (Rectangle<int> newSize)
|
||||
{
|
||||
if (chain == nullptr)
|
||||
return E_FAIL;
|
||||
|
||||
constexpr auto minFrameSize = 1;
|
||||
constexpr auto maxFrameSize = 16384;
|
||||
|
||||
auto scaledSize = newSize.getUnion ({ minFrameSize, minFrameSize })
|
||||
.getIntersection ({ maxFrameSize, maxFrameSize });
|
||||
|
||||
buffer = nullptr;
|
||||
|
||||
if (const auto hr = chain->ResizeBuffers (0,
|
||||
(UINT) scaledSize.getWidth(),
|
||||
(UINT) scaledSize.getHeight(),
|
||||
DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
swapChainFlags);
|
||||
FAILED (hr))
|
||||
{
|
||||
return hr;
|
||||
}
|
||||
|
||||
ComSmartPtr<IDXGIDevice> device;
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
chain->GetDevice (__uuidof (device), (void**) device.resetAndGetPointerAddress());
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
createBuffer (Direct2DDeviceResources::findAdapter (directX->adapters, device));
|
||||
|
||||
return buffer != nullptr ? S_OK : E_FAIL;
|
||||
}
|
||||
|
||||
Rectangle<int> getSize() const
|
||||
{
|
||||
const auto surface = getSurface();
|
||||
|
||||
if (surface == nullptr)
|
||||
return {};
|
||||
|
||||
DXGI_SURFACE_DESC desc{};
|
||||
if (FAILED (surface->GetDesc (&desc)))
|
||||
return {};
|
||||
|
||||
return { (int) desc.Width, (int) desc.Height };
|
||||
}
|
||||
|
||||
auto getChain() const
|
||||
{
|
||||
return chain;
|
||||
}
|
||||
|
||||
ComSmartPtr<ID2D1Bitmap1> getBuffer() const
|
||||
{
|
||||
return buffer;
|
||||
}
|
||||
|
||||
bool canPresent()
|
||||
{
|
||||
didWait = didWait || event == nullptr || (WaitForSingleObjectEx (event.get(), 0, true) == WAIT_OBJECT_0);
|
||||
return didWait;
|
||||
}
|
||||
|
||||
void didPresent()
|
||||
{
|
||||
didWait = false;
|
||||
}
|
||||
|
||||
static constexpr uint32 swapChainFlags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
|
||||
static constexpr uint32 presentSyncInterval = 1;
|
||||
static constexpr uint32 presentFlags = 0;
|
||||
|
||||
private:
|
||||
ComSmartPtr<IDXGISurface> getSurface() const
|
||||
{
|
||||
if (chain == nullptr)
|
||||
return nullptr;
|
||||
|
||||
ComSmartPtr<IDXGISurface> surface;
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
if (const auto hr = chain->GetBuffer (0, __uuidof (surface), reinterpret_cast<void**> (surface.resetAndGetPointerAddress())); FAILED (hr))
|
||||
return nullptr;
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
return surface;
|
||||
}
|
||||
|
||||
void createBuffer (DxgiAdapter::Ptr adapter)
|
||||
{
|
||||
buffer = nullptr;
|
||||
|
||||
const auto deviceContext = Direct2DDeviceContext::create (adapter);
|
||||
|
||||
if (deviceContext == nullptr)
|
||||
return;
|
||||
|
||||
const auto surface = getSurface();
|
||||
|
||||
if (surface == nullptr)
|
||||
return;
|
||||
|
||||
D2D1_BITMAP_PROPERTIES1 bitmapProperties{};
|
||||
bitmapProperties.bitmapOptions = D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW;
|
||||
bitmapProperties.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
bitmapProperties.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
|
||||
|
||||
deviceContext->CreateBitmapFromDxgiSurface (surface, bitmapProperties, buffer.resetAndGetPointerAddress());
|
||||
}
|
||||
|
||||
class AssignableDirectX
|
||||
{
|
||||
public:
|
||||
AssignableDirectX() = default;
|
||||
AssignableDirectX (const AssignableDirectX&) {}
|
||||
AssignableDirectX (AssignableDirectX&&) noexcept {}
|
||||
AssignableDirectX& operator= (const AssignableDirectX&) { return *this; }
|
||||
AssignableDirectX& operator= (AssignableDirectX&&) noexcept { return *this; }
|
||||
~AssignableDirectX() = default;
|
||||
|
||||
DirectX* operator->() const { return directX.operator->(); }
|
||||
|
||||
private:
|
||||
SharedResourcePointer<DirectX> directX;
|
||||
};
|
||||
|
||||
AssignableDirectX directX;
|
||||
ComSmartPtr<IDXGISwapChain1> chain;
|
||||
ComSmartPtr<ID2D1Bitmap1> buffer;
|
||||
WindowsScopedEvent event;
|
||||
bool didWait = false;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/* DirectComposition
|
||||
Using DirectComposition enables transparent windows and smoother window
|
||||
resizing
|
||||
|
||||
This class builds a simple DirectComposition tree that ultimately contains
|
||||
the swap chain
|
||||
*/
|
||||
class CompositionTree
|
||||
{
|
||||
public:
|
||||
static std::optional<CompositionTree> create (IDXGIDevice* dxgiDevice,
|
||||
HWND hwnd,
|
||||
IDXGISwapChain1* swapChain)
|
||||
{
|
||||
if (dxgiDevice == nullptr)
|
||||
return {};
|
||||
|
||||
CompositionTree result;
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
|
||||
if (const auto hr = DCompositionCreateDevice (dxgiDevice,
|
||||
__uuidof (IDCompositionDevice),
|
||||
reinterpret_cast<void**> (result.compositionDevice.resetAndGetPointerAddress()));
|
||||
FAILED (hr))
|
||||
{
|
||||
return {};
|
||||
}
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
if (const auto hr = result.compositionDevice->CreateTargetForHwnd (hwnd, FALSE, result.compositionTarget.resetAndGetPointerAddress()); FAILED (hr))
|
||||
return {};
|
||||
if (const auto hr = result.compositionDevice->CreateVisual (result.compositionVisual.resetAndGetPointerAddress()); FAILED (hr))
|
||||
return {};
|
||||
if (const auto hr = result.compositionTarget->SetRoot (result.compositionVisual); FAILED (hr))
|
||||
return {};
|
||||
if (const auto hr = result.compositionVisual->SetContent (swapChain); FAILED (hr))
|
||||
return {};
|
||||
if (const auto hr = result.compositionDevice->Commit(); FAILED (hr))
|
||||
return {};
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private:
|
||||
CompositionTree() = default;
|
||||
|
||||
ComSmartPtr<IDCompositionDevice> compositionDevice;
|
||||
ComSmartPtr<IDCompositionTarget> compositionTarget;
|
||||
ComSmartPtr<IDCompositionVisual> compositionVisual;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
struct Direct2DHwndContext::HwndPimpl : public Pimpl
|
||||
{
|
||||
private:
|
||||
HWND hwnd;
|
||||
SwapChain swap;
|
||||
ComSmartPtr<ID2D1DeviceContext1> deviceContext;
|
||||
std::optional<CompositionTree> compositionTree;
|
||||
|
||||
// Areas that must be repainted during the next paint call, between startFrame/endFrame
|
||||
RectangleList<int> deferredRepaintsCurrent, deferredRepaintsNext;
|
||||
|
||||
std::vector<RECT> dirtyRectangles;
|
||||
int64 lastFinishFrameTicks = 0;
|
||||
|
||||
bool prepare() override
|
||||
{
|
||||
const auto adapter = getDefaultAdapter();
|
||||
|
||||
if (adapter == nullptr)
|
||||
return false;
|
||||
|
||||
if (deviceContext == nullptr)
|
||||
deviceContext = Direct2DDeviceContext::create (adapter);
|
||||
|
||||
if (deviceContext == nullptr)
|
||||
return false;
|
||||
|
||||
if (! Pimpl::prepare())
|
||||
return false;
|
||||
|
||||
if (! hwnd || getClientRect().isEmpty())
|
||||
return false;
|
||||
|
||||
if (! swap.canPaint())
|
||||
{
|
||||
if (auto hr = swap.create (hwnd, getClientRect(), adapter); FAILED (hr))
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! compositionTree.has_value())
|
||||
compositionTree = CompositionTree::create (adapter->dxgiDevice, hwnd, swap.getChain());
|
||||
|
||||
if (! compositionTree.has_value())
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void teardown() override
|
||||
{
|
||||
compositionTree.reset();
|
||||
deviceContext = nullptr;
|
||||
swap = {};
|
||||
|
||||
Pimpl::teardown();
|
||||
}
|
||||
|
||||
RectangleList<int> getPaintAreas() const override
|
||||
{
|
||||
return deferredRepaintsNext;
|
||||
}
|
||||
|
||||
bool checkPaintReady() override
|
||||
{
|
||||
const auto now = Time::getHighResolutionTicks();
|
||||
|
||||
// Try not to saturate the message thread; this is a little crude. Perhaps some kind of credit system...
|
||||
if (Time::highResolutionTicksToSeconds (now - lastFinishFrameTicks) < 0.001)
|
||||
return false;
|
||||
|
||||
bool ready = Pimpl::checkPaintReady();
|
||||
ready &= swap.canPaint();
|
||||
ready &= swap.canPresent();
|
||||
ready &= compositionTree.has_value();
|
||||
|
||||
return ready;
|
||||
}
|
||||
|
||||
void present()
|
||||
{
|
||||
JUCE_D2DMETRICS_SCOPED_ELAPSED_TIME (getMetrics(), present1Duration);
|
||||
|
||||
if (swap.getBuffer() == nullptr || deferredRepaintsCurrent.isEmpty())
|
||||
return;
|
||||
|
||||
auto const swapChainSize = swap.getSize();
|
||||
DXGI_PRESENT_PARAMETERS params{};
|
||||
|
||||
if (! deferredRepaintsCurrent.containsRectangle (swapChainSize))
|
||||
{
|
||||
// Allocate enough memory for the array of dirty rectangles
|
||||
dirtyRectangles.resize ((size_t) deferredRepaintsCurrent.getNumRectangles());
|
||||
|
||||
// Fill the array of dirty rectangles, intersecting each paint area with the swap chain buffer
|
||||
params.pDirtyRects = dirtyRectangles.data();
|
||||
params.DirtyRectsCount = 0;
|
||||
|
||||
for (const auto& area : deferredRepaintsCurrent)
|
||||
{
|
||||
const auto intersection = area.getIntersection (swapChainSize);
|
||||
|
||||
if (! intersection.isEmpty())
|
||||
params.pDirtyRects[params.DirtyRectsCount++] = D2DUtilities::toRECT (intersection);
|
||||
}
|
||||
}
|
||||
|
||||
// Present the freshly painted buffer
|
||||
const auto hr = swap.getChain()->Present1 (swap.presentSyncInterval,
|
||||
swap.presentFlags,
|
||||
¶ms);
|
||||
if (FAILED (hr))
|
||||
{
|
||||
jassertfalse;
|
||||
return;
|
||||
}
|
||||
|
||||
swap.didPresent();
|
||||
|
||||
JUCE_TRACE_LOG_D2D_PAINT_CALL (etw::direct2dHwndPaintEnd, getFrameId());
|
||||
}
|
||||
|
||||
JUCE_DECLARE_WEAK_REFERENCEABLE (HwndPimpl)
|
||||
|
||||
public:
|
||||
HwndPimpl (Direct2DHwndContext& ownerIn, HWND hwndIn)
|
||||
: Pimpl (ownerIn),
|
||||
hwnd (hwndIn)
|
||||
{
|
||||
}
|
||||
|
||||
~HwndPimpl() override = default;
|
||||
|
||||
void handleShowWindow()
|
||||
{
|
||||
// One of the trickier problems was determining when Direct2D & DXGI resources can be safely created;
|
||||
// that's not really spelled out in the documentation.
|
||||
// This method is called when the component peer receives WM_SHOWWINDOW
|
||||
prepare();
|
||||
deferredRepaintsNext = getClientRect();
|
||||
}
|
||||
|
||||
Rectangle<int> getClientRect() const
|
||||
{
|
||||
RECT clientRect;
|
||||
GetClientRect (hwnd, &clientRect);
|
||||
|
||||
return Rectangle<int>::leftTopRightBottom (clientRect.left,
|
||||
clientRect.top,
|
||||
clientRect.right,
|
||||
clientRect.bottom);
|
||||
}
|
||||
|
||||
Rectangle<int> getFrameSize() const override
|
||||
{
|
||||
return getClientRect();
|
||||
}
|
||||
|
||||
ComSmartPtr<ID2D1DeviceContext1> getDeviceContext() const override
|
||||
{
|
||||
return deviceContext;
|
||||
}
|
||||
|
||||
ComSmartPtr<ID2D1Image> getDeviceContextTarget() const override
|
||||
{
|
||||
return swap.getBuffer();
|
||||
}
|
||||
|
||||
ComSmartPtr<IDWriteRenderingParams> getDefaultTextRenderingParams() const override
|
||||
{
|
||||
if (auto monitor = MonitorFromWindow (hwnd, MONITOR_DEFAULTTONULL))
|
||||
{
|
||||
ComSmartPtr<IDWriteRenderingParams> result;
|
||||
getDirectWriteFactory()->CreateMonitorRenderingParams (monitor, result.resetAndGetPointerAddress());
|
||||
|
||||
if (result != nullptr)
|
||||
return result;
|
||||
}
|
||||
|
||||
return Pimpl::getDefaultTextRenderingParams();
|
||||
}
|
||||
|
||||
void setSize (Rectangle<int> size)
|
||||
{
|
||||
if (size == swap.getSize() || size.isEmpty())
|
||||
return;
|
||||
|
||||
// Require the entire window to be repainted
|
||||
deferredRepaintsNext = size;
|
||||
|
||||
InvalidateRect (hwnd, nullptr, TRUE);
|
||||
|
||||
// Resize/scale the swap chain
|
||||
prepare();
|
||||
|
||||
auto hr = swap.resize (size);
|
||||
jassert (SUCCEEDED (hr));
|
||||
if (FAILED (hr))
|
||||
teardown();
|
||||
}
|
||||
|
||||
void addDeferredRepaint (Rectangle<int> deferredRepaint)
|
||||
{
|
||||
deferredRepaintsNext.add (deferredRepaint);
|
||||
|
||||
JUCE_TRACE_EVENT_INT_RECT (etw::repaint, etw::paintKeyword, deferredRepaint);
|
||||
}
|
||||
|
||||
SavedState* startFrame() override
|
||||
{
|
||||
setSize (getClientRect());
|
||||
|
||||
if (deferredRepaintsNext.isEmpty())
|
||||
return nullptr;
|
||||
|
||||
auto* savedState = Pimpl::startFrame();
|
||||
|
||||
if (savedState == nullptr)
|
||||
return nullptr;
|
||||
|
||||
std::swap (deferredRepaintsNext, deferredRepaintsCurrent);
|
||||
deferredRepaintsNext.clear();
|
||||
|
||||
JUCE_TRACE_LOG_D2D_PAINT_CALL (etw::direct2dHwndPaintStart, getFrameId());
|
||||
|
||||
return savedState;
|
||||
}
|
||||
|
||||
HRESULT finishFrame() override
|
||||
{
|
||||
const auto result = Pimpl::finishFrame();
|
||||
present();
|
||||
lastFinishFrameTicks = Time::getHighResolutionTicks();
|
||||
return result;
|
||||
}
|
||||
|
||||
Image createSnapshot() const
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
|
||||
|
||||
// This won't capture child windows. Perhaps a better approach would be to use
|
||||
// IGraphicsCaptureItemInterop, although this is only supported on Windows 10 v1903+
|
||||
|
||||
if (deviceContext == nullptr)
|
||||
return {};
|
||||
|
||||
const auto buffer = swap.getBuffer();
|
||||
|
||||
if (buffer == nullptr)
|
||||
return {};
|
||||
|
||||
// Create the bitmap to receive the snapshot
|
||||
D2D1_BITMAP_PROPERTIES1 bitmapProperties{};
|
||||
bitmapProperties.bitmapOptions = D2D1_BITMAP_OPTIONS_TARGET;
|
||||
bitmapProperties.pixelFormat = buffer->GetPixelFormat();
|
||||
|
||||
const auto swapRect = swap.getSize();
|
||||
const auto size = D2D1::SizeU ((UINT32) swapRect.getWidth(), (UINT32) swapRect.getHeight());
|
||||
|
||||
ComSmartPtr<ID2D1Bitmap1> snapshot;
|
||||
|
||||
auto hr = deviceContext->CreateBitmap (size,
|
||||
nullptr,
|
||||
0,
|
||||
bitmapProperties,
|
||||
snapshot.resetAndGetPointerAddress());
|
||||
|
||||
if (FAILED (hr))
|
||||
return {};
|
||||
|
||||
swap.getChain()->Present (0, DXGI_PRESENT_DO_NOT_WAIT);
|
||||
|
||||
// Copy the swap chain buffer to the bitmap snapshot
|
||||
D2D_POINT_2U p { 0, 0 };
|
||||
const auto sourceRect = D2DUtilities::toRECT_U (swapRect);
|
||||
|
||||
hr = snapshot->CopyFromBitmap (&p, buffer, &sourceRect);
|
||||
|
||||
if (FAILED (hr))
|
||||
return {};
|
||||
|
||||
const Image result { new Direct2DPixelData { D2DUtilities::getDeviceForContext (deviceContext),
|
||||
snapshot } };
|
||||
|
||||
swap.getChain()->Present (0, DXGI_PRESENT_DO_NOT_WAIT);
|
||||
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
Direct2DHwndContext::Direct2DHwndContext (HWND windowHandle)
|
||||
{
|
||||
#if JUCE_DIRECT2D_METRICS
|
||||
metrics = new Direct2DMetrics { Direct2DMetricsHub::getInstance()->lock,
|
||||
"HWND " + String::toHexString ((pointer_sized_int) windowHandle),
|
||||
windowHandle };
|
||||
Direct2DMetricsHub::getInstance()->add (metrics);
|
||||
#endif
|
||||
|
||||
pimpl = std::make_unique<HwndPimpl> (*this, windowHandle);
|
||||
}
|
||||
|
||||
Direct2DHwndContext::~Direct2DHwndContext()
|
||||
{
|
||||
#if JUCE_DIRECT2D_METRICS
|
||||
Direct2DMetricsHub::getInstance()->remove (metrics);
|
||||
#endif
|
||||
}
|
||||
|
||||
Direct2DGraphicsContext::Pimpl* Direct2DHwndContext::getPimpl() const noexcept
|
||||
{
|
||||
return pimpl.get();
|
||||
}
|
||||
|
||||
void Direct2DHwndContext::handleShowWindow()
|
||||
{
|
||||
pimpl->handleShowWindow();
|
||||
}
|
||||
|
||||
void Direct2DHwndContext::addDeferredRepaint (Rectangle<int> deferredRepaint)
|
||||
{
|
||||
pimpl->addDeferredRepaint (deferredRepaint);
|
||||
}
|
||||
|
||||
Image Direct2DHwndContext::createSnapshot() const
|
||||
{
|
||||
return pimpl->createSnapshot();
|
||||
}
|
||||
|
||||
void Direct2DHwndContext::clearTargetBuffer()
|
||||
{
|
||||
applyPendingClipList();
|
||||
pimpl->getDeviceContext()->Clear();
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class Direct2DHwndContext : public Direct2DGraphicsContext
|
||||
{
|
||||
public:
|
||||
explicit Direct2DHwndContext (HWND windowHandle);
|
||||
~Direct2DHwndContext() override;
|
||||
|
||||
void handleShowWindow();
|
||||
|
||||
void addDeferredRepaint (Rectangle<int> deferredRepaint);
|
||||
|
||||
Image createSnapshot() const override;
|
||||
|
||||
private:
|
||||
struct HwndPimpl;
|
||||
std::unique_ptr<HwndPimpl> pimpl;
|
||||
|
||||
Pimpl* getPimpl() const noexcept override;
|
||||
void clearTargetBuffer() override;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DHwndContext)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,609 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
static Cursor createDraggingHandCursor();
|
||||
ComponentPeer* getPeerFor (::Window);
|
||||
|
||||
//==============================================================================
|
||||
class X11DragState
|
||||
{
|
||||
public:
|
||||
X11DragState() = default;
|
||||
|
||||
//==============================================================================
|
||||
bool isDragging() const noexcept
|
||||
{
|
||||
return dragging;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void handleExternalSelectionClear()
|
||||
{
|
||||
if (dragging)
|
||||
externalResetDragAndDrop();
|
||||
}
|
||||
|
||||
void handleExternalSelectionRequest (const XEvent& evt)
|
||||
{
|
||||
auto targetType = evt.xselectionrequest.target;
|
||||
|
||||
XEvent s;
|
||||
s.xselection.type = SelectionNotify;
|
||||
s.xselection.requestor = evt.xselectionrequest.requestor;
|
||||
s.xselection.selection = evt.xselectionrequest.selection;
|
||||
s.xselection.target = targetType;
|
||||
s.xselection.property = None;
|
||||
s.xselection.time = evt.xselectionrequest.time;
|
||||
|
||||
auto* display = getDisplay();
|
||||
|
||||
if (allowedTypes.contains (targetType))
|
||||
{
|
||||
s.xselection.property = evt.xselectionrequest.property;
|
||||
|
||||
X11Symbols::getInstance()->xChangeProperty (display, evt.xselectionrequest.requestor, evt.xselectionrequest.property,
|
||||
targetType, 8, PropModeReplace,
|
||||
reinterpret_cast<const unsigned char*> (textOrFiles.toRawUTF8()),
|
||||
(int) textOrFiles.getNumBytesAsUTF8());
|
||||
}
|
||||
|
||||
X11Symbols::getInstance()->xSendEvent (display, evt.xselectionrequest.requestor, True, 0, &s);
|
||||
}
|
||||
|
||||
void handleExternalDragAndDropStatus (const XClientMessageEvent& clientMsg)
|
||||
{
|
||||
if (expectingStatus)
|
||||
{
|
||||
expectingStatus = false;
|
||||
canDrop = false;
|
||||
silentRect = {};
|
||||
|
||||
const auto& atoms = getAtoms();
|
||||
|
||||
if ((clientMsg.data.l[1] & 1) != 0
|
||||
&& ((Atom) clientMsg.data.l[4] == atoms.XdndActionCopy
|
||||
|| (Atom) clientMsg.data.l[4] == atoms.XdndActionPrivate))
|
||||
{
|
||||
if ((clientMsg.data.l[1] & 2) == 0) // target requests silent rectangle
|
||||
silentRect.setBounds ((int) clientMsg.data.l[2] >> 16, (int) clientMsg.data.l[2] & 0xffff,
|
||||
(int) clientMsg.data.l[3] >> 16, (int) clientMsg.data.l[3] & 0xffff);
|
||||
|
||||
canDrop = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void handleExternalDragButtonReleaseEvent()
|
||||
{
|
||||
if (dragging)
|
||||
XWindowSystem::getInstance()->ungrabPointer();
|
||||
|
||||
if (canDrop)
|
||||
{
|
||||
sendExternalDragAndDropDrop();
|
||||
}
|
||||
else
|
||||
{
|
||||
sendExternalDragAndDropLeave();
|
||||
externalResetDragAndDrop();
|
||||
}
|
||||
}
|
||||
|
||||
void handleExternalDragMotionNotify()
|
||||
{
|
||||
auto* display = getDisplay();
|
||||
|
||||
auto newTargetWindow = externalFindDragTargetWindow (X11Symbols::getInstance()
|
||||
->xRootWindow (display,
|
||||
X11Symbols::getInstance()->xDefaultScreen (display)));
|
||||
|
||||
if (targetWindow != newTargetWindow)
|
||||
{
|
||||
if (targetWindow != None)
|
||||
sendExternalDragAndDropLeave();
|
||||
|
||||
canDrop = false;
|
||||
silentRect = {};
|
||||
|
||||
if (newTargetWindow == None)
|
||||
return;
|
||||
|
||||
xdndVersion = getDnDVersionForWindow (newTargetWindow);
|
||||
|
||||
if (xdndVersion == -1)
|
||||
return;
|
||||
|
||||
targetWindow = newTargetWindow;
|
||||
sendExternalDragAndDropEnter();
|
||||
}
|
||||
|
||||
if (! expectingStatus)
|
||||
sendExternalDragAndDropPosition();
|
||||
}
|
||||
|
||||
void handleDragAndDropPosition (const XClientMessageEvent& clientMsg, ComponentPeer* peer)
|
||||
{
|
||||
if (dragAndDropSourceWindow == 0)
|
||||
return;
|
||||
|
||||
dragAndDropSourceWindow = (::Window) clientMsg.data.l[0];
|
||||
|
||||
if (windowH == 0)
|
||||
windowH = (::Window) peer->getNativeHandle();
|
||||
|
||||
const auto& displays = Desktop::getInstance().getDisplays();
|
||||
const auto logicalPos = displays.physicalToLogical (Point ((int) clientMsg.data.l[2] >> 16,
|
||||
(int) clientMsg.data.l[2] & 0xffff).toFloat());
|
||||
const auto dropPos = detail::ScalingHelpers::screenPosToLocalPos (peer->getComponent(), logicalPos).roundToInt();
|
||||
|
||||
const auto& atoms = getAtoms();
|
||||
|
||||
auto targetAction = atoms.XdndActionCopy;
|
||||
|
||||
for (int i = numElementsInArray (atoms.allowedActions); --i >= 0;)
|
||||
{
|
||||
if ((Atom) clientMsg.data.l[4] == atoms.allowedActions[i])
|
||||
{
|
||||
targetAction = atoms.allowedActions[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
sendDragAndDropStatus (true, targetAction);
|
||||
|
||||
if (dragInfo.position != dropPos)
|
||||
{
|
||||
dragInfo.position = dropPos;
|
||||
|
||||
if (dragInfo.isEmpty())
|
||||
updateDraggedFileList (clientMsg, (::Window) peer->getNativeHandle());
|
||||
|
||||
if (! dragInfo.isEmpty())
|
||||
peer->handleDragMove (dragInfo);
|
||||
}
|
||||
}
|
||||
|
||||
void handleDragAndDropDrop (const XClientMessageEvent& clientMsg, ComponentPeer* peer)
|
||||
{
|
||||
if (dragInfo.isEmpty())
|
||||
{
|
||||
// no data, transaction finished in handleDragAndDropSelection()
|
||||
finishAfterDropDataReceived = true;
|
||||
updateDraggedFileList (clientMsg, (::Window) peer->getNativeHandle());
|
||||
}
|
||||
else
|
||||
{
|
||||
handleDragAndDropDataReceived(); // data was already received
|
||||
}
|
||||
}
|
||||
|
||||
void handleDragAndDropEnter (const XClientMessageEvent& clientMsg, ComponentPeer* peer)
|
||||
{
|
||||
dragInfo.clear();
|
||||
srcMimeTypeAtomList.clear();
|
||||
|
||||
dragAndDropCurrentMimeType = 0;
|
||||
auto dndCurrentVersion = (static_cast<unsigned long> (clientMsg.data.l[1]) & 0xff000000) >> 24;
|
||||
|
||||
if (dndCurrentVersion < 3 || dndCurrentVersion > XWindowSystemUtilities::Atoms::DndVersion)
|
||||
{
|
||||
dragAndDropSourceWindow = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& atoms = getAtoms();
|
||||
|
||||
dragAndDropSourceWindow = (::Window) clientMsg.data.l[0];
|
||||
|
||||
if ((clientMsg.data.l[1] & 1) != 0)
|
||||
{
|
||||
XWindowSystemUtilities::ScopedXLock xLock;
|
||||
|
||||
XWindowSystemUtilities::GetXProperty prop (getDisplay(),
|
||||
dragAndDropSourceWindow,
|
||||
atoms.XdndTypeList,
|
||||
0,
|
||||
0x8000000L,
|
||||
false,
|
||||
XA_ATOM);
|
||||
|
||||
if (prop.success && prop.actualType == XA_ATOM && prop.actualFormat == 32 && prop.numItems != 0)
|
||||
{
|
||||
auto* types = prop.data;
|
||||
|
||||
for (unsigned long i = 0; i < prop.numItems; ++i)
|
||||
{
|
||||
unsigned long type;
|
||||
memcpy (&type, types, sizeof (unsigned long));
|
||||
|
||||
if (type != None)
|
||||
srcMimeTypeAtomList.add (type);
|
||||
|
||||
types += sizeof (unsigned long);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (srcMimeTypeAtomList.isEmpty())
|
||||
{
|
||||
for (int i = 2; i < 5; ++i)
|
||||
if (clientMsg.data.l[i] != None)
|
||||
srcMimeTypeAtomList.add ((unsigned long) clientMsg.data.l[i]);
|
||||
|
||||
if (srcMimeTypeAtomList.isEmpty())
|
||||
{
|
||||
dragAndDropSourceWindow = 0;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
|
||||
for (int j = 0; j < numElementsInArray (atoms.allowedMimeTypes); ++j)
|
||||
if (srcMimeTypeAtomList[i] == atoms.allowedMimeTypes[j])
|
||||
dragAndDropCurrentMimeType = atoms.allowedMimeTypes[j];
|
||||
|
||||
handleDragAndDropPosition (clientMsg, peer);
|
||||
}
|
||||
|
||||
void handleDragAndDropExit()
|
||||
{
|
||||
if (auto* peer = getPeerFor (windowH))
|
||||
peer->handleDragExit (dragInfo);
|
||||
|
||||
resetDragAndDrop();
|
||||
}
|
||||
|
||||
void handleDragAndDropSelection (const XEvent& evt)
|
||||
{
|
||||
dragInfo.clear();
|
||||
|
||||
if (evt.xselection.property != None)
|
||||
{
|
||||
StringArray lines;
|
||||
|
||||
{
|
||||
MemoryBlock dropData;
|
||||
|
||||
for (;;)
|
||||
{
|
||||
XWindowSystemUtilities::GetXProperty prop (getDisplay(),
|
||||
evt.xany.window,
|
||||
evt.xselection.property,
|
||||
(long) (dropData.getSize() / 4),
|
||||
65536,
|
||||
false,
|
||||
AnyPropertyType);
|
||||
|
||||
if (! prop.success)
|
||||
break;
|
||||
|
||||
dropData.append (prop.data, (size_t) (prop.actualFormat / 8) * prop.numItems);
|
||||
|
||||
if (prop.bytesLeft <= 0)
|
||||
break;
|
||||
}
|
||||
|
||||
lines.addLines (dropData.toString());
|
||||
}
|
||||
|
||||
if (XWindowSystemUtilities::Atoms::isMimeTypeFile (getDisplay(), dragAndDropCurrentMimeType))
|
||||
{
|
||||
for (const auto& line : lines)
|
||||
{
|
||||
const auto escaped = line.replace ("+", "%2B").replace ("file://", String(), true);
|
||||
dragInfo.files.add (URL::removeEscapeChars (escaped));
|
||||
}
|
||||
|
||||
dragInfo.files.trim();
|
||||
dragInfo.files.removeEmptyStrings();
|
||||
}
|
||||
else
|
||||
{
|
||||
dragInfo.text = lines.joinIntoString ("\n");
|
||||
}
|
||||
|
||||
if (finishAfterDropDataReceived)
|
||||
handleDragAndDropDataReceived();
|
||||
}
|
||||
}
|
||||
|
||||
void externalResetDragAndDrop()
|
||||
{
|
||||
if (dragging)
|
||||
XWindowSystem::getInstance()->ungrabPointer();
|
||||
|
||||
NullCheckedInvocation::invoke (completionCallback);
|
||||
|
||||
dragging = false;
|
||||
}
|
||||
|
||||
bool externalDragInit (::Window window, bool text, const String& str, std::function<void()>&& cb)
|
||||
{
|
||||
windowH = window;
|
||||
isText = text;
|
||||
textOrFiles = str;
|
||||
targetWindow = windowH;
|
||||
completionCallback = std::move (cb);
|
||||
|
||||
auto* display = getDisplay();
|
||||
|
||||
allowedTypes.add (XWindowSystemUtilities::Atoms::getCreating (display, isText ? "text/plain" : "text/uri-list"));
|
||||
|
||||
XWindowSystemUtilities::ScopedXLock xLock;
|
||||
|
||||
if (XWindowSystem::getInstance()->grabPointerForExternalDrag (windowH, (Cursor) createDraggingHandCursor()))
|
||||
{
|
||||
const auto& atoms = getAtoms();
|
||||
|
||||
X11Symbols::getInstance()->xSetSelectionOwner (display, atoms.XdndSelection, windowH, CurrentTime);
|
||||
|
||||
// save the available types to XdndTypeList
|
||||
X11Symbols::getInstance()->xChangeProperty (display, windowH, atoms.XdndTypeList, XA_ATOM, 32, PropModeReplace,
|
||||
reinterpret_cast<const unsigned char*> (allowedTypes.getRawDataPointer()), allowedTypes.size());
|
||||
|
||||
dragging = true;
|
||||
xdndVersion = getDnDVersionForWindow (targetWindow);
|
||||
|
||||
sendExternalDragAndDropEnter();
|
||||
handleExternalDragMotionNotify();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
const XWindowSystemUtilities::Atoms& getAtoms() const noexcept { return XWindowSystem::getInstance()->getAtoms(); }
|
||||
::Display* getDisplay() const noexcept { return XWindowSystem::getInstance()->getDisplay(); }
|
||||
|
||||
//==============================================================================
|
||||
void sendDragAndDropMessage (XClientMessageEvent& msg)
|
||||
{
|
||||
auto* display = getDisplay();
|
||||
|
||||
msg.type = ClientMessage;
|
||||
msg.display = display;
|
||||
msg.window = dragAndDropSourceWindow;
|
||||
msg.format = 32;
|
||||
msg.data.l[0] = (long) windowH;
|
||||
|
||||
XWindowSystemUtilities::ScopedXLock xLock;
|
||||
X11Symbols::getInstance()->xSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
|
||||
}
|
||||
|
||||
bool sendExternalDragAndDropMessage (XClientMessageEvent& msg)
|
||||
{
|
||||
auto* display = getDisplay();
|
||||
|
||||
msg.type = ClientMessage;
|
||||
msg.display = display;
|
||||
msg.window = targetWindow;
|
||||
msg.format = 32;
|
||||
msg.data.l[0] = (long) windowH;
|
||||
|
||||
XWindowSystemUtilities::ScopedXLock xLock;
|
||||
return X11Symbols::getInstance()->xSendEvent (display, targetWindow, False, 0, (XEvent*) &msg) != 0;
|
||||
}
|
||||
|
||||
void sendExternalDragAndDropDrop()
|
||||
{
|
||||
XClientMessageEvent msg;
|
||||
zerostruct (msg);
|
||||
|
||||
msg.message_type = getAtoms().XdndDrop;
|
||||
msg.data.l[2] = CurrentTime;
|
||||
|
||||
sendExternalDragAndDropMessage (msg);
|
||||
}
|
||||
|
||||
void sendExternalDragAndDropEnter()
|
||||
{
|
||||
XClientMessageEvent msg;
|
||||
zerostruct (msg);
|
||||
|
||||
msg.message_type = getAtoms().XdndEnter;
|
||||
msg.data.l[1] = (xdndVersion << 24);
|
||||
|
||||
for (int i = 0; i < 3; ++i)
|
||||
msg.data.l[i + 2] = (long) allowedTypes[i];
|
||||
|
||||
sendExternalDragAndDropMessage (msg);
|
||||
}
|
||||
|
||||
void sendExternalDragAndDropPosition()
|
||||
{
|
||||
XClientMessageEvent msg;
|
||||
zerostruct (msg);
|
||||
|
||||
const auto& atoms = getAtoms();
|
||||
|
||||
msg.message_type = atoms.XdndPosition;
|
||||
|
||||
auto mousePos = Desktop::getInstance().getMousePosition();
|
||||
|
||||
if (silentRect.contains (mousePos)) // we've been asked to keep silent
|
||||
return;
|
||||
|
||||
mousePos = Desktop::getInstance().getDisplays().logicalToPhysical (mousePos.toFloat()).roundToInt();
|
||||
|
||||
msg.data.l[1] = 0;
|
||||
msg.data.l[2] = (mousePos.x << 16) | mousePos.y;
|
||||
msg.data.l[3] = CurrentTime;
|
||||
msg.data.l[4] = (long) atoms.XdndActionCopy; // this is all JUCE currently supports
|
||||
|
||||
expectingStatus = sendExternalDragAndDropMessage (msg);
|
||||
}
|
||||
|
||||
void sendDragAndDropStatus (bool acceptDrop, Atom dropAction)
|
||||
{
|
||||
XClientMessageEvent msg;
|
||||
zerostruct (msg);
|
||||
|
||||
msg.message_type = getAtoms().XdndStatus;
|
||||
msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
|
||||
msg.data.l[4] = (long) dropAction;
|
||||
|
||||
sendDragAndDropMessage (msg);
|
||||
}
|
||||
|
||||
void sendExternalDragAndDropLeave()
|
||||
{
|
||||
XClientMessageEvent msg;
|
||||
zerostruct (msg);
|
||||
|
||||
msg.message_type = getAtoms().XdndLeave;
|
||||
sendExternalDragAndDropMessage (msg);
|
||||
}
|
||||
|
||||
void sendDragAndDropFinish()
|
||||
{
|
||||
XClientMessageEvent msg;
|
||||
zerostruct (msg);
|
||||
|
||||
msg.message_type = getAtoms().XdndFinished;
|
||||
sendDragAndDropMessage (msg);
|
||||
}
|
||||
|
||||
void updateDraggedFileList (const XClientMessageEvent& clientMsg, ::Window requestor)
|
||||
{
|
||||
jassert (dragInfo.isEmpty());
|
||||
|
||||
if (dragAndDropSourceWindow != None && dragAndDropCurrentMimeType != None)
|
||||
{
|
||||
auto* display = getDisplay();
|
||||
|
||||
XWindowSystemUtilities::ScopedXLock xLock;
|
||||
X11Symbols::getInstance()->xConvertSelection (display, getAtoms().XdndSelection, dragAndDropCurrentMimeType,
|
||||
XWindowSystemUtilities::Atoms::getCreating (display, "JXSelectionWindowProperty"),
|
||||
requestor, (::Time) clientMsg.data.l[2]);
|
||||
}
|
||||
}
|
||||
|
||||
bool isWindowDnDAware (::Window w) const
|
||||
{
|
||||
int numProperties = 0;
|
||||
auto* properties = X11Symbols::getInstance()->xListProperties (getDisplay(), w, &numProperties);
|
||||
|
||||
bool dndAwarePropFound = false;
|
||||
|
||||
for (int i = 0; i < numProperties; ++i)
|
||||
if (properties[i] == getAtoms().XdndAware)
|
||||
dndAwarePropFound = true;
|
||||
|
||||
if (properties != nullptr)
|
||||
X11Symbols::getInstance()->xFree (properties);
|
||||
|
||||
return dndAwarePropFound;
|
||||
}
|
||||
|
||||
int getDnDVersionForWindow (::Window target)
|
||||
{
|
||||
XWindowSystemUtilities::GetXProperty prop (getDisplay(),
|
||||
target,
|
||||
getAtoms().XdndAware,
|
||||
0,
|
||||
2,
|
||||
false,
|
||||
AnyPropertyType);
|
||||
|
||||
if (prop.success && prop.data != nullptr && prop.actualFormat == 32 && prop.numItems == 1)
|
||||
return jmin ((int) prop.data[0], (int) XWindowSystemUtilities::Atoms::DndVersion);
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
::Window externalFindDragTargetWindow (::Window target)
|
||||
{
|
||||
if (target == None)
|
||||
return None;
|
||||
|
||||
if (isWindowDnDAware (target))
|
||||
return target;
|
||||
|
||||
::Window child, phonyWin;
|
||||
int phony;
|
||||
unsigned int uphony;
|
||||
|
||||
X11Symbols::getInstance()->xQueryPointer (getDisplay(), target, &phonyWin, &child, &phony, &phony, &phony, &phony, &uphony);
|
||||
|
||||
return externalFindDragTargetWindow (child);
|
||||
}
|
||||
|
||||
void handleDragAndDropDataReceived()
|
||||
{
|
||||
ComponentPeer::DragInfo dragInfoCopy (dragInfo);
|
||||
|
||||
sendDragAndDropFinish();
|
||||
resetDragAndDrop();
|
||||
|
||||
if (! dragInfoCopy.isEmpty())
|
||||
if (auto* peer = getPeerFor (windowH))
|
||||
peer->handleDragDrop (dragInfoCopy);
|
||||
}
|
||||
|
||||
void resetDragAndDrop()
|
||||
{
|
||||
dragInfo.clear();
|
||||
dragInfo.position = Point<int> (-1, -1);
|
||||
dragAndDropCurrentMimeType = 0;
|
||||
dragAndDropSourceWindow = 0;
|
||||
srcMimeTypeAtomList.clear();
|
||||
finishAfterDropDataReceived = false;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
::Window windowH = 0, targetWindow = 0, dragAndDropSourceWindow = 0;
|
||||
|
||||
int xdndVersion = -1;
|
||||
bool isText = false, dragging = false, expectingStatus = false, canDrop = false, finishAfterDropDataReceived = false;
|
||||
|
||||
Atom dragAndDropCurrentMimeType;
|
||||
Array<Atom> allowedTypes, srcMimeTypeAtomList;
|
||||
|
||||
ComponentPeer::DragInfo dragInfo;
|
||||
Rectangle<int> silentRect;
|
||||
String textOrFiles;
|
||||
|
||||
std::function<void()> completionCallback = nullptr;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_LEAK_DETECTOR (X11DragState)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,375 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
namespace DragAndDropHelpers
|
||||
{
|
||||
//==============================================================================
|
||||
struct JuceDropSource final : public ComBaseClassHelper<IDropSource>
|
||||
{
|
||||
JuceDropSource() = default;
|
||||
|
||||
JUCE_COMRESULT QueryContinueDrag (BOOL escapePressed, DWORD keys) override
|
||||
{
|
||||
if (escapePressed)
|
||||
return DRAGDROP_S_CANCEL;
|
||||
|
||||
if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
|
||||
return DRAGDROP_S_DROP;
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GiveFeedback (DWORD) override
|
||||
{
|
||||
return DRAGDROP_S_USEDEFAULTCURSORS;
|
||||
}
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
struct JuceEnumFormatEtc final : public ComBaseClassHelper<IEnumFORMATETC>
|
||||
{
|
||||
JuceEnumFormatEtc (const FORMATETC* f) : format (f) {}
|
||||
|
||||
JUCE_COMRESULT Clone (IEnumFORMATETC** result) override
|
||||
{
|
||||
if (result == nullptr)
|
||||
return E_POINTER;
|
||||
|
||||
auto newOne = new JuceEnumFormatEtc (format);
|
||||
newOne->index = index;
|
||||
*result = newOne;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched) override
|
||||
{
|
||||
if (pceltFetched != nullptr)
|
||||
*pceltFetched = 0;
|
||||
else if (celt != 1)
|
||||
return S_FALSE;
|
||||
|
||||
if (index == 0 && celt > 0 && lpFormatEtc != nullptr)
|
||||
{
|
||||
copyFormatEtc (lpFormatEtc [0], *format);
|
||||
++index;
|
||||
|
||||
if (pceltFetched != nullptr)
|
||||
*pceltFetched = 1;
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
return S_FALSE;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT Skip (ULONG celt) override
|
||||
{
|
||||
if (index + (int) celt >= 1)
|
||||
return S_FALSE;
|
||||
|
||||
index += (int) celt;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT Reset() override
|
||||
{
|
||||
index = 0;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
private:
|
||||
const FORMATETC* const format;
|
||||
int index = 0;
|
||||
|
||||
static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
|
||||
{
|
||||
dest = source;
|
||||
|
||||
if (source.ptd != nullptr)
|
||||
{
|
||||
dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
|
||||
|
||||
if (dest.ptd != nullptr)
|
||||
*(dest.ptd) = *(source.ptd);
|
||||
}
|
||||
}
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class JuceDataObject final : public ComBaseClassHelper<IDataObject>
|
||||
{
|
||||
public:
|
||||
JuceDataObject (const FORMATETC* f, const STGMEDIUM* m)
|
||||
: format (f), medium (m)
|
||||
{
|
||||
}
|
||||
|
||||
~JuceDataObject() override
|
||||
{
|
||||
jassert (refCount == 0);
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium) override
|
||||
{
|
||||
if ((pFormatEtc->tymed & format->tymed) != 0
|
||||
&& pFormatEtc->cfFormat == format->cfFormat
|
||||
&& pFormatEtc->dwAspect == format->dwAspect)
|
||||
{
|
||||
pMedium->tymed = format->tymed;
|
||||
pMedium->pUnkForRelease = nullptr;
|
||||
|
||||
if (format->tymed == TYMED_HGLOBAL)
|
||||
{
|
||||
auto len = GlobalSize (medium->hGlobal);
|
||||
void* const src = GlobalLock (medium->hGlobal);
|
||||
void* const dst = GlobalAlloc (GMEM_FIXED, len);
|
||||
|
||||
if (src != nullptr && dst != nullptr)
|
||||
memcpy (dst, src, len);
|
||||
|
||||
GlobalUnlock (medium->hGlobal);
|
||||
|
||||
pMedium->hGlobal = dst;
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
|
||||
return DV_E_FORMATETC;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT QueryGetData (FORMATETC* f) override
|
||||
{
|
||||
if (f == nullptr)
|
||||
return E_INVALIDARG;
|
||||
|
||||
if (f->tymed == format->tymed
|
||||
&& f->cfFormat == format->cfFormat
|
||||
&& f->dwAspect == format->dwAspect)
|
||||
return S_OK;
|
||||
|
||||
return DV_E_FORMATETC;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut) override
|
||||
{
|
||||
pFormatEtcOut->ptd = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT EnumFormatEtc (DWORD direction, IEnumFORMATETC** result) override
|
||||
{
|
||||
if (result == nullptr)
|
||||
return E_POINTER;
|
||||
|
||||
if (direction == DATADIR_GET)
|
||||
{
|
||||
*result = new JuceEnumFormatEtc (format);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
*result = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
JUCE_COMRESULT GetDataHere (FORMATETC*, STGMEDIUM*) override { return DATA_E_FORMATETC; }
|
||||
JUCE_COMRESULT SetData (FORMATETC*, STGMEDIUM*, BOOL) override { return E_NOTIMPL; }
|
||||
JUCE_COMRESULT DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) override { return OLE_E_ADVISENOTSUPPORTED; }
|
||||
JUCE_COMRESULT DUnadvise (DWORD) override { return E_NOTIMPL; }
|
||||
JUCE_COMRESULT EnumDAdvise (IEnumSTATDATA**) override { return OLE_E_ADVISENOTSUPPORTED; }
|
||||
|
||||
private:
|
||||
const FORMATETC* const format;
|
||||
const STGMEDIUM* const medium;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (JuceDataObject)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
static HDROP createHDrop (const StringArray& fileNames)
|
||||
{
|
||||
size_t totalBytes = 0;
|
||||
for (int i = fileNames.size(); --i >= 0;)
|
||||
totalBytes += CharPointer_UTF16::getBytesRequiredFor (fileNames[i].getCharPointer()) + sizeof (WCHAR);
|
||||
|
||||
struct Deleter
|
||||
{
|
||||
void operator() (void* ptr) const noexcept { GlobalFree (ptr); }
|
||||
};
|
||||
|
||||
auto hDrop = std::unique_ptr<void, Deleter> ((HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof (DROPFILES) + totalBytes + 4));
|
||||
|
||||
if (hDrop != nullptr)
|
||||
{
|
||||
auto pDropFiles = (LPDROPFILES) GlobalLock (hDrop.get());
|
||||
|
||||
if (pDropFiles == nullptr)
|
||||
return nullptr;
|
||||
|
||||
pDropFiles->pFiles = sizeof (DROPFILES);
|
||||
pDropFiles->fWide = true;
|
||||
|
||||
auto* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
|
||||
|
||||
for (int i = 0; i < fileNames.size(); ++i)
|
||||
{
|
||||
auto bytesWritten = fileNames[i].copyToUTF16 (fname, 2048);
|
||||
fname = reinterpret_cast<WCHAR*> (addBytesToPointer (fname, bytesWritten));
|
||||
}
|
||||
|
||||
*fname = 0;
|
||||
|
||||
GlobalUnlock (hDrop.get());
|
||||
}
|
||||
|
||||
return static_cast<HDROP> (hDrop.release());
|
||||
}
|
||||
|
||||
struct DragAndDropJob final : public ThreadPoolJob
|
||||
{
|
||||
DragAndDropJob (FORMATETC f, STGMEDIUM m, DWORD d, std::function<void()>&& cb)
|
||||
: ThreadPoolJob ("DragAndDrop"),
|
||||
format (f), medium (m), whatToDo (d),
|
||||
completionCallback (std::move (cb))
|
||||
{
|
||||
}
|
||||
|
||||
JobStatus runJob() override
|
||||
{
|
||||
[[maybe_unused]] const auto result = OleInitialize (nullptr);
|
||||
|
||||
auto* source = new JuceDropSource();
|
||||
auto* data = new JuceDataObject (&format, &medium);
|
||||
|
||||
DWORD effect;
|
||||
DoDragDrop (data, source, whatToDo, &effect);
|
||||
|
||||
data->Release();
|
||||
source->Release();
|
||||
|
||||
OleUninitialize();
|
||||
|
||||
if (completionCallback != nullptr)
|
||||
MessageManager::callAsync (std::move (completionCallback));
|
||||
|
||||
return jobHasFinished;
|
||||
}
|
||||
|
||||
FORMATETC format;
|
||||
STGMEDIUM medium;
|
||||
DWORD whatToDo;
|
||||
|
||||
std::function<void()> completionCallback;
|
||||
};
|
||||
|
||||
class ThreadPoolHolder final : private DeletedAtShutdown
|
||||
{
|
||||
public:
|
||||
ThreadPoolHolder() = default;
|
||||
|
||||
~ThreadPoolHolder()
|
||||
{
|
||||
// Wait forever if there's a job running. The user needs to cancel the transfer
|
||||
// in the GUI.
|
||||
pool.removeAllJobs (true, -1);
|
||||
|
||||
clearSingletonInstance();
|
||||
}
|
||||
|
||||
JUCE_DECLARE_SINGLETON_SINGLETHREADED_INLINE (ThreadPoolHolder, false)
|
||||
|
||||
// We need to make sure we don't do simultaneous text and file drag and drops,
|
||||
// so use a pool that can only run a single job.
|
||||
ThreadPool pool { ThreadPoolOptions{}.withNumberOfThreads (1) };
|
||||
};
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove,
|
||||
Component*, std::function<void()> callback)
|
||||
{
|
||||
if (files.isEmpty())
|
||||
return false;
|
||||
|
||||
FORMATETC format = { CF_HDROP, nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
|
||||
STGMEDIUM medium = { TYMED_HGLOBAL, { nullptr }, nullptr };
|
||||
|
||||
medium.hGlobal = DragAndDropHelpers::createHDrop (files);
|
||||
|
||||
auto& pool = DragAndDropHelpers::ThreadPoolHolder::getInstance()->pool;
|
||||
pool.addJob (new DragAndDropHelpers::DragAndDropJob (format, medium,
|
||||
canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE) : DROPEFFECT_COPY,
|
||||
std::move (callback)),
|
||||
true);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DragAndDropContainer::performExternalDragDropOfText (const String& text, Component*, std::function<void()> callback)
|
||||
{
|
||||
if (text.isEmpty())
|
||||
return false;
|
||||
|
||||
FORMATETC format = { CF_TEXT, nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
|
||||
STGMEDIUM medium = { TYMED_HGLOBAL, { nullptr }, nullptr };
|
||||
|
||||
auto numBytes = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer());
|
||||
|
||||
medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, numBytes + 2);
|
||||
|
||||
if (medium.hGlobal == nullptr)
|
||||
return false;
|
||||
|
||||
auto* data = static_cast<WCHAR*> (GlobalLock (medium.hGlobal));
|
||||
|
||||
text.copyToUTF16 (data, numBytes + 2);
|
||||
format.cfFormat = CF_UNICODETEXT;
|
||||
|
||||
GlobalUnlock (medium.hGlobal);
|
||||
|
||||
auto& pool = DragAndDropHelpers::ThreadPoolHolder::getInstance()->pool;
|
||||
pool.addJob (new DragAndDropHelpers::DragAndDropJob (format,
|
||||
medium,
|
||||
DROPEFFECT_COPY | DROPEFFECT_MOVE,
|
||||
std::move (callback)),
|
||||
true);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,284 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
|
||||
METHOD (getItemCount, "getItemCount", "()I") \
|
||||
METHOD (getItemAt, "getItemAt", "(I)Landroid/content/ClipData$Item;")
|
||||
|
||||
DECLARE_JNI_CLASS (ClipData, "android/content/ClipData")
|
||||
#undef JNI_CLASS_MEMBERS
|
||||
|
||||
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
|
||||
METHOD (getUri, "getUri", "()Landroid/net/Uri;")
|
||||
|
||||
DECLARE_JNI_CLASS (ClipDataItem, "android/content/ClipData$Item")
|
||||
#undef JNI_CLASS_MEMBERS
|
||||
|
||||
class FileChooser::Native final : public FileChooser::Pimpl
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
Native (FileChooser& fileChooser, int flags) : owner (fileChooser)
|
||||
{
|
||||
if (currentFileChooser == nullptr)
|
||||
{
|
||||
currentFileChooser = this;
|
||||
auto* env = getEnv();
|
||||
|
||||
auto saveMode = ((flags & FileBrowserComponent::saveMode) != 0);
|
||||
auto selectsDirectories = ((flags & FileBrowserComponent::canSelectDirectories) != 0);
|
||||
auto canSelectMultiple = ((flags & FileBrowserComponent::canSelectMultipleItems) != 0);
|
||||
|
||||
// You cannot save a directory
|
||||
jassert (! (saveMode && selectsDirectories));
|
||||
|
||||
const char* action = (selectsDirectories ? "android.intent.action.OPEN_DOCUMENT_TREE"
|
||||
: (saveMode ? "android.intent.action.CREATE_DOCUMENT"
|
||||
: "android.intent.action.OPEN_DOCUMENT"));
|
||||
|
||||
|
||||
intent = GlobalRef (LocalRef<jobject> (env->NewObject (AndroidIntent, AndroidIntent.constructWithString,
|
||||
javaString (action).get())));
|
||||
|
||||
if (owner.startingFile != File())
|
||||
{
|
||||
if (saveMode && (! owner.startingFile.isDirectory()))
|
||||
{
|
||||
LocalRef { env->CallObjectMethod (intent.get(), AndroidIntent.putExtraString,
|
||||
javaString ("android.intent.extra.TITLE").get(),
|
||||
javaString (owner.startingFile.getFileName()).get()) };
|
||||
}
|
||||
|
||||
|
||||
URL url (owner.startingFile);
|
||||
LocalRef<jobject> uri (env->CallStaticObjectMethod (AndroidUri, AndroidUri.parse,
|
||||
javaString (url.toString (true)).get()));
|
||||
|
||||
if (uri)
|
||||
{
|
||||
LocalRef { env->CallObjectMethod (intent.get(), AndroidIntent.putExtraParcelable,
|
||||
javaString ("android.provider.extra.INITIAL_URI").get(),
|
||||
uri.get()) };
|
||||
}
|
||||
}
|
||||
|
||||
LocalRef { env->CallObjectMethod (intent.get(),
|
||||
AndroidIntent.putExtraBool,
|
||||
javaString ("android.intent.extra.ALLOW_MULTIPLE").get(),
|
||||
canSelectMultiple) };
|
||||
|
||||
if (! selectsDirectories)
|
||||
{
|
||||
LocalRef { env->CallObjectMethod (intent.get(), AndroidIntent.addCategory,
|
||||
javaString ("android.intent.category.OPENABLE").get()) };
|
||||
|
||||
auto mimeTypes = convertFiltersToMimeTypes (owner.filters);
|
||||
|
||||
if (mimeTypes.size() == 1)
|
||||
{
|
||||
LocalRef { env->CallObjectMethod (intent.get(),
|
||||
AndroidIntent.setType,
|
||||
javaString (mimeTypes[0]).get()) };
|
||||
}
|
||||
else
|
||||
{
|
||||
String mimeGroup = "*";
|
||||
|
||||
if (mimeTypes.size() > 0)
|
||||
{
|
||||
mimeGroup = mimeTypes[0].upToFirstOccurrenceOf ("/", false, false);
|
||||
auto allMimeTypesHaveSameGroup = true;
|
||||
|
||||
LocalRef<jobjectArray> jMimeTypes (env->NewObjectArray (mimeTypes.size(), JavaString,
|
||||
javaString ("").get()));
|
||||
|
||||
for (int i = 0; i < mimeTypes.size(); ++i)
|
||||
{
|
||||
env->SetObjectArrayElement (jMimeTypes.get(), i, javaString (mimeTypes[i]).get());
|
||||
|
||||
if (mimeGroup != mimeTypes[i].upToFirstOccurrenceOf ("/", false, false))
|
||||
allMimeTypesHaveSameGroup = false;
|
||||
}
|
||||
|
||||
LocalRef { env->CallObjectMethod (intent.get(), AndroidIntent.putExtraStrings,
|
||||
javaString ("android.intent.extra.MIME_TYPES").get(),
|
||||
jMimeTypes.get()) };
|
||||
|
||||
if (! allMimeTypesHaveSameGroup)
|
||||
mimeGroup = "*";
|
||||
}
|
||||
|
||||
LocalRef { env->CallObjectMethod (intent.get(),
|
||||
AndroidIntent.setType,
|
||||
javaString (mimeGroup + "/*").get()) };
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
jassertfalse; // there can only be a single file chooser
|
||||
}
|
||||
|
||||
~Native() override
|
||||
{
|
||||
masterReference.clear();
|
||||
currentFileChooser = nullptr;
|
||||
}
|
||||
|
||||
void runModally() override
|
||||
{
|
||||
// Android does not support modal file choosers
|
||||
jassertfalse;
|
||||
}
|
||||
|
||||
void launch() override
|
||||
{
|
||||
auto* env = getEnv();
|
||||
|
||||
if (currentFileChooser != nullptr)
|
||||
{
|
||||
startAndroidActivityForResult (LocalRef<jobject> (env->NewLocalRef (intent.get())), /*READ_REQUEST_CODE*/ 42,
|
||||
[myself = WeakReference<Native> { this }] (int requestCode, int resultCode, LocalRef<jobject> intentData) mutable
|
||||
{
|
||||
if (myself != nullptr)
|
||||
myself->onActivityResult (requestCode, resultCode, intentData);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
jassertfalse; // There is already a file chooser running
|
||||
}
|
||||
}
|
||||
|
||||
void onActivityResult (int /*requestCode*/, int resultCode, const LocalRef<jobject>& intentData)
|
||||
{
|
||||
currentFileChooser = nullptr;
|
||||
auto* env = getEnv();
|
||||
|
||||
const auto getUrls = [&]() -> Array<URL>
|
||||
{
|
||||
if (resultCode != /*Activity.RESULT_OK*/ -1 || intentData == nullptr)
|
||||
return {};
|
||||
|
||||
Array<URL> chosenURLs;
|
||||
|
||||
const auto addUrl = [env, &chosenURLs] (jobject uri)
|
||||
{
|
||||
if (LocalRef jStr { (jstring) env->CallObjectMethod (uri, JavaObject.toString) })
|
||||
chosenURLs.add (URL (juceString (env, jStr)));
|
||||
};
|
||||
|
||||
if (LocalRef<jobject> clipData { env->CallObjectMethod (intentData.get(), AndroidIntent.getClipData) })
|
||||
{
|
||||
const auto count = env->CallIntMethod (clipData.get(), ClipData.getItemCount);
|
||||
|
||||
for (auto i = 0; i < count; ++i)
|
||||
{
|
||||
if (LocalRef<jobject> item { env->CallObjectMethod (clipData.get(), ClipData.getItemAt, i) })
|
||||
{
|
||||
if (LocalRef<jobject> itemUri { env->CallObjectMethod (item.get(), ClipDataItem.getUri) })
|
||||
addUrl (itemUri.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (LocalRef<jobject> uri { env->CallObjectMethod (intentData.get(), AndroidIntent.getData )})
|
||||
{
|
||||
addUrl (uri.get());
|
||||
}
|
||||
|
||||
return chosenURLs;
|
||||
};
|
||||
|
||||
owner.finished (getUrls());
|
||||
}
|
||||
|
||||
static Native* currentFileChooser;
|
||||
|
||||
static StringArray convertFiltersToMimeTypes (const String& fileFilters)
|
||||
{
|
||||
StringArray result;
|
||||
auto wildcards = StringArray::fromTokens (fileFilters, ";", "");
|
||||
|
||||
for (auto wildcard : wildcards)
|
||||
{
|
||||
if (wildcard.upToLastOccurrenceOf (".", false, false) == "*")
|
||||
{
|
||||
auto extension = wildcard.fromLastOccurrenceOf (".", false, false);
|
||||
|
||||
result.addArray (detail::MimeTypeTable::getMimeTypesForFileExtension (extension));
|
||||
}
|
||||
}
|
||||
|
||||
result.removeDuplicates (false);
|
||||
return result;
|
||||
}
|
||||
|
||||
private:
|
||||
JUCE_DECLARE_WEAK_REFERENCEABLE (Native)
|
||||
|
||||
FileChooser& owner;
|
||||
GlobalRef intent;
|
||||
};
|
||||
|
||||
FileChooser::Native* FileChooser::Native::currentFileChooser = nullptr;
|
||||
|
||||
std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags,
|
||||
FilePreviewComponent*)
|
||||
{
|
||||
if (FileChooser::Native::currentFileChooser == nullptr)
|
||||
return std::make_shared<FileChooser::Native> (owner, flags);
|
||||
|
||||
// there can only be one file chooser on Android at a once
|
||||
jassertfalse;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool FileChooser::isPlatformDialogAvailable()
|
||||
{
|
||||
#if JUCE_DISABLE_NATIVE_FILECHOOSERS
|
||||
return false;
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
void FileChooser::registerCustomMimeTypeForFileExtension (const String& mimeType,
|
||||
const String& fileExtension)
|
||||
{
|
||||
detail::MimeTypeTable::registerCustomMimeTypeForFileExtension (mimeType, fileExtension);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,427 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
@interface FileChooserControllerClass : UIDocumentPickerViewController
|
||||
- (void) setParent: (std::shared_ptr<FileChooser::Native>) ptr;
|
||||
@end
|
||||
|
||||
@interface FileChooserDelegateClass : NSObject<UIDocumentPickerDelegate, UIAdaptivePresentationControllerDelegate>
|
||||
- (void) setParent: (std::shared_ptr<FileChooser::Native>) owner;
|
||||
@end
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class FileChooser::Native final : public FileChooser::Pimpl,
|
||||
public detail::NativeModalWrapperComponent,
|
||||
public std::enable_shared_from_this<Native>
|
||||
{
|
||||
public:
|
||||
static std::shared_ptr<Native> make (FileChooser& fileChooser, int flags)
|
||||
{
|
||||
std::shared_ptr<Native> result { new Native (fileChooser, flags) };
|
||||
/* Must be called after forming a shared_ptr to an instance of this class.
|
||||
Note that we can't call this directly inside the class constructor, because
|
||||
the owning shared_ptr might not yet exist.
|
||||
*/
|
||||
[result->controller.get() setParent: result];
|
||||
[result->delegate.get() setParent: result];
|
||||
return result;
|
||||
}
|
||||
|
||||
void launch() override
|
||||
{
|
||||
jassert (shared_from_this() != nullptr);
|
||||
|
||||
/* Normally, when deleteWhenDismissed is true, the modal component manager will keep a copy of a raw pointer
|
||||
to our component and delete it when the modal state has ended. However, this is incompatible with
|
||||
our class being tracked by shared_ptr as it will force delete our class regardless of the current
|
||||
reference count. On the other hand, it's important that the modal manager keeps a reference as it can
|
||||
sometimes be the only reference to our class.
|
||||
|
||||
To do this, we set deleteWhenDismissed to false so that the modal component manager does not delete
|
||||
our class. Instead, we pass in a lambda which captures a shared_ptr to ourselves to increase the
|
||||
reference count while the component is modal.
|
||||
*/
|
||||
enterModalState (true,
|
||||
ModalCallbackFunction::create ([_self = shared_from_this()] (int) {}),
|
||||
false);
|
||||
}
|
||||
|
||||
void runModally() override
|
||||
{
|
||||
#if JUCE_MODAL_LOOPS_PERMITTED
|
||||
launch();
|
||||
runModalLoop();
|
||||
#else
|
||||
jassertfalse;
|
||||
#endif
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void didPickDocumentsAtURLs (NSArray<NSURL*>* urls)
|
||||
{
|
||||
const auto isWriting = (savedFlags & FileBrowserComponent::saveMode) != 0;
|
||||
const auto accessOptions = isWriting ? 0 : NSFileCoordinatorReadingWithoutChanges;
|
||||
|
||||
auto* fileCoordinator = [[[NSFileCoordinator alloc] initWithFilePresenter: nil] autorelease];
|
||||
auto* intents = [[[NSMutableArray alloc] init] autorelease];
|
||||
|
||||
for (NSURL* url in urls)
|
||||
{
|
||||
auto* fileAccessIntent = isWriting
|
||||
? [NSFileAccessIntent writingIntentWithURL: url options: accessOptions]
|
||||
: [NSFileAccessIntent readingIntentWithURL: url options: accessOptions];
|
||||
[intents addObject: fileAccessIntent];
|
||||
}
|
||||
|
||||
auto strong = shared_from_this();
|
||||
|
||||
[fileCoordinator coordinateAccessWithIntents: intents queue: [NSOperationQueue mainQueue] byAccessor: ^(NSError* err)
|
||||
{
|
||||
if (err != nil)
|
||||
{
|
||||
[[maybe_unused]] auto desc = [err localizedDescription];
|
||||
jassertfalse;
|
||||
return;
|
||||
}
|
||||
|
||||
Array<URL> result;
|
||||
|
||||
for (NSURL* url in urls)
|
||||
{
|
||||
[url startAccessingSecurityScopedResource];
|
||||
|
||||
NSError* error = nil;
|
||||
|
||||
auto* bookmark = [url bookmarkDataWithOptions: 0
|
||||
includingResourceValuesForKeys: nil
|
||||
relativeToURL: nil
|
||||
error: &error];
|
||||
|
||||
[bookmark retain];
|
||||
|
||||
[url stopAccessingSecurityScopedResource];
|
||||
|
||||
URL juceUrl (nsStringToJuce ([url absoluteString]));
|
||||
|
||||
if (error == nil)
|
||||
{
|
||||
setURLBookmark (juceUrl, (void*) bookmark);
|
||||
}
|
||||
else
|
||||
{
|
||||
[[maybe_unused]] auto desc = [error localizedDescription];
|
||||
jassertfalse;
|
||||
}
|
||||
|
||||
result.add (std::move (juceUrl));
|
||||
}
|
||||
|
||||
strong->passResultsToInitiator (std::move (result));
|
||||
}];
|
||||
}
|
||||
|
||||
void didPickDocumentAtURL (NSURL* url)
|
||||
{
|
||||
didPickDocumentsAtURLs (@[url]);
|
||||
}
|
||||
|
||||
void pickerWasCancelled()
|
||||
{
|
||||
passResultsToInitiator ({});
|
||||
}
|
||||
|
||||
private:
|
||||
UIViewController* getViewController() const override { return controller.get(); }
|
||||
|
||||
struct CreateSaveControllerTrait
|
||||
{
|
||||
API_AVAILABLE (ios (14))
|
||||
static FileChooserControllerClass* newFn (NSURL* url, const File& currentFileOrDirectory)
|
||||
{
|
||||
return [[FileChooserControllerClass alloc] initForExportingURLs: @[url] asCopy: currentFileOrDirectory.existsAsFile()];
|
||||
}
|
||||
|
||||
static FileChooserControllerClass* oldFn (NSURL* url, const File& currentFileOrDirectory)
|
||||
{
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
|
||||
const auto pickerMode = currentFileOrDirectory.existsAsFile()
|
||||
? UIDocumentPickerModeExportToService
|
||||
: UIDocumentPickerModeMoveToService;
|
||||
return [[FileChooserControllerClass alloc] initWithURL: url inMode: pickerMode];
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}
|
||||
};
|
||||
|
||||
struct CreateOpenControllerTrait
|
||||
{
|
||||
API_AVAILABLE (ios (14))
|
||||
static FileChooserControllerClass* newFn (int flags, const StringArray& validExtensions)
|
||||
{
|
||||
NSUniquePtr<NSMutableArray> types ([[NSMutableArray alloc] init]);
|
||||
|
||||
if ((flags & FileBrowserComponent::canSelectDirectories) != 0)
|
||||
{
|
||||
if (auto* ptr = [UTType typeWithIdentifier: @"public.folder"])
|
||||
[types.get() addObject: ptr];
|
||||
}
|
||||
else
|
||||
{
|
||||
if (validExtensions.isEmpty())
|
||||
if (auto* ptr = [UTType typeWithIdentifier: @"public.data"])
|
||||
[types.get() addObject: ptr];
|
||||
|
||||
for (const auto& extension : validExtensions)
|
||||
if (auto* ptr = [UTType typeWithFilenameExtension: juceStringToNS (extension)])
|
||||
[types.get() addObject: ptr];
|
||||
}
|
||||
|
||||
return [[FileChooserControllerClass alloc] initForOpeningContentTypes: types.get()];
|
||||
}
|
||||
|
||||
static FileChooserControllerClass* oldFn (int flags, const StringArray& validExtensions)
|
||||
{
|
||||
const auto utTypes { std::invoke ([&]() -> StringArray
|
||||
{
|
||||
if ((flags & FileBrowserComponent::canSelectDirectories) != 0)
|
||||
return { "public.folder" };
|
||||
|
||||
if (validExtensions.isEmpty())
|
||||
return { "public.data" };
|
||||
|
||||
StringArray result;
|
||||
|
||||
for (const auto& extension : validExtensions)
|
||||
{
|
||||
if (extension.isEmpty())
|
||||
continue;
|
||||
|
||||
CFUniquePtr<CFStringRef> fileExtensionCF (extension.toCFString());
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
|
||||
if (CFUniquePtr<CFStringRef> tag { UTTypeCreatePreferredIdentifierForTag (kUTTagClassFilenameExtension, fileExtensionCF.get(), nullptr) })
|
||||
result.add (String::fromCFString (tag.get()));
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}
|
||||
|
||||
return result;
|
||||
}) };
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
|
||||
return [[FileChooserControllerClass alloc] initWithDocumentTypes: createNSArrayFromStringArray (utTypes) inMode: UIDocumentPickerModeOpen];
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}
|
||||
};
|
||||
|
||||
Native (FileChooser& fileChooser, int flags)
|
||||
: owner (fileChooser),
|
||||
savedFlags (flags)
|
||||
{
|
||||
delegate.reset ([[FileChooserDelegateClass alloc] init]);
|
||||
|
||||
const auto validExtensions = getValidExtensionsForWildcards (owner.filters);
|
||||
|
||||
if ((flags & FileBrowserComponent::saveMode) != 0)
|
||||
{
|
||||
auto currentFileOrDirectory = owner.startingFile;
|
||||
|
||||
if (! currentFileOrDirectory.existsAsFile())
|
||||
{
|
||||
const auto extension = validExtensions.isEmpty() ? String()
|
||||
: validExtensions.getReference (0);
|
||||
const auto filename = getFilename (currentFileOrDirectory, extension);
|
||||
const auto tmpDirectory = File::createTempFile ("JUCE-filepath");
|
||||
|
||||
if (tmpDirectory.createDirectory().wasOk())
|
||||
{
|
||||
currentFileOrDirectory = tmpDirectory.getChildFile (filename);
|
||||
currentFileOrDirectory.replaceWithText ("");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Temporary directory creation failed! You need to specify a
|
||||
// path you have write access to. Saving will not work for
|
||||
// current path.
|
||||
jassertfalse;
|
||||
}
|
||||
}
|
||||
|
||||
const NSUniquePtr<NSURL> url { [[NSURL alloc] initFileURLWithPath: juceStringToNS (currentFileOrDirectory.getFullPathName())] };
|
||||
controller.reset (ifelse_14_0<CreateSaveControllerTrait> (url.get(), currentFileOrDirectory));
|
||||
}
|
||||
else
|
||||
{
|
||||
controller.reset (ifelse_14_0<CreateOpenControllerTrait> (flags, validExtensions));
|
||||
[controller.get() setAllowsMultipleSelection: (flags & FileBrowserComponent::canSelectMultipleItems) != 0];
|
||||
}
|
||||
|
||||
[controller.get() setDelegate: delegate.get()];
|
||||
|
||||
if (auto* pc = [controller.get() presentationController])
|
||||
[pc setDelegate: delegate.get()];
|
||||
|
||||
displayNativeWindowModally (fileChooser.parent);
|
||||
}
|
||||
|
||||
void passResultsToInitiator (Array<URL> urls)
|
||||
{
|
||||
exitModalState (0);
|
||||
|
||||
// If the caller attempts to show a platform-native dialog box inside the results callback (e.g. in the DialogsDemo)
|
||||
// then the original peer must already have focus. Otherwise, there's a danger that either the invisible FileChooser
|
||||
// components will display the popup, locking the application, or maybe no component will have focus, and the
|
||||
// dialog won't show at all.
|
||||
for (auto i = 0; i < ComponentPeer::getNumPeers(); ++i)
|
||||
if (auto* p = ComponentPeer::getPeer (i))
|
||||
if (p != getPeer())
|
||||
if (auto* view = (UIView*) p->getNativeHandle())
|
||||
if ([view becomeFirstResponder] && [view isFirstResponder])
|
||||
break;
|
||||
|
||||
// Calling owner.finished will delete this Pimpl instance, so don't call any more member functions here!
|
||||
owner.finished (std::move (urls));
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
static StringArray getValidExtensionsForWildcards (const String& filterWildcards)
|
||||
{
|
||||
const auto filters = StringArray::fromTokens (filterWildcards, ";", "");
|
||||
|
||||
if (filters.contains ("*") || filters.isEmpty())
|
||||
return {};
|
||||
|
||||
StringArray result;
|
||||
|
||||
for (const auto& filter : filters)
|
||||
{
|
||||
if (filter.isEmpty())
|
||||
continue;
|
||||
|
||||
// iOS only supports file extension wild cards
|
||||
jassert (filter.upToLastOccurrenceOf (".", true, false) == "*.");
|
||||
|
||||
result.add (filter.fromLastOccurrenceOf (".", false, false));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static String getFilename (const File& path, const String& fallbackExtension)
|
||||
{
|
||||
auto filename = path.getFileNameWithoutExtension();
|
||||
auto extension = path.getFileExtension().substring (1);
|
||||
|
||||
if (filename.isEmpty())
|
||||
filename = "Untitled";
|
||||
|
||||
if (extension.isEmpty())
|
||||
extension = fallbackExtension;
|
||||
|
||||
if (extension.isNotEmpty())
|
||||
filename += "." + extension;
|
||||
|
||||
return filename;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
FileChooser& owner;
|
||||
NSUniquePtr<FileChooserDelegateClass> delegate;
|
||||
NSUniquePtr<FileChooserControllerClass> controller;
|
||||
int savedFlags = 0;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Native)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
bool FileChooser::isPlatformDialogAvailable()
|
||||
{
|
||||
#if JUCE_DISABLE_NATIVE_FILECHOOSERS
|
||||
return false;
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags,
|
||||
FilePreviewComponent*)
|
||||
{
|
||||
return Native::make (owner, flags);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
|
||||
@implementation FileChooserControllerClass
|
||||
{
|
||||
std::weak_ptr<FileChooser::Native> ptr;
|
||||
}
|
||||
|
||||
- (void) setParent: (std::shared_ptr<FileChooser::Native>) parent
|
||||
{
|
||||
ptr = parent;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation FileChooserDelegateClass
|
||||
{
|
||||
std::weak_ptr<FileChooser::Native> weak;
|
||||
}
|
||||
|
||||
- (void) setParent: (std::shared_ptr<FileChooser::Native>) o
|
||||
{
|
||||
weak = o;
|
||||
}
|
||||
|
||||
- (void) documentPicker: (UIDocumentPickerViewController*) controller didPickDocumentsAtURLs: (NSArray<NSURL*>*) urls
|
||||
{
|
||||
if (auto strong = weak.lock())
|
||||
strong->didPickDocumentsAtURLs (urls);
|
||||
}
|
||||
|
||||
- (void) documentPickerWasCancelled: (UIDocumentPickerViewController*) controller
|
||||
{
|
||||
if (auto strong = weak.lock())
|
||||
strong->pickerWasCancelled();
|
||||
}
|
||||
|
||||
- (void) presentationControllerDidDismiss: (UIPresentationController *) presentationController
|
||||
{
|
||||
if (auto strong = weak.lock())
|
||||
strong->pickerWasCancelled();
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,333 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
static bool exeIsAvailable (String executable)
|
||||
{
|
||||
ChildProcess child;
|
||||
|
||||
if (child.start ("which " + executable))
|
||||
{
|
||||
child.waitForProcessToFinish (60 * 1000);
|
||||
return (child.getExitCode() == 0);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool isSet (int flags, int toCheck)
|
||||
{
|
||||
return (flags & toCheck) != 0;
|
||||
}
|
||||
|
||||
class FileChooser::Native final : public FileChooser::Pimpl,
|
||||
private Timer
|
||||
{
|
||||
public:
|
||||
Native (FileChooser& fileChooser, int flags)
|
||||
: owner (fileChooser),
|
||||
// kdialog/zenity only support opening either files or directories.
|
||||
// Files should take precedence, if requested.
|
||||
isDirectory (isSet (flags, FileBrowserComponent::canSelectDirectories) && ! isSet (flags, FileBrowserComponent::canSelectFiles)),
|
||||
isSave (isSet (flags, FileBrowserComponent::saveMode)),
|
||||
selectMultipleFiles (isSet (flags, FileBrowserComponent::canSelectMultipleItems)),
|
||||
warnAboutOverwrite (isSet (flags, FileBrowserComponent::warnAboutOverwriting))
|
||||
{
|
||||
const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
|
||||
|
||||
// use kdialog for KDE sessions or if zenity is missing
|
||||
if (exeIsAvailable ("kdialog") && (isKdeFullSession() || ! exeIsAvailable ("zenity")))
|
||||
addKDialogArgs();
|
||||
else
|
||||
addZenityArgs();
|
||||
}
|
||||
|
||||
~Native() override
|
||||
{
|
||||
finish (true);
|
||||
}
|
||||
|
||||
void runModally() override
|
||||
{
|
||||
#if JUCE_MODAL_LOOPS_PERMITTED
|
||||
child.start (args, ChildProcess::wantStdOut);
|
||||
|
||||
while (child.isRunning())
|
||||
if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
|
||||
break;
|
||||
|
||||
finish (false);
|
||||
#else
|
||||
jassertfalse;
|
||||
#endif
|
||||
}
|
||||
|
||||
void launch() override
|
||||
{
|
||||
child.start (args, ChildProcess::wantStdOut);
|
||||
startTimer (100);
|
||||
}
|
||||
|
||||
private:
|
||||
FileChooser& owner;
|
||||
bool isDirectory, isSave, selectMultipleFiles, warnAboutOverwrite;
|
||||
|
||||
ChildProcess child;
|
||||
StringArray args;
|
||||
String separator;
|
||||
|
||||
void timerCallback() override
|
||||
{
|
||||
if (! child.isRunning())
|
||||
{
|
||||
stopTimer();
|
||||
finish (false);
|
||||
}
|
||||
}
|
||||
|
||||
void finish (bool shouldKill)
|
||||
{
|
||||
String result;
|
||||
Array<URL> selection;
|
||||
|
||||
if (shouldKill)
|
||||
child.kill();
|
||||
else
|
||||
result = child.readAllProcessOutput().trim();
|
||||
|
||||
if (result.isNotEmpty())
|
||||
{
|
||||
StringArray tokens;
|
||||
|
||||
if (selectMultipleFiles)
|
||||
tokens.addTokens (result, separator, "\"");
|
||||
else
|
||||
tokens.add (result);
|
||||
|
||||
for (auto& token : tokens)
|
||||
selection.add (URL (File::getCurrentWorkingDirectory().getChildFile (token)));
|
||||
}
|
||||
|
||||
if (! shouldKill)
|
||||
{
|
||||
child.waitForProcessToFinish (60 * 1000);
|
||||
owner.finished (selection);
|
||||
}
|
||||
}
|
||||
|
||||
static uint64 getTopWindowID() noexcept
|
||||
{
|
||||
if (TopLevelWindow* top = TopLevelWindow::getActiveTopLevelWindow())
|
||||
return (uint64) (pointer_sized_uint) top->getWindowHandle();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static bool isKdeFullSession()
|
||||
{
|
||||
return SystemStats::getEnvironmentVariable ("KDE_FULL_SESSION", String())
|
||||
.equalsIgnoreCase ("true");
|
||||
}
|
||||
|
||||
void addKDialogArgs()
|
||||
{
|
||||
args.add ("kdialog");
|
||||
|
||||
if (owner.title.isNotEmpty())
|
||||
args.add ("--title=" + owner.title);
|
||||
|
||||
if (uint64 topWindowID = getTopWindowID())
|
||||
{
|
||||
args.add ("--attach");
|
||||
args.add (String (topWindowID));
|
||||
}
|
||||
|
||||
if (selectMultipleFiles)
|
||||
{
|
||||
separator = "\n";
|
||||
args.add ("--multiple");
|
||||
args.add ("--separate-output");
|
||||
args.add ("--getopenfilename");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (isSave) args.add ("--getsavefilename");
|
||||
else if (isDirectory) args.add ("--getexistingdirectory");
|
||||
else args.add ("--getopenfilename");
|
||||
}
|
||||
|
||||
File startPath;
|
||||
|
||||
if (owner.startingFile.exists())
|
||||
{
|
||||
startPath = owner.startingFile;
|
||||
}
|
||||
else if (owner.startingFile.getParentDirectory().exists())
|
||||
{
|
||||
startPath = owner.startingFile.getParentDirectory();
|
||||
}
|
||||
else
|
||||
{
|
||||
startPath = File::getSpecialLocation (File::userHomeDirectory);
|
||||
|
||||
if (isSave)
|
||||
startPath = startPath.getChildFile (owner.startingFile.getFileName());
|
||||
}
|
||||
|
||||
args.add (startPath.getFullPathName());
|
||||
args.add ("(" + owner.filters.replaceCharacter (';', ' ').trim() + ")");
|
||||
}
|
||||
|
||||
void addZenityArgs()
|
||||
{
|
||||
args.add ("zenity");
|
||||
args.add ("--file-selection");
|
||||
|
||||
const auto zenityVersion = std::invoke ([]
|
||||
{
|
||||
ChildProcess process;
|
||||
process.start ("zenity --version");
|
||||
process.waitForProcessToFinish (1000);
|
||||
const auto versionString = process.readAllProcessOutput();
|
||||
const auto version = StringArray::fromTokens (versionString.trim(), ".", "");
|
||||
|
||||
std::array<int, 3> versionArray{};
|
||||
|
||||
for (int i = 0; i < std::min (version.size(), 3); ++i)
|
||||
versionArray[(size_t) i] = version[i].getIntValue();
|
||||
|
||||
return versionArray;
|
||||
});
|
||||
|
||||
const auto getUnderstandsConfirmOverwrite = [zenityVersion]
|
||||
{
|
||||
if (zenityVersion == std::array<int, 3>{})
|
||||
return false;
|
||||
|
||||
// --confirm-overwrite is deprecated in zenity 3.91 and higher
|
||||
return zenityVersion < std::array<int, 3> { 3, 91 };
|
||||
};
|
||||
|
||||
if (warnAboutOverwrite && getUnderstandsConfirmOverwrite())
|
||||
args.add ("--confirm-overwrite");
|
||||
|
||||
if (owner.title.isNotEmpty())
|
||||
args.add ("--title=" + owner.title);
|
||||
|
||||
if (selectMultipleFiles)
|
||||
{
|
||||
separator = ":";
|
||||
args.add ("--multiple");
|
||||
args.add ("--separator=" + separator);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (isSave)
|
||||
args.add ("--save");
|
||||
}
|
||||
|
||||
if (isDirectory)
|
||||
args.add ("--directory");
|
||||
|
||||
if (owner.filters.isNotEmpty() && owner.filters != "*" && owner.filters != "*.*")
|
||||
{
|
||||
StringArray tokens;
|
||||
tokens.addTokens (owner.filters, ";,|", "\"");
|
||||
tokens.removeEmptyStrings();
|
||||
|
||||
args.add ("--file-filter=" + tokens.joinIntoString (" "));
|
||||
}
|
||||
|
||||
// When a directory is specified for the --filename argument older zenity versions
|
||||
// e.g. 4.0.1 will not enter this directory, but display it as a selected directory inside
|
||||
// the parent directory. This is the case even if the argument ends with '/'.
|
||||
//
|
||||
// This workaround will enter the directory. This workaround completely breaks with version
|
||||
// 4.2.1 and fails to select a starting location entirely. On the upside, 4.2.1 will enter
|
||||
// the directory if the filename argument ends with '/'.
|
||||
const auto pre421WorkaroundToEnterStartingDirectory = [&]
|
||||
{
|
||||
if (owner.startingFile.isDirectory())
|
||||
owner.startingFile.setAsCurrentWorkingDirectory();
|
||||
else if (owner.startingFile.getParentDirectory().exists())
|
||||
owner.startingFile.getParentDirectory().setAsCurrentWorkingDirectory();
|
||||
else
|
||||
File::getSpecialLocation (File::userHomeDirectory).setAsCurrentWorkingDirectory();
|
||||
|
||||
return owner.startingFile.getFileName();
|
||||
};
|
||||
|
||||
const auto getFilename = [&]() -> String
|
||||
{
|
||||
if (owner.startingFile.isDirectory())
|
||||
return File::addTrailingSeparator (owner.startingFile.getFullPathName());
|
||||
|
||||
if (owner.startingFile.getParentDirectory().exists())
|
||||
return owner.startingFile.getFullPathName();
|
||||
|
||||
return {};
|
||||
};
|
||||
|
||||
const auto filename = zenityVersion < std::array<int, 3> { 4, 1, 2 } ? pre421WorkaroundToEnterStartingDirectory()
|
||||
: getFilename();
|
||||
|
||||
if (! filename.isEmpty())
|
||||
args.add ("--filename=" + filename);
|
||||
|
||||
// supplying the window ID of the topmost window makes sure that Zenity pops up
|
||||
if (uint64 topWindowID = getTopWindowID())
|
||||
setenv ("WINDOWID", String (topWindowID).toRawUTF8(), true);
|
||||
}
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Native)
|
||||
};
|
||||
|
||||
bool FileChooser::isPlatformDialogAvailable()
|
||||
{
|
||||
#if JUCE_DISABLE_NATIVE_FILECHOOSERS
|
||||
return false;
|
||||
#else
|
||||
static bool canUseNativeBox = exeIsAvailable ("zenity") || exeIsAvailable ("kdialog");
|
||||
return canUseNativeBox;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags, FilePreviewComponent*)
|
||||
{
|
||||
return std::make_shared<Native> (owner, flags);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,416 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
static NSMutableArray* createAllowedTypesArray (const StringArray& filters)
|
||||
{
|
||||
if (filters.size() == 0)
|
||||
return nil;
|
||||
|
||||
NSMutableArray* filterArray = [[[NSMutableArray alloc] init] autorelease];
|
||||
|
||||
for (int i = 0; i < filters.size(); ++i)
|
||||
{
|
||||
// From OS X 10.6 you can only specify allowed extensions, so any filters containing wildcards
|
||||
// must be of the form "*.extension"
|
||||
jassert (filters[i] == "*"
|
||||
|| (filters[i].startsWith ("*.") && filters[i].lastIndexOfChar ('*') == 0));
|
||||
const String f (filters[i].replace ("*.", ""));
|
||||
|
||||
if (f == "*")
|
||||
return nil;
|
||||
|
||||
[filterArray addObject: juceStringToNS (f)];
|
||||
}
|
||||
|
||||
return filterArray;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
class FileChooser::Native final : public Component,
|
||||
public FileChooser::Pimpl
|
||||
{
|
||||
public:
|
||||
Native (FileChooser& fileChooser, int flags, FilePreviewComponent* previewComponent)
|
||||
: owner (fileChooser), preview (previewComponent),
|
||||
selectsDirectories ((flags & FileBrowserComponent::canSelectDirectories) != 0),
|
||||
selectsFiles ((flags & FileBrowserComponent::canSelectFiles) != 0),
|
||||
isSave ((flags & FileBrowserComponent::saveMode) != 0),
|
||||
selectMultiple ((flags & FileBrowserComponent::canSelectMultipleItems) != 0)
|
||||
{
|
||||
setBounds (0, 0, 0, 0);
|
||||
setOpaque (true);
|
||||
|
||||
panel = [&]
|
||||
{
|
||||
if (SystemStats::isAppSandboxEnabled())
|
||||
return isSave ? [[NSSavePanel alloc] init]
|
||||
: [[NSOpenPanel alloc] init];
|
||||
|
||||
static SafeSavePanel safeSavePanel;
|
||||
static SafeOpenPanel safeOpenPanel;
|
||||
|
||||
return isSave ? [safeSavePanel.createInstance() init]
|
||||
: [safeOpenPanel.createInstance() init];
|
||||
}();
|
||||
|
||||
static DelegateClass delegateClass;
|
||||
|
||||
delegate = [delegateClass.createInstance() init];
|
||||
object_setInstanceVariable (delegate, "cppObject", this);
|
||||
|
||||
[panel setDelegate: delegate];
|
||||
|
||||
filters.addTokens (owner.filters.replaceCharacters (",:", ";;"), ";", String());
|
||||
filters.trim();
|
||||
filters.removeEmptyStrings();
|
||||
|
||||
auto* nsTitle = juceStringToNS (owner.title);
|
||||
[panel setTitle: nsTitle];
|
||||
[panel setReleasedWhenClosed: YES];
|
||||
|
||||
JUCE_BEGIN_IGNORE_DEPRECATION_WARNINGS
|
||||
[panel setAllowedFileTypes: createAllowedTypesArray (filters)];
|
||||
JUCE_END_IGNORE_DEPRECATION_WARNINGS
|
||||
|
||||
if (! isSave)
|
||||
{
|
||||
auto* openPanel = static_cast<NSOpenPanel*> (panel);
|
||||
|
||||
[openPanel setCanChooseDirectories: selectsDirectories];
|
||||
[openPanel setCanChooseFiles: selectsFiles];
|
||||
[openPanel setAllowsMultipleSelection: selectMultiple];
|
||||
[openPanel setResolvesAliases: YES];
|
||||
[openPanel setMessage: nsTitle]; // equivalent to the title bar since 10.11
|
||||
|
||||
if (owner.treatFilePackagesAsDirs)
|
||||
[openPanel setTreatsFilePackagesAsDirectories: YES];
|
||||
}
|
||||
|
||||
if (preview != nullptr)
|
||||
{
|
||||
nsViewPreview = [[NSView alloc] initWithFrame: makeCGRect (preview->getLocalBounds())];
|
||||
[panel setAccessoryView: nsViewPreview];
|
||||
|
||||
preview->addToDesktop (0, (void*) nsViewPreview);
|
||||
preview->setVisible (true);
|
||||
|
||||
if (! isSave)
|
||||
{
|
||||
auto* openPanel = static_cast<NSOpenPanel*> (panel);
|
||||
[openPanel setAccessoryViewDisclosed: YES];
|
||||
}
|
||||
}
|
||||
|
||||
if (isSave || selectsDirectories)
|
||||
[panel setCanCreateDirectories: YES];
|
||||
|
||||
[panel setLevel: NSModalPanelWindowLevel];
|
||||
|
||||
if (owner.startingFile.isDirectory())
|
||||
{
|
||||
startingDirectory = owner.startingFile.getFullPathName();
|
||||
}
|
||||
else
|
||||
{
|
||||
startingDirectory = owner.startingFile.getParentDirectory().getFullPathName();
|
||||
filename = owner.startingFile.getFileName();
|
||||
}
|
||||
|
||||
[panel setDirectoryURL: createNSURLFromFile (startingDirectory)];
|
||||
[panel setNameFieldStringValue: juceStringToNS (filename)];
|
||||
}
|
||||
|
||||
~Native() override
|
||||
{
|
||||
exitModalState (0);
|
||||
|
||||
if (preview != nullptr)
|
||||
preview->removeFromDesktop();
|
||||
|
||||
removeFromDesktop();
|
||||
|
||||
if (panel != nil)
|
||||
{
|
||||
[panel setDelegate: nil];
|
||||
|
||||
if (nsViewPreview != nil)
|
||||
{
|
||||
[panel setAccessoryView: nil];
|
||||
[nsViewPreview release];
|
||||
}
|
||||
|
||||
[panel close];
|
||||
}
|
||||
|
||||
if (delegate != nil)
|
||||
[delegate release];
|
||||
}
|
||||
|
||||
void launch() override
|
||||
{
|
||||
if (panel != nil)
|
||||
{
|
||||
setAlwaysOnTop (WindowUtils::areThereAnyAlwaysOnTopWindows());
|
||||
addToDesktop (0);
|
||||
|
||||
enterModalState (true);
|
||||
|
||||
MessageManager::callAsync ([ref = SafePointer<Native> (this)]
|
||||
{
|
||||
if (ref == nullptr)
|
||||
return;
|
||||
|
||||
[ref->panel beginWithCompletionHandler: ^(NSInteger result)
|
||||
{
|
||||
if (auto* ptr = ref.getComponent())
|
||||
ptr->finished (result);
|
||||
}];
|
||||
|
||||
if (ref->preview != nullptr)
|
||||
ref->preview->toFront (true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void runModally() override
|
||||
{
|
||||
#if JUCE_MODAL_LOOPS_PERMITTED
|
||||
ensurePanelSafe();
|
||||
|
||||
std::unique_ptr<TemporaryMainMenuWithStandardCommands> tempMenu;
|
||||
|
||||
if (JUCEApplicationBase::isStandaloneApp())
|
||||
tempMenu = std::make_unique<TemporaryMainMenuWithStandardCommands> (preview);
|
||||
|
||||
jassert (panel != nil);
|
||||
auto result = [panel runModal];
|
||||
finished (result);
|
||||
#else
|
||||
jassertfalse;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool canModalEventBeSentToComponent (const Component* targetComponent) override
|
||||
{
|
||||
return TemporaryMainMenuWithStandardCommands::checkModalEvent (preview, targetComponent);
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
typedef NSObject<NSOpenSavePanelDelegate> DelegateType;
|
||||
|
||||
static URL urlFromNSURL (NSURL* url)
|
||||
{
|
||||
const auto scheme = nsStringToJuce ([url scheme]);
|
||||
|
||||
auto pathComponents = StringArray::fromTokens (nsStringToJuce ([url path]), "/", {});
|
||||
|
||||
for (auto& component : pathComponents)
|
||||
component = URL::addEscapeChars (component, false);
|
||||
|
||||
return { scheme + "://" + pathComponents.joinIntoString ("/") };
|
||||
}
|
||||
|
||||
void finished (NSInteger result)
|
||||
{
|
||||
Array<URL> chooserResults;
|
||||
|
||||
exitModalState (0);
|
||||
|
||||
if (panel != nil && result == NSModalResponseOK)
|
||||
{
|
||||
auto addURLResult = [&chooserResults] (NSURL* urlToAdd)
|
||||
{
|
||||
chooserResults.add (urlFromNSURL (urlToAdd));
|
||||
};
|
||||
|
||||
if (isSave)
|
||||
{
|
||||
addURLResult ([panel URL]);
|
||||
}
|
||||
else
|
||||
{
|
||||
auto* openPanel = static_cast<NSOpenPanel*> (panel);
|
||||
auto urls = [openPanel URLs];
|
||||
|
||||
for (unsigned int i = 0; i < [urls count]; ++i)
|
||||
addURLResult ([urls objectAtIndex: i]);
|
||||
}
|
||||
}
|
||||
|
||||
owner.finished (chooserResults);
|
||||
}
|
||||
|
||||
BOOL shouldShowURL (const URL& urlToTest)
|
||||
{
|
||||
for (int i = filters.size(); --i >= 0;)
|
||||
if (urlToTest.getFileName().matchesWildcard (filters[i], true))
|
||||
return YES;
|
||||
|
||||
const auto f = urlToTest.getLocalFile();
|
||||
return f.isDirectory()
|
||||
&& ! [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (f.getFullPathName())];
|
||||
}
|
||||
|
||||
void panelSelectionDidChange ([[maybe_unused]] id sender)
|
||||
{
|
||||
jassert (sender == panel);
|
||||
|
||||
// NB: would need to extend FilePreviewComponent to handle the full list rather than just the first one
|
||||
if (preview != nullptr)
|
||||
preview->selectedFileChanged (File (getSelectedPaths()[0]));
|
||||
}
|
||||
|
||||
StringArray getSelectedPaths() const
|
||||
{
|
||||
if (panel == nullptr)
|
||||
return {};
|
||||
|
||||
StringArray paths;
|
||||
|
||||
if (isSave)
|
||||
{
|
||||
paths.add (nsStringToJuce ([[panel URL] path]));
|
||||
}
|
||||
else
|
||||
{
|
||||
auto* urls = [static_cast<NSOpenPanel*> (panel) URLs];
|
||||
|
||||
for (NSUInteger i = 0; i < [urls count]; ++i)
|
||||
paths.add (nsStringToJuce ([[urls objectAtIndex: i] path]));
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
FileChooser& owner;
|
||||
FilePreviewComponent* preview;
|
||||
NSView* nsViewPreview = nullptr;
|
||||
bool selectsDirectories, selectsFiles, isSave, selectMultiple;
|
||||
|
||||
NSSavePanel* panel;
|
||||
DelegateType* delegate;
|
||||
|
||||
StringArray filters;
|
||||
String startingDirectory, filename;
|
||||
|
||||
void ensurePanelSafe()
|
||||
{
|
||||
// If you hit this, something (probably the plugin host) has modified the panel,
|
||||
// allowing the application to terminate while the panel's modal loop is running.
|
||||
// This is a very bad idea! Quitting from within the panel's modal loop may cause
|
||||
// your plugin/app destructor to run directly from within `runModally`, which will
|
||||
// dispose all app resources while they're still in use.
|
||||
// A safer alternative is to invoke the FileChooser with `launchAsync`, rather than
|
||||
// using the modal launchers.
|
||||
jassert ([panel preventsApplicationTerminationWhenModal]);
|
||||
}
|
||||
|
||||
static BOOL preventsApplicationTerminationWhenModal (id, SEL) { return YES; }
|
||||
|
||||
template <typename Base>
|
||||
struct SafeModalPanel : public ObjCClass<Base>
|
||||
{
|
||||
explicit SafeModalPanel (const char* name)
|
||||
: ObjCClass<Base> (name)
|
||||
{
|
||||
this->addMethod (@selector (preventsApplicationTerminationWhenModal),
|
||||
preventsApplicationTerminationWhenModal);
|
||||
|
||||
this->registerClass();
|
||||
}
|
||||
};
|
||||
|
||||
struct SafeSavePanel : SafeModalPanel<NSSavePanel>
|
||||
{
|
||||
SafeSavePanel() : SafeModalPanel ("SafeSavePanel_") {}
|
||||
};
|
||||
|
||||
struct SafeOpenPanel : SafeModalPanel<NSOpenPanel>
|
||||
{
|
||||
SafeOpenPanel() : SafeModalPanel ("SafeOpenPanel_") {}
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
struct DelegateClass final : public ObjCClass<DelegateType>
|
||||
{
|
||||
DelegateClass()
|
||||
: ObjCClass ("JUCEFileChooser_")
|
||||
{
|
||||
addIvar<Native*> ("cppObject");
|
||||
|
||||
addMethod (@selector (panel:shouldEnableURL:), shouldEnableURL);
|
||||
addMethod (@selector (panelSelectionDidChange:), panelSelectionDidChange);
|
||||
|
||||
addProtocol (@protocol (NSOpenSavePanelDelegate));
|
||||
|
||||
registerClass();
|
||||
}
|
||||
|
||||
private:
|
||||
static BOOL shouldEnableURL (id self, SEL, id /*sender*/, NSURL* url)
|
||||
{
|
||||
return getIvar<Native*> (self, "cppObject")->shouldShowURL (urlFromNSURL (url));
|
||||
}
|
||||
|
||||
static void panelSelectionDidChange (id self, SEL, id sender)
|
||||
{
|
||||
getIvar<Native*> (self, "cppObject")->panelSelectionDidChange (sender);
|
||||
}
|
||||
};
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Native)
|
||||
};
|
||||
|
||||
std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags,
|
||||
FilePreviewComponent* preview)
|
||||
{
|
||||
return std::make_shared<FileChooser::Native> (owner, flags, preview);
|
||||
}
|
||||
|
||||
bool FileChooser::isPlatformDialogAvailable()
|
||||
{
|
||||
#if JUCE_DISABLE_NATIVE_FILECHOOSERS
|
||||
return false;
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,908 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
// Implemented in juce_Messaging_windows.cpp
|
||||
namespace detail
|
||||
{
|
||||
bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
|
||||
} // namespace detail
|
||||
|
||||
class Win32NativeFileChooser final : private Thread
|
||||
{
|
||||
public:
|
||||
enum { charsAvailableForResult = 32768 };
|
||||
|
||||
Win32NativeFileChooser (Component* parent, int flags, FilePreviewComponent* previewComp,
|
||||
const File& startingFile, const String& titleToUse,
|
||||
const String& filtersToUse)
|
||||
: Thread (SystemStats::getJUCEVersion() + ": Native Win32 FileChooser"),
|
||||
owner (parent),
|
||||
title (titleToUse),
|
||||
filtersString (filtersToUse.replaceCharacter (',', ';')),
|
||||
selectsDirectories ((flags & FileBrowserComponent::canSelectDirectories) != 0),
|
||||
// When dealing with directories, it is not possible to 'Save' them. However, one can 'Open' a directory in order to save into it.
|
||||
// If the 'saveMode' and 'canSelectDirectories' flags are both present, create an FileOpenDialog instead of an FileSaveDialog.
|
||||
isSave ((flags & FileBrowserComponent::saveMode) != 0 && ! selectsDirectories),
|
||||
warnAboutOverwrite ((flags & FileBrowserComponent::warnAboutOverwriting) != 0),
|
||||
selectMultiple ((flags & FileBrowserComponent::canSelectMultipleItems) != 0)
|
||||
{
|
||||
auto parentDirectory = startingFile.getParentDirectory();
|
||||
|
||||
// Handle nonexistent root directories in the same way as existing ones
|
||||
files.calloc (static_cast<size_t> (charsAvailableForResult) + 1);
|
||||
|
||||
if (startingFile.isDirectory() || startingFile.isRoot())
|
||||
{
|
||||
initialPath = startingFile.getFullPathName();
|
||||
}
|
||||
else
|
||||
{
|
||||
startingFile.getFileName().copyToUTF16 (files,
|
||||
static_cast<size_t> (charsAvailableForResult) * sizeof (WCHAR));
|
||||
initialPath = parentDirectory.getFullPathName();
|
||||
}
|
||||
|
||||
if (! selectsDirectories)
|
||||
{
|
||||
if (previewComp != nullptr)
|
||||
customComponent.reset (new CustomComponentHolder (previewComp));
|
||||
|
||||
setupFilters();
|
||||
}
|
||||
}
|
||||
|
||||
~Win32NativeFileChooser() override
|
||||
{
|
||||
signalThreadShouldExit();
|
||||
|
||||
while (isThreadRunning())
|
||||
{
|
||||
if (! detail::dispatchNextMessageOnSystemQueue (true))
|
||||
Thread::sleep (1);
|
||||
}
|
||||
}
|
||||
|
||||
void open (bool async)
|
||||
{
|
||||
results.clear();
|
||||
|
||||
// the thread should not be running
|
||||
nativeDialogRef.set (nullptr);
|
||||
|
||||
if (async)
|
||||
{
|
||||
jassert (! isThreadRunning());
|
||||
|
||||
startThread();
|
||||
}
|
||||
else
|
||||
{
|
||||
results = openDialog (false);
|
||||
owner->exitModalState (results.size() > 0 ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
void cancel()
|
||||
{
|
||||
ScopedLock lock (deletingDialog);
|
||||
|
||||
customComponent = nullptr;
|
||||
shouldCancel = true;
|
||||
|
||||
if (auto hwnd = nativeDialogRef.get())
|
||||
PostMessage (hwnd, WM_CLOSE, 0, 0);
|
||||
}
|
||||
|
||||
Component* getCustomComponent() { return customComponent.get(); }
|
||||
|
||||
Array<URL> results;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
class CustomComponentHolder final : public Component
|
||||
{
|
||||
public:
|
||||
CustomComponentHolder (Component* const customComp)
|
||||
{
|
||||
setVisible (true);
|
||||
setOpaque (true);
|
||||
addAndMakeVisible (customComp);
|
||||
setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
|
||||
}
|
||||
|
||||
void paint (Graphics& g) override
|
||||
{
|
||||
g.fillAll (Colours::lightgrey);
|
||||
}
|
||||
|
||||
void resized() override
|
||||
{
|
||||
if (Component* const c = getChildComponent (0))
|
||||
c->setBounds (getLocalBounds());
|
||||
}
|
||||
|
||||
private:
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
const Component::SafePointer<Component> owner;
|
||||
String title, filtersString;
|
||||
std::unique_ptr<CustomComponentHolder> customComponent;
|
||||
String initialPath, returnedString;
|
||||
|
||||
CriticalSection deletingDialog;
|
||||
|
||||
bool selectsDirectories, isSave, warnAboutOverwrite, selectMultiple;
|
||||
|
||||
HeapBlock<WCHAR> files;
|
||||
HeapBlock<WCHAR> filters;
|
||||
|
||||
Atomic<HWND> nativeDialogRef { nullptr };
|
||||
bool shouldCancel = false;
|
||||
|
||||
struct FreeLPWSTR
|
||||
{
|
||||
void operator() (LPWSTR ptr) const noexcept { CoTaskMemFree (ptr); }
|
||||
};
|
||||
|
||||
bool showDialog (IFileDialog& dialog)
|
||||
{
|
||||
FILEOPENDIALOGOPTIONS flags = {};
|
||||
|
||||
if (FAILED (dialog.GetOptions (&flags)))
|
||||
return false;
|
||||
|
||||
const auto setBit = [] (FILEOPENDIALOGOPTIONS& field, bool value, FILEOPENDIALOGOPTIONS option)
|
||||
{
|
||||
if (value)
|
||||
field |= option;
|
||||
else
|
||||
field &= ~option;
|
||||
};
|
||||
|
||||
setBit (flags, selectsDirectories, FOS_PICKFOLDERS);
|
||||
setBit (flags, warnAboutOverwrite, FOS_OVERWRITEPROMPT);
|
||||
setBit (flags, selectMultiple, FOS_ALLOWMULTISELECT);
|
||||
setBit (flags, customComponent != nullptr, FOS_FORCEPREVIEWPANEON);
|
||||
|
||||
if (FAILED (dialog.SetOptions (flags)) || FAILED (dialog.SetTitle (title.toUTF16())))
|
||||
return false;
|
||||
|
||||
PIDLIST_ABSOLUTE pidl = {};
|
||||
|
||||
if (FAILED (SHParseDisplayName (initialPath.toWideCharPointer(), nullptr, &pidl, SFGAO_FOLDER, nullptr)))
|
||||
{
|
||||
LPWSTR ptr = nullptr;
|
||||
auto result = SHGetKnownFolderPath (FOLDERID_Desktop, 0, nullptr, &ptr);
|
||||
std::unique_ptr<WCHAR, FreeLPWSTR> desktopPath (ptr);
|
||||
|
||||
if (FAILED (result))
|
||||
return false;
|
||||
|
||||
if (FAILED (SHParseDisplayName (desktopPath.get(), nullptr, &pidl, SFGAO_FOLDER, nullptr)))
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto item = [&]
|
||||
{
|
||||
ComSmartPtr<IShellItem> ptr;
|
||||
SHCreateShellItem (nullptr, nullptr, pidl, ptr.resetAndGetPointerAddress());
|
||||
return ptr;
|
||||
}();
|
||||
|
||||
if (item != nullptr)
|
||||
{
|
||||
dialog.SetDefaultFolder (item);
|
||||
|
||||
if (! initialPath.isEmpty())
|
||||
dialog.SetFolder (item);
|
||||
}
|
||||
|
||||
String filename (files.getData());
|
||||
|
||||
if (FAILED (dialog.SetFileName (filename.toWideCharPointer())))
|
||||
return false;
|
||||
|
||||
auto extension = getDefaultFileExtension (filename);
|
||||
|
||||
if (extension.isNotEmpty() && FAILED (dialog.SetDefaultExtension (extension.toWideCharPointer())))
|
||||
return false;
|
||||
|
||||
const COMDLG_FILTERSPEC spec[] { { filtersString.toWideCharPointer(), filtersString.toWideCharPointer() } };
|
||||
|
||||
if (! selectsDirectories && FAILED (dialog.SetFileTypes (numElementsInArray (spec), spec)))
|
||||
return false;
|
||||
|
||||
struct Events final : public ComBaseClassHelper<IFileDialogEvents>
|
||||
{
|
||||
explicit Events (Win32NativeFileChooser& o) : owner (o) {}
|
||||
|
||||
JUCE_COMRESULT OnTypeChange (IFileDialog* d) override { return updateHwnd (d); }
|
||||
JUCE_COMRESULT OnFolderChanging (IFileDialog* d, IShellItem*) override { return updateHwnd (d); }
|
||||
JUCE_COMRESULT OnFileOk (IFileDialog* d) override { return updateHwnd (d); }
|
||||
JUCE_COMRESULT OnFolderChange (IFileDialog* d) override { return updateHwnd (d); }
|
||||
JUCE_COMRESULT OnSelectionChange (IFileDialog* d) override { focusWorkaround(); return updateHwnd (d); }
|
||||
JUCE_COMRESULT OnShareViolation (IFileDialog* d, IShellItem*, FDE_SHAREVIOLATION_RESPONSE*) override { return updateHwnd (d); }
|
||||
JUCE_COMRESULT OnOverwrite (IFileDialog* d, IShellItem*, FDE_OVERWRITE_RESPONSE*) override { return updateHwnd (d); }
|
||||
|
||||
/* Workaround for a bug in Vista+, OpenFileDialog will truncate the initialFile text.
|
||||
Moving the caret along the full length of the text and back will reveal the full string.
|
||||
*/
|
||||
void focusWorkaround()
|
||||
{
|
||||
if (! defaultFileNameTextCaretMoved)
|
||||
{
|
||||
auto makeKeyInput = [] (WORD vk, bool pressed)
|
||||
{
|
||||
INPUT i;
|
||||
|
||||
ZeroMemory (&i, sizeof (INPUT));
|
||||
|
||||
i.type = INPUT_KEYBOARD;
|
||||
i.ki.wVk = vk;
|
||||
i.ki.dwFlags = pressed ? 0 : KEYEVENTF_KEYUP;
|
||||
|
||||
return i;
|
||||
};
|
||||
|
||||
INPUT inputs[] = {
|
||||
makeKeyInput (VK_HOME, true),
|
||||
makeKeyInput (VK_HOME, false),
|
||||
makeKeyInput (VK_END, true),
|
||||
makeKeyInput (VK_END, false),
|
||||
};
|
||||
|
||||
SendInput ((UINT) std::size (inputs), inputs, sizeof (INPUT));
|
||||
defaultFileNameTextCaretMoved = true;
|
||||
}
|
||||
}
|
||||
|
||||
JUCE_COMRESULT updateHwnd (IFileDialog* d)
|
||||
{
|
||||
HWND hwnd = nullptr;
|
||||
|
||||
if (auto window = ComSmartPtr (d, IncrementRef::yes).getInterface<IOleWindow>())
|
||||
window->GetWindow (&hwnd);
|
||||
|
||||
ScopedLock lock (owner.deletingDialog);
|
||||
|
||||
if (owner.shouldCancel)
|
||||
d->Close (S_FALSE);
|
||||
else if (hwnd != nullptr)
|
||||
owner.nativeDialogRef = hwnd;
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
bool defaultFileNameTextCaretMoved = false;
|
||||
Win32NativeFileChooser& owner;
|
||||
};
|
||||
|
||||
{
|
||||
ScopedLock lock (deletingDialog);
|
||||
|
||||
if (shouldCancel)
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto result = [&]
|
||||
{
|
||||
struct ScopedAdvise
|
||||
{
|
||||
ScopedAdvise (IFileDialog& d, Events& events) : dialog (d) { dialog.Advise (&events, &cookie); }
|
||||
~ScopedAdvise() { dialog.Unadvise (cookie); }
|
||||
IFileDialog& dialog;
|
||||
DWORD cookie = 0;
|
||||
};
|
||||
|
||||
Events events { *this };
|
||||
ScopedAdvise scope { dialog, events };
|
||||
return dialog.Show (GetActiveWindow()) == S_OK;
|
||||
}();
|
||||
|
||||
ScopedLock lock (deletingDialog);
|
||||
nativeDialogRef = nullptr;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
Array<URL> openDialogWithoutPreview()
|
||||
{
|
||||
const auto getUrl = [] (IShellItem& item)
|
||||
{
|
||||
LPWSTR ptr = nullptr;
|
||||
|
||||
if (item.GetDisplayName (SIGDN_FILESYSPATH, &ptr) != S_OK)
|
||||
return URL();
|
||||
|
||||
const auto path = std::unique_ptr<WCHAR, FreeLPWSTR> { ptr };
|
||||
return URL (File (String (path.get())));
|
||||
};
|
||||
|
||||
if (isSave)
|
||||
{
|
||||
const auto dialog = [&]
|
||||
{
|
||||
ComSmartPtr<IFileDialog> ptr;
|
||||
ptr.CoCreateInstance (CLSID_FileSaveDialog, CLSCTX_INPROC_SERVER);
|
||||
return ptr;
|
||||
}();
|
||||
|
||||
if (dialog == nullptr)
|
||||
return {};
|
||||
|
||||
showDialog (*dialog);
|
||||
|
||||
const auto item = [&]
|
||||
{
|
||||
ComSmartPtr<IShellItem> ptr;
|
||||
dialog->GetResult (ptr.resetAndGetPointerAddress());
|
||||
return ptr;
|
||||
}();
|
||||
|
||||
if (item == nullptr)
|
||||
return {};
|
||||
|
||||
const auto url = getUrl (*item);
|
||||
|
||||
if (url.isEmpty())
|
||||
return {};
|
||||
|
||||
return { url };
|
||||
}
|
||||
|
||||
const auto dialog = [&]
|
||||
{
|
||||
ComSmartPtr<IFileOpenDialog> ptr;
|
||||
ptr.CoCreateInstance (CLSID_FileOpenDialog, CLSCTX_INPROC_SERVER);
|
||||
return ptr;
|
||||
}();
|
||||
|
||||
if (dialog == nullptr)
|
||||
return {};
|
||||
|
||||
showDialog (*dialog);
|
||||
|
||||
const auto items = [&]
|
||||
{
|
||||
ComSmartPtr<IShellItemArray> ptr;
|
||||
dialog->GetResults (ptr.resetAndGetPointerAddress());
|
||||
return ptr;
|
||||
}();
|
||||
|
||||
if (items == nullptr)
|
||||
return {};
|
||||
|
||||
Array<URL> result;
|
||||
|
||||
DWORD numItems = 0;
|
||||
items->GetCount (&numItems);
|
||||
|
||||
for (DWORD i = 0; i < numItems; ++i)
|
||||
{
|
||||
ComSmartPtr<IShellItem> scope;
|
||||
items->GetItemAt (i, scope.resetAndGetPointerAddress());
|
||||
|
||||
if (scope != nullptr)
|
||||
{
|
||||
const auto url = getUrl (*scope);
|
||||
|
||||
if (! url.isEmpty())
|
||||
result.add (url);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Array<URL> openDialogWithPreview (bool async)
|
||||
{
|
||||
Array<URL> selections;
|
||||
|
||||
if (selectsDirectories)
|
||||
{
|
||||
BROWSEINFO bi = {};
|
||||
bi.hwndOwner = GetActiveWindow();
|
||||
bi.pszDisplayName = files;
|
||||
bi.lpszTitle = title.toWideCharPointer();
|
||||
bi.lParam = (LPARAM) this;
|
||||
bi.lpfn = browseCallbackProc;
|
||||
#ifdef BIF_USENEWUI
|
||||
bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
|
||||
#else
|
||||
bi.ulFlags = 0x50;
|
||||
#endif
|
||||
|
||||
LPITEMIDLIST list = SHBrowseForFolder (&bi);
|
||||
|
||||
if (! SHGetPathFromIDListW (list, files))
|
||||
{
|
||||
files[0] = 0;
|
||||
returnedString.clear();
|
||||
}
|
||||
|
||||
LPMALLOC al;
|
||||
|
||||
if (list != nullptr && SUCCEEDED (SHGetMalloc (&al)))
|
||||
al->Free (list);
|
||||
|
||||
if (files[0] != 0)
|
||||
{
|
||||
File result (String (files.get()));
|
||||
|
||||
if (returnedString.isNotEmpty())
|
||||
result = result.getSiblingFile (returnedString);
|
||||
|
||||
selections.add (URL (result));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
OPENFILENAMEW of = {};
|
||||
|
||||
#ifdef OPENFILENAME_SIZE_VERSION_400W
|
||||
of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
|
||||
#else
|
||||
of.lStructSize = sizeof (of);
|
||||
#endif
|
||||
|
||||
if (files[0] != 0)
|
||||
{
|
||||
auto startingFile = File (initialPath).getChildFile (String (files.get()));
|
||||
startingFile.getFullPathName().copyToUTF16 (files, charsAvailableForResult * sizeof (WCHAR));
|
||||
}
|
||||
|
||||
of.hwndOwner = GetActiveWindow();
|
||||
of.lpstrFilter = filters.getData();
|
||||
of.nFilterIndex = 1;
|
||||
of.lpstrFile = files;
|
||||
of.nMaxFile = (DWORD) charsAvailableForResult;
|
||||
of.lpstrInitialDir = initialPath.toWideCharPointer();
|
||||
of.lpstrTitle = title.toWideCharPointer();
|
||||
of.Flags = getOpenFilenameFlags (async);
|
||||
of.lCustData = (LPARAM) this;
|
||||
of.lpfnHook = &openCallback;
|
||||
|
||||
if (isSave)
|
||||
{
|
||||
auto extension = getDefaultFileExtension (files.getData());
|
||||
|
||||
if (extension.isNotEmpty())
|
||||
of.lpstrDefExt = extension.toWideCharPointer();
|
||||
|
||||
if (! GetSaveFileName (&of))
|
||||
return {};
|
||||
}
|
||||
else
|
||||
{
|
||||
if (! GetOpenFileName (&of))
|
||||
return {};
|
||||
}
|
||||
|
||||
if (selectMultiple && of.nFileOffset > 0 && files[of.nFileOffset - 1] == 0)
|
||||
{
|
||||
const WCHAR* filename = files + of.nFileOffset;
|
||||
|
||||
while (*filename != 0)
|
||||
{
|
||||
selections.add (URL (File (String (files.get())).getChildFile (String (filename))));
|
||||
filename += wcslen (filename) + 1;
|
||||
}
|
||||
}
|
||||
else if (files[0] != 0)
|
||||
{
|
||||
selections.add (URL (File (String (files.get()))));
|
||||
}
|
||||
}
|
||||
|
||||
return selections;
|
||||
}
|
||||
|
||||
Array<URL> openDialog (bool async)
|
||||
{
|
||||
struct Remover
|
||||
{
|
||||
explicit Remover (Win32NativeFileChooser& chooser) : item (chooser) {}
|
||||
~Remover() { getNativeDialogList().removeValue (&item); }
|
||||
|
||||
Win32NativeFileChooser& item;
|
||||
};
|
||||
|
||||
const Remover remover (*this);
|
||||
|
||||
if (customComponent == nullptr)
|
||||
return openDialogWithoutPreview();
|
||||
|
||||
return openDialogWithPreview (async);
|
||||
}
|
||||
|
||||
void run() override
|
||||
{
|
||||
results = [&]
|
||||
{
|
||||
struct ScopedCoInitialize
|
||||
{
|
||||
// IUnknown_GetWindow will only succeed when instantiated in a single-thread apartment
|
||||
ScopedCoInitialize() { [[maybe_unused]] const auto result = CoInitializeEx (nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); }
|
||||
~ScopedCoInitialize() { CoUninitialize(); }
|
||||
};
|
||||
|
||||
ScopedCoInitialize scope;
|
||||
|
||||
return openDialog (true);
|
||||
}();
|
||||
|
||||
auto safeOwner = owner;
|
||||
auto resultCode = results.size() > 0 ? 1 : 0;
|
||||
|
||||
MessageManager::callAsync ([resultCode, safeOwner]
|
||||
{
|
||||
if (safeOwner != nullptr)
|
||||
safeOwner->exitModalState (resultCode);
|
||||
});
|
||||
}
|
||||
|
||||
static HashMap<HWND, Win32NativeFileChooser*>& getNativeDialogList()
|
||||
{
|
||||
static HashMap<HWND, Win32NativeFileChooser*> dialogs;
|
||||
return dialogs;
|
||||
}
|
||||
|
||||
static Win32NativeFileChooser* getNativePointerForDialog (HWND hwnd)
|
||||
{
|
||||
return getNativeDialogList()[hwnd];
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void setupFilters()
|
||||
{
|
||||
const size_t filterSpaceNumChars = 2048;
|
||||
filters.calloc (filterSpaceNumChars);
|
||||
|
||||
const size_t bytesWritten = filtersString.copyToUTF16 (filters.getData(), filterSpaceNumChars * sizeof (WCHAR));
|
||||
filtersString.copyToUTF16 (filters + (bytesWritten / sizeof (WCHAR)),
|
||||
((filterSpaceNumChars - 1) * sizeof (WCHAR) - bytesWritten));
|
||||
|
||||
for (size_t i = 0; i < filterSpaceNumChars; ++i)
|
||||
if (filters[i] == '|')
|
||||
filters[i] = 0;
|
||||
}
|
||||
|
||||
DWORD getOpenFilenameFlags (bool async)
|
||||
{
|
||||
DWORD ofFlags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_ENABLESIZING;
|
||||
|
||||
if (warnAboutOverwrite)
|
||||
ofFlags |= OFN_OVERWRITEPROMPT;
|
||||
|
||||
if (selectMultiple)
|
||||
ofFlags |= OFN_ALLOWMULTISELECT;
|
||||
|
||||
if (async || customComponent != nullptr)
|
||||
ofFlags |= OFN_ENABLEHOOK;
|
||||
|
||||
return ofFlags;
|
||||
}
|
||||
|
||||
String getDefaultFileExtension (const String& filename) const
|
||||
{
|
||||
const auto extension = filename.contains (".") ? filename.fromLastOccurrenceOf (".", false, false)
|
||||
: String();
|
||||
|
||||
if (! extension.isEmpty())
|
||||
return extension;
|
||||
|
||||
auto tokens = StringArray::fromTokens (filtersString, ";,", "\"'");
|
||||
tokens.trim();
|
||||
tokens.removeEmptyStrings();
|
||||
|
||||
if (tokens.size() == 1 && tokens[0].removeCharacters ("*.").isNotEmpty())
|
||||
return tokens[0].fromFirstOccurrenceOf (".", false, false);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void initialised (HWND hWnd)
|
||||
{
|
||||
SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) initialPath.toWideCharPointer());
|
||||
initDialog (hWnd);
|
||||
}
|
||||
|
||||
void validateFailed (const String& path)
|
||||
{
|
||||
returnedString = path;
|
||||
}
|
||||
|
||||
void initDialog (HWND hdlg)
|
||||
{
|
||||
ScopedLock lock (deletingDialog);
|
||||
getNativeDialogList().set (hdlg, this);
|
||||
|
||||
if (shouldCancel)
|
||||
{
|
||||
EndDialog (hdlg, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
nativeDialogRef.set (hdlg);
|
||||
|
||||
if (customComponent != nullptr)
|
||||
{
|
||||
Component::SafePointer<Component> safeCustomComponent (customComponent.get());
|
||||
|
||||
RECT dialogScreenRect, dialogClientRect;
|
||||
GetWindowRect (hdlg, &dialogScreenRect);
|
||||
GetClientRect (hdlg, &dialogClientRect);
|
||||
|
||||
auto screenRectangle = Rectangle<int>::leftTopRightBottom (dialogScreenRect.left, dialogScreenRect.top,
|
||||
dialogScreenRect.right, dialogScreenRect.bottom);
|
||||
|
||||
auto scale = Desktop::getInstance().getDisplays().getDisplayForRect (screenRectangle, true)->scale;
|
||||
auto physicalComponentWidth = roundToInt (safeCustomComponent->getWidth() * scale);
|
||||
|
||||
SetWindowPos (hdlg, nullptr, screenRectangle.getX(), screenRectangle.getY(),
|
||||
physicalComponentWidth + jmax (150, screenRectangle.getWidth()),
|
||||
jmax (150, screenRectangle.getHeight()),
|
||||
SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
|
||||
|
||||
auto appendCustomComponent = [safeCustomComponent, dialogClientRect, scale, hdlg]() mutable
|
||||
{
|
||||
if (safeCustomComponent != nullptr)
|
||||
{
|
||||
auto scaledClientRectangle = Rectangle<int>::leftTopRightBottom (dialogClientRect.left, dialogClientRect.top,
|
||||
dialogClientRect.right, dialogClientRect.bottom) / scale;
|
||||
|
||||
safeCustomComponent->setBounds (scaledClientRectangle.getRight(), scaledClientRectangle.getY(),
|
||||
safeCustomComponent->getWidth(), scaledClientRectangle.getHeight());
|
||||
safeCustomComponent->addToDesktop (0, hdlg);
|
||||
}
|
||||
};
|
||||
|
||||
if (MessageManager::getInstance()->isThisTheMessageThread())
|
||||
appendCustomComponent();
|
||||
else
|
||||
MessageManager::callAsync (appendCustomComponent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void destroyDialog (HWND hdlg)
|
||||
{
|
||||
ScopedLock exiting (deletingDialog);
|
||||
|
||||
getNativeDialogList().remove (hdlg);
|
||||
nativeDialogRef.set (nullptr);
|
||||
|
||||
if (MessageManager::getInstance()->isThisTheMessageThread())
|
||||
customComponent = nullptr;
|
||||
else
|
||||
MessageManager::callAsync ([this] { customComponent = nullptr; });
|
||||
}
|
||||
|
||||
void selectionChanged (HWND hdlg)
|
||||
{
|
||||
ScopedLock lock (deletingDialog);
|
||||
|
||||
if (customComponent != nullptr && ! shouldCancel)
|
||||
{
|
||||
if (FilePreviewComponent* comp = dynamic_cast<FilePreviewComponent*> (customComponent->getChildComponent (0)))
|
||||
{
|
||||
WCHAR path [MAX_PATH * 2] = { 0 };
|
||||
CommDlg_OpenSave_GetFilePath (hdlg, (LPARAM) &path, MAX_PATH);
|
||||
|
||||
if (MessageManager::getInstance()->isThisTheMessageThread())
|
||||
{
|
||||
comp->selectedFileChanged (File (path));
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageManager::callAsync ([safeComp = Component::SafePointer<FilePreviewComponent> { comp },
|
||||
selectedFile = File { path }]() mutable
|
||||
{
|
||||
if (safeComp != nullptr)
|
||||
safeComp->selectedFileChanged (selectedFile);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
|
||||
{
|
||||
auto* self = reinterpret_cast<Win32NativeFileChooser*> (lpData);
|
||||
|
||||
switch (msg)
|
||||
{
|
||||
case BFFM_INITIALIZED: self->initialised (hWnd); break;
|
||||
case BFFM_VALIDATEFAILEDW: self->validateFailed (String ((LPCWSTR) lParam)); break;
|
||||
case BFFM_VALIDATEFAILEDA: self->validateFailed (String ((const char*) lParam)); break;
|
||||
default: break;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static UINT_PTR CALLBACK openCallback (HWND hwnd, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
|
||||
{
|
||||
auto hdlg = getDialogFromHWND (hwnd);
|
||||
|
||||
switch (uiMsg)
|
||||
{
|
||||
case WM_INITDIALOG:
|
||||
{
|
||||
if (auto* self = reinterpret_cast<Win32NativeFileChooser*> (((OPENFILENAMEW*) lParam)->lCustData))
|
||||
self->initDialog (hdlg);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_DESTROY:
|
||||
{
|
||||
if (auto* self = getNativeDialogList()[hdlg])
|
||||
self->destroyDialog (hdlg);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_NOTIFY:
|
||||
{
|
||||
auto ofn = reinterpret_cast<LPOFNOTIFY> (lParam);
|
||||
|
||||
if (ofn->hdr.code == CDN_SELCHANGE)
|
||||
if (auto* self = reinterpret_cast<Win32NativeFileChooser*> (ofn->lpOFN->lCustData))
|
||||
self->selectionChanged (hdlg);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static HWND getDialogFromHWND (HWND hwnd)
|
||||
{
|
||||
if (hwnd == nullptr)
|
||||
return nullptr;
|
||||
|
||||
HWND dialogH = GetParent (hwnd);
|
||||
|
||||
if (dialogH == nullptr)
|
||||
dialogH = hwnd;
|
||||
|
||||
return dialogH;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32NativeFileChooser)
|
||||
};
|
||||
|
||||
class FileChooser::Native final : public std::enable_shared_from_this<Native>,
|
||||
public Component,
|
||||
public FileChooser::Pimpl
|
||||
{
|
||||
public:
|
||||
Native (FileChooser& fileChooser, int flagsIn, FilePreviewComponent* previewComp)
|
||||
: owner (fileChooser),
|
||||
nativeFileChooser (std::make_unique<Win32NativeFileChooser> (this, flagsIn, previewComp, fileChooser.startingFile,
|
||||
fileChooser.title, fileChooser.filters))
|
||||
{
|
||||
auto mainMon = Desktop::getInstance().getDisplays().getPrimaryDisplay()->userBounds.toNearestInt();
|
||||
|
||||
setBounds (mainMon.getX() + mainMon.getWidth() / 4,
|
||||
mainMon.getY() + mainMon.getHeight() / 4,
|
||||
0, 0);
|
||||
|
||||
setOpaque (true);
|
||||
setAlwaysOnTop (WindowUtils::areThereAnyAlwaysOnTopWindows());
|
||||
addToDesktop (0);
|
||||
}
|
||||
|
||||
~Native() override
|
||||
{
|
||||
exitModalState (0);
|
||||
nativeFileChooser->cancel();
|
||||
}
|
||||
|
||||
void launch() override
|
||||
{
|
||||
std::weak_ptr<Native> safeThis = shared_from_this();
|
||||
|
||||
enterModalState (true, ModalCallbackFunction::create ([safeThis] (int)
|
||||
{
|
||||
if (auto locked = safeThis.lock())
|
||||
locked->owner.finished (locked->nativeFileChooser->results);
|
||||
}));
|
||||
|
||||
nativeFileChooser->open (true);
|
||||
}
|
||||
|
||||
void runModally() override
|
||||
{
|
||||
#if JUCE_MODAL_LOOPS_PERMITTED
|
||||
enterModalState (true);
|
||||
nativeFileChooser->open (false);
|
||||
exitModalState (nativeFileChooser->results.size() > 0 ? 1 : 0);
|
||||
nativeFileChooser->cancel();
|
||||
|
||||
owner.finished (nativeFileChooser->results);
|
||||
#else
|
||||
jassertfalse;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool canModalEventBeSentToComponent (const Component* targetComponent) override
|
||||
{
|
||||
if (targetComponent == nullptr)
|
||||
return false;
|
||||
|
||||
if (targetComponent == nativeFileChooser->getCustomComponent())
|
||||
return true;
|
||||
|
||||
return targetComponent->findParentComponentOfClass<FilePreviewComponent>() != nullptr;
|
||||
}
|
||||
|
||||
void inputAttemptWhenModal() override {}
|
||||
|
||||
private:
|
||||
FileChooser& owner;
|
||||
std::shared_ptr<Win32NativeFileChooser> nativeFileChooser;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
bool FileChooser::isPlatformDialogAvailable()
|
||||
{
|
||||
#if JUCE_DISABLE_NATIVE_FILECHOOSERS
|
||||
return false;
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::shared_ptr<FileChooser::Pimpl> FileChooser::showPlatformDialog (FileChooser& owner, int flags,
|
||||
FilePreviewComponent* preview)
|
||||
{
|
||||
return std::make_shared<FileChooser::Native> (owner, flags, preview);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,841 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
|
||||
const auto menuItemInvokedSelector = @selector (menuItemInvoked:);
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
//==============================================================================
|
||||
struct JuceMainMenuBarHolder final : private DeletedAtShutdown
|
||||
{
|
||||
JuceMainMenuBarHolder()
|
||||
: mainMenuBar ([[NSMenu alloc] initWithTitle: nsStringLiteral ("MainMenu")])
|
||||
{
|
||||
auto item = [mainMenuBar addItemWithTitle: nsStringLiteral ("Apple")
|
||||
action: nil
|
||||
keyEquivalent: nsEmptyString()];
|
||||
|
||||
auto appMenu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("Apple")];
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
|
||||
[NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
[mainMenuBar setSubmenu: appMenu forItem: item];
|
||||
[appMenu release];
|
||||
|
||||
[NSApp setMainMenu: mainMenuBar];
|
||||
}
|
||||
|
||||
~JuceMainMenuBarHolder()
|
||||
{
|
||||
clearSingletonInstance();
|
||||
|
||||
[NSApp setMainMenu: nil];
|
||||
[mainMenuBar release];
|
||||
}
|
||||
|
||||
NSMenu* mainMenuBar = nil;
|
||||
|
||||
JUCE_DECLARE_SINGLETON_SINGLETHREADED_INLINE (JuceMainMenuBarHolder, true)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class JuceMainMenuHandler final : private MenuBarModel::Listener,
|
||||
private DeletedAtShutdown
|
||||
{
|
||||
public:
|
||||
JuceMainMenuHandler()
|
||||
{
|
||||
static JuceMenuCallbackClass cls;
|
||||
callback = [cls.createInstance() init];
|
||||
JuceMenuCallbackClass::setOwner (callback, this);
|
||||
}
|
||||
|
||||
~JuceMainMenuHandler() override
|
||||
{
|
||||
setMenu (nullptr, nullptr, String());
|
||||
|
||||
jassert (instance == this);
|
||||
instance = nullptr;
|
||||
|
||||
[callback release];
|
||||
}
|
||||
|
||||
void setMenu (MenuBarModel* const newMenuBarModel,
|
||||
const PopupMenu* newExtraAppleMenuItems,
|
||||
const String& recentItemsName)
|
||||
{
|
||||
recentItemsMenuName = recentItemsName;
|
||||
|
||||
if (currentModel != newMenuBarModel)
|
||||
{
|
||||
if (currentModel != nullptr)
|
||||
currentModel->removeListener (this);
|
||||
|
||||
currentModel = newMenuBarModel;
|
||||
|
||||
if (currentModel != nullptr)
|
||||
currentModel->addListener (this);
|
||||
|
||||
menuBarItemsChanged (nullptr);
|
||||
}
|
||||
|
||||
extraAppleMenuItems.reset (createCopyIfNotNull (newExtraAppleMenuItems));
|
||||
}
|
||||
|
||||
void addTopLevelMenu (NSMenu* parent, const PopupMenu& child, const String& name, int menuId, int topLevelIndex)
|
||||
{
|
||||
NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
|
||||
action: nil
|
||||
keyEquivalent: nsEmptyString()];
|
||||
|
||||
NSMenu* sub = createMenu (child, name, menuId, topLevelIndex, true);
|
||||
|
||||
[parent setSubmenu: sub forItem: item];
|
||||
[sub release];
|
||||
}
|
||||
|
||||
void updateTopLevelMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy, const String& name, int menuId, int topLevelIndex)
|
||||
{
|
||||
// Note: This method used to update the contents of the existing menu in-place, but that caused
|
||||
// weird side-effects which messed-up keyboard focus when switching between windows. By creating
|
||||
// a new menu and replacing the old one with it, that problem seems to be avoided..
|
||||
NSMenu* menu = createMenu (menuToCopy, name, menuId, topLevelIndex, true);
|
||||
|
||||
removeItemRecursive ([parentItem submenu]);
|
||||
[parentItem setSubmenu: menu];
|
||||
|
||||
[menu release];
|
||||
}
|
||||
|
||||
void updateTopLevelMenu (NSMenu* menu)
|
||||
{
|
||||
NSMenu* superMenu = [menu supermenu];
|
||||
auto menuNames = currentModel->getMenuBarNames();
|
||||
auto indexOfMenu = (int) [superMenu indexOfItemWithSubmenu: menu] - 1;
|
||||
|
||||
if (indexOfMenu >= 0)
|
||||
{
|
||||
removeItemRecursive (menu);
|
||||
|
||||
auto updatedPopup = currentModel->getMenuForIndex (indexOfMenu, menuNames[indexOfMenu]);
|
||||
|
||||
for (PopupMenu::MenuItemIterator iter (updatedPopup); iter.next();)
|
||||
addMenuItem (iter, menu, 1, indexOfMenu);
|
||||
|
||||
[menu update];
|
||||
}
|
||||
}
|
||||
|
||||
void menuBarItemsChanged (MenuBarModel*) override
|
||||
{
|
||||
if (isOpen)
|
||||
{
|
||||
defferedUpdateRequested = true;
|
||||
return;
|
||||
}
|
||||
|
||||
lastUpdateTime = Time::getMillisecondCounter();
|
||||
|
||||
StringArray menuNames;
|
||||
if (currentModel != nullptr)
|
||||
menuNames = currentModel->getMenuBarNames();
|
||||
|
||||
auto* menuBar = getMainMenuBar();
|
||||
|
||||
while ([menuBar numberOfItems] > 1 + menuNames.size())
|
||||
removeItemRecursive (menuBar, static_cast<int> ([menuBar numberOfItems] - 1));
|
||||
|
||||
int menuId = 1;
|
||||
|
||||
for (int i = 0; i < menuNames.size(); ++i)
|
||||
{
|
||||
const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames[i]));
|
||||
|
||||
if (i >= [menuBar numberOfItems] - 1)
|
||||
addTopLevelMenu (menuBar, menu, menuNames[i], menuId, i);
|
||||
else
|
||||
updateTopLevelMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
|
||||
}
|
||||
}
|
||||
|
||||
void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info) override
|
||||
{
|
||||
if ((info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0
|
||||
&& info.invocationMethod != ApplicationCommandTarget::InvocationInfo::fromKeyPress)
|
||||
if (auto* item = findMenuItemWithCommandID (getMainMenuBar(), info.commandID))
|
||||
flashMenuBar ([item menu]);
|
||||
}
|
||||
|
||||
void invoke (const PopupMenu::Item& item, int topLevelIndex) const
|
||||
{
|
||||
if (currentModel != nullptr)
|
||||
{
|
||||
if (item.action != nullptr)
|
||||
{
|
||||
MessageManager::callAsync (item.action);
|
||||
return;
|
||||
}
|
||||
|
||||
if (item.customCallback != nullptr)
|
||||
if (! item.customCallback->menuItemTriggered())
|
||||
return;
|
||||
|
||||
if (item.commandManager != nullptr)
|
||||
{
|
||||
ApplicationCommandTarget::InvocationInfo info (item.itemID);
|
||||
info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
|
||||
|
||||
item.commandManager->invoke (info, true);
|
||||
}
|
||||
|
||||
MessageManager::callAsync ([=]
|
||||
{
|
||||
if (instance != nullptr)
|
||||
instance->invokeDirectly (item.itemID, topLevelIndex);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void invokeDirectly (int commandId, int topLevelIndex)
|
||||
{
|
||||
if (currentModel != nullptr)
|
||||
currentModel->menuItemSelected (commandId, topLevelIndex);
|
||||
}
|
||||
|
||||
void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
|
||||
const int topLevelMenuId, const int topLevelIndex)
|
||||
{
|
||||
const PopupMenu::Item& i = iter.getItem();
|
||||
NSString* text = juceStringToNS (i.text);
|
||||
|
||||
if (text == nil)
|
||||
text = nsEmptyString();
|
||||
|
||||
if (i.isSeparator)
|
||||
{
|
||||
[menuToAddTo addItem: [NSMenuItem separatorItem]];
|
||||
}
|
||||
else if (i.isSectionHeader)
|
||||
{
|
||||
NSMenuItem* item = [menuToAddTo addItemWithTitle: text
|
||||
action: nil
|
||||
keyEquivalent: nsEmptyString()];
|
||||
|
||||
[item setEnabled: false];
|
||||
}
|
||||
else if (i.subMenu != nullptr)
|
||||
{
|
||||
if (recentItemsMenuName.isNotEmpty() && i.text == recentItemsMenuName)
|
||||
{
|
||||
if (recent == nullptr)
|
||||
recent = std::make_unique<RecentFilesMenuItem>();
|
||||
|
||||
if (recent->recentItem != nil)
|
||||
{
|
||||
if (NSMenu* parent = [recent->recentItem menu])
|
||||
[parent removeItem: recent->recentItem];
|
||||
|
||||
[menuToAddTo addItem: recent->recentItem];
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
NSMenuItem* item = [menuToAddTo addItemWithTitle: text
|
||||
action: nil
|
||||
keyEquivalent: nsEmptyString()];
|
||||
|
||||
[item setTag: i.itemID];
|
||||
[item setEnabled: i.isEnabled];
|
||||
|
||||
NSMenu* sub = createMenu (*i.subMenu, i.text, topLevelMenuId, topLevelIndex, false);
|
||||
[menuToAddTo setSubmenu: sub forItem: item];
|
||||
[sub release];
|
||||
}
|
||||
else
|
||||
{
|
||||
auto item = [[NSMenuItem alloc] initWithTitle: text
|
||||
action: menuItemInvokedSelector
|
||||
keyEquivalent: nsEmptyString()];
|
||||
|
||||
[item setTag: topLevelIndex];
|
||||
[item setEnabled: i.isEnabled];
|
||||
[item setState: i.isTicked ? NSControlStateValueOn : NSControlStateValueOff];
|
||||
[item setTarget: (id) callback];
|
||||
|
||||
auto* juceItem = new PopupMenu::Item (i);
|
||||
juceItem->customComponent = nullptr;
|
||||
|
||||
[item setRepresentedObject: [createNSObjectFromJuceClass (juceItem) autorelease]];
|
||||
|
||||
if (i.commandManager != nullptr)
|
||||
{
|
||||
for (auto& kp : i.commandManager->getKeyMappings()->getKeyPressesAssignedToCommand (i.itemID))
|
||||
{
|
||||
if (kp != KeyPress::backspaceKey // (adding these is annoying because it flashes the menu bar
|
||||
&& kp != KeyPress::deleteKey) // every time you press the key while editing text)
|
||||
{
|
||||
juce_wchar key = kp.getTextCharacter();
|
||||
|
||||
if (key == 0)
|
||||
key = (juce_wchar) kp.getKeyCode();
|
||||
|
||||
[item setKeyEquivalent: juceStringToNS (String::charToString (key).toLowerCase())];
|
||||
[item setKeyEquivalentModifierMask: juceModsToNSMods (kp.getModifiers())];
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
[menuToAddTo addItem: item];
|
||||
[item release];
|
||||
}
|
||||
}
|
||||
|
||||
NSMenu* createMenu (const PopupMenu menu,
|
||||
const String& menuName,
|
||||
const int topLevelMenuId,
|
||||
const int topLevelIndex,
|
||||
const bool addDelegate)
|
||||
{
|
||||
NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
|
||||
|
||||
if (addDelegate)
|
||||
[m setDelegate: (id<NSMenuDelegate>) callback];
|
||||
|
||||
for (PopupMenu::MenuItemIterator iter (menu); iter.next();)
|
||||
addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
|
||||
|
||||
[m update];
|
||||
return m;
|
||||
}
|
||||
|
||||
static JuceMainMenuHandler* instance;
|
||||
|
||||
MenuBarModel* currentModel = nullptr;
|
||||
std::unique_ptr<PopupMenu> extraAppleMenuItems;
|
||||
uint32 lastUpdateTime = 0;
|
||||
NSObject* callback = nil;
|
||||
String recentItemsMenuName;
|
||||
bool isOpen = false, defferedUpdateRequested = false;
|
||||
|
||||
private:
|
||||
struct RecentFilesMenuItem
|
||||
{
|
||||
RecentFilesMenuItem() : recentItem (nil)
|
||||
{
|
||||
if (NSNib* menuNib = [[[NSNib alloc] initWithNibNamed: @"RecentFilesMenuTemplate" bundle: nil] autorelease])
|
||||
{
|
||||
NSArray* array = nil;
|
||||
|
||||
[menuNib instantiateWithOwner: NSApp
|
||||
topLevelObjects: &array];
|
||||
|
||||
for (id object in array)
|
||||
{
|
||||
if ([object isKindOfClass: [NSMenu class]])
|
||||
{
|
||||
if (NSArray* items = [object itemArray])
|
||||
{
|
||||
if (NSMenuItem* item = findRecentFilesItem (items))
|
||||
{
|
||||
recentItem = [item retain];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
~RecentFilesMenuItem()
|
||||
{
|
||||
[recentItem release];
|
||||
}
|
||||
|
||||
static NSMenuItem* findRecentFilesItem (NSArray* const items)
|
||||
{
|
||||
for (id object in items)
|
||||
if (NSArray* subMenuItems = [[object submenu] itemArray])
|
||||
for (id subObject in subMenuItems)
|
||||
if ([subObject isKindOfClass: [NSMenuItem class]])
|
||||
return subObject;
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSMenuItem* recentItem;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RecentFilesMenuItem)
|
||||
};
|
||||
|
||||
std::unique_ptr<RecentFilesMenuItem> recent;
|
||||
|
||||
//==============================================================================
|
||||
static NSMenuItem* findMenuItemWithCommandID (NSMenu* const menu, int commandID)
|
||||
{
|
||||
for (NSInteger i = [menu numberOfItems]; --i >= 0;)
|
||||
{
|
||||
NSMenuItem* m = [menu itemAtIndex: i];
|
||||
if (auto* menuItem = getJuceClassFromNSObject<PopupMenu::Item> ([m representedObject]))
|
||||
if (menuItem->itemID == commandID)
|
||||
return m;
|
||||
|
||||
if (NSMenu* sub = [m submenu])
|
||||
if (NSMenuItem* found = findMenuItemWithCommandID (sub, commandID))
|
||||
return found;
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
static void flashMenuBar (NSMenu* menu)
|
||||
{
|
||||
if ([[menu title] isEqualToString: nsStringLiteral ("Apple")])
|
||||
return;
|
||||
|
||||
[menu retain];
|
||||
|
||||
const unichar f35Key = NSF35FunctionKey;
|
||||
NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
|
||||
|
||||
NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: nsStringLiteral ("x")
|
||||
action: menuItemInvokedSelector
|
||||
keyEquivalent: f35String];
|
||||
|
||||
// When the f35Event is invoked, the item's enablement is checked and a
|
||||
// NSBeep is triggered if the item appears to be disabled.
|
||||
// This ValidatorClass exists solely to return YES from validateMenuItem.
|
||||
struct ValidatorClass final : public ObjCClass<NSObject>
|
||||
{
|
||||
ValidatorClass() : ObjCClass ("JUCEMenuValidator_")
|
||||
{
|
||||
addMethod (menuItemInvokedSelector, [] (id, SEL, NSMenuItem*) {});
|
||||
addMethod (@selector (validateMenuItem:), [] (id, SEL, NSMenuItem*) { return YES; });
|
||||
addProtocol (@protocol (NSMenuItemValidation));
|
||||
|
||||
registerClass();
|
||||
}
|
||||
};
|
||||
|
||||
static ValidatorClass validatorClass;
|
||||
static auto* vcInstance = validatorClass.createInstance();
|
||||
|
||||
[item setTarget: vcInstance];
|
||||
[menu insertItem: item atIndex: [menu numberOfItems]];
|
||||
[item release];
|
||||
|
||||
if ([menu indexOfItem: item] >= 0)
|
||||
{
|
||||
NSEvent* f35Event = [NSEvent keyEventWithType: NSEventTypeKeyDown
|
||||
location: NSZeroPoint
|
||||
modifierFlags: NSEventModifierFlagCommand
|
||||
timestamp: 0
|
||||
windowNumber: 0
|
||||
context: [NSGraphicsContext currentContext]
|
||||
characters: f35String
|
||||
charactersIgnoringModifiers: f35String
|
||||
isARepeat: NO
|
||||
keyCode: 0];
|
||||
|
||||
[menu performKeyEquivalent: f35Event];
|
||||
|
||||
if ([menu indexOfItem: item] >= 0)
|
||||
[menu removeItem: item]; // (this throws if the item isn't actually in the menu)
|
||||
}
|
||||
|
||||
[menu release];
|
||||
}
|
||||
|
||||
static unsigned int juceModsToNSMods (const ModifierKeys mods)
|
||||
{
|
||||
unsigned int m = 0;
|
||||
if (mods.isShiftDown()) m |= NSEventModifierFlagShift;
|
||||
if (mods.isCtrlDown()) m |= NSEventModifierFlagControl;
|
||||
if (mods.isAltDown()) m |= NSEventModifierFlagOption;
|
||||
if (mods.isCommandDown()) m |= NSEventModifierFlagCommand;
|
||||
return m;
|
||||
}
|
||||
|
||||
// Apple Bug: For some reason [NSMenu removeAllItems] seems to leak its objects
|
||||
// on shutdown, so we need this method to release the items one-by-one manually
|
||||
static void removeItemRecursive (NSMenu* parentMenu, int menuItemIndex)
|
||||
{
|
||||
if (isPositiveAndBelow (menuItemIndex, (int) [parentMenu numberOfItems]))
|
||||
{
|
||||
if (auto menuItem = [parentMenu itemAtIndex:menuItemIndex])
|
||||
{
|
||||
if (auto submenu = [menuItem submenu])
|
||||
removeItemRecursive (submenu);
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wnullable-to-nonnull-conversion")
|
||||
[parentMenu removeItem: menuItem];
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}
|
||||
}
|
||||
else
|
||||
jassertfalse;
|
||||
}
|
||||
|
||||
static void removeItemRecursive (NSMenu* menu)
|
||||
{
|
||||
if (menu != nullptr)
|
||||
{
|
||||
auto n = static_cast<int> ([menu numberOfItems]);
|
||||
|
||||
for (auto i = n; --i >= 0;)
|
||||
removeItemRecursive (menu, i);
|
||||
}
|
||||
}
|
||||
|
||||
static NSMenu* getMainMenuBar()
|
||||
{
|
||||
return JuceMainMenuBarHolder::getInstance()->mainMenuBar;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
struct JuceMenuCallbackClass final : public ObjCClass<NSObject>
|
||||
{
|
||||
JuceMenuCallbackClass() : ObjCClass ("JUCEMainMenu_")
|
||||
{
|
||||
addIvar<JuceMainMenuHandler*> ("owner");
|
||||
|
||||
addMethod (menuItemInvokedSelector, [] (id self, SEL, NSMenuItem* item)
|
||||
{
|
||||
if (auto* juceItem = getPopupMenuItem (item))
|
||||
getOwner (self)->invoke (*juceItem, static_cast<int> ([item tag]));
|
||||
});
|
||||
|
||||
addMethod (@selector (menuNeedsUpdate:), [] (id self, SEL, NSMenu* menu)
|
||||
{
|
||||
getOwner (self)->updateTopLevelMenu (menu);
|
||||
});
|
||||
|
||||
addMethod (@selector (validateMenuItem:), [] (id, SEL, NSMenuItem* item) -> BOOL
|
||||
{
|
||||
if (auto* juceItem = getPopupMenuItem (item))
|
||||
return juceItem->isEnabled;
|
||||
|
||||
return YES;
|
||||
});
|
||||
|
||||
addProtocol (@protocol (NSMenuDelegate));
|
||||
addProtocol (@protocol (NSMenuItemValidation));
|
||||
|
||||
registerClass();
|
||||
}
|
||||
|
||||
static void setOwner (id self, JuceMainMenuHandler* owner)
|
||||
{
|
||||
object_setInstanceVariable (self, "owner", owner);
|
||||
}
|
||||
|
||||
private:
|
||||
static PopupMenu::Item* getPopupMenuItem (NSMenuItem* item)
|
||||
{
|
||||
return getJuceClassFromNSObject<PopupMenu::Item> ([item representedObject]);
|
||||
}
|
||||
|
||||
static JuceMainMenuHandler* getOwner (id self)
|
||||
{
|
||||
return getIvar<JuceMainMenuHandler*> (self, "owner");
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
JuceMainMenuHandler* JuceMainMenuHandler::instance = nullptr;
|
||||
|
||||
//==============================================================================
|
||||
class TemporaryMainMenuWithStandardCommands
|
||||
{
|
||||
public:
|
||||
explicit TemporaryMainMenuWithStandardCommands (FilePreviewComponent* filePreviewComponent)
|
||||
: oldMenu (MenuBarModel::getMacMainMenu()), dummyModalComponent (filePreviewComponent)
|
||||
{
|
||||
if (auto* appleMenu = MenuBarModel::getMacExtraAppleItemsMenu())
|
||||
oldAppleMenu = std::make_unique<PopupMenu> (*appleMenu);
|
||||
|
||||
if (auto* handler = JuceMainMenuHandler::instance)
|
||||
oldRecentItems = handler->recentItemsMenuName;
|
||||
|
||||
MenuBarModel::setMacMainMenu (nullptr);
|
||||
|
||||
if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
|
||||
{
|
||||
NSMenu* menu = [[NSMenu alloc] initWithTitle: nsStringLiteral ("Edit")];
|
||||
NSMenuItem* item;
|
||||
|
||||
item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Cut"), nil)
|
||||
action: @selector (cut:) keyEquivalent: nsStringLiteral ("x")];
|
||||
[menu addItem: item];
|
||||
[item release];
|
||||
|
||||
item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Copy"), nil)
|
||||
action: @selector (copy:) keyEquivalent: nsStringLiteral ("c")];
|
||||
[menu addItem: item];
|
||||
[item release];
|
||||
|
||||
item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (nsStringLiteral ("Paste"), nil)
|
||||
action: @selector (paste:) keyEquivalent: nsStringLiteral ("v")];
|
||||
[menu addItem: item];
|
||||
[item release];
|
||||
|
||||
editMenuIndex = [mainMenu numberOfItems];
|
||||
|
||||
item = [mainMenu addItemWithTitle: NSLocalizedString (nsStringLiteral ("Edit"), nil)
|
||||
action: nil keyEquivalent: nsEmptyString()];
|
||||
[mainMenu setSubmenu: menu forItem: item];
|
||||
[menu release];
|
||||
}
|
||||
|
||||
// use a dummy modal component so that apps can tell that something is currently modal
|
||||
dummyModalComponent.enterModalState (false);
|
||||
}
|
||||
|
||||
~TemporaryMainMenuWithStandardCommands()
|
||||
{
|
||||
if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
|
||||
[mainMenu removeItemAtIndex:editMenuIndex];
|
||||
|
||||
MenuBarModel::setMacMainMenu (oldMenu, oldAppleMenu.get(), oldRecentItems);
|
||||
}
|
||||
|
||||
static bool checkModalEvent (FilePreviewComponent* preview, const Component* targetComponent)
|
||||
{
|
||||
if (targetComponent == nullptr)
|
||||
return false;
|
||||
|
||||
return (targetComponent == preview
|
||||
|| targetComponent->findParentComponentOfClass<FilePreviewComponent>() != nullptr);
|
||||
}
|
||||
|
||||
private:
|
||||
MenuBarModel* const oldMenu = nullptr;
|
||||
std::unique_ptr<PopupMenu> oldAppleMenu;
|
||||
String oldRecentItems;
|
||||
NSInteger editMenuIndex;
|
||||
|
||||
// The OS view already plays an alert when clicking outside
|
||||
// the modal comp, so this override avoids adding extra
|
||||
// inappropriate noises when the cancel button is pressed.
|
||||
// This override is also important because it stops the base class
|
||||
// calling ModalComponentManager::bringToFront, which can get
|
||||
// recursive when file dialogs are involved
|
||||
struct SilentDummyModalComp final : public Component
|
||||
{
|
||||
explicit SilentDummyModalComp (FilePreviewComponent* p)
|
||||
: preview (p) {}
|
||||
|
||||
void inputAttemptWhenModal() override {}
|
||||
|
||||
bool canModalEventBeSentToComponent (const Component* targetComponent) override
|
||||
{
|
||||
return checkModalEvent (preview, targetComponent);
|
||||
}
|
||||
|
||||
FilePreviewComponent* preview = nullptr;
|
||||
};
|
||||
|
||||
SilentDummyModalComp dummyModalComponent;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
namespace MainMenuHelpers
|
||||
{
|
||||
static NSString* translateMenuName (const String& name)
|
||||
{
|
||||
return NSLocalizedString (juceStringToNS (TRANS (name)), nil);
|
||||
}
|
||||
|
||||
static NSMenuItem* createMenuItem (NSMenu* menu, const String& name, SEL sel, NSString* key)
|
||||
{
|
||||
NSMenuItem* item = [[[NSMenuItem alloc] initWithTitle: translateMenuName (name)
|
||||
action: sel
|
||||
keyEquivalent: key] autorelease];
|
||||
[item setTarget: NSApp];
|
||||
[menu addItem: item];
|
||||
return item;
|
||||
}
|
||||
|
||||
static void createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
|
||||
{
|
||||
if (extraItems != nullptr && JuceMainMenuHandler::instance != nullptr && extraItems->getNumItems() > 0)
|
||||
{
|
||||
for (PopupMenu::MenuItemIterator iter (*extraItems); iter.next();)
|
||||
JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
|
||||
|
||||
[menu addItem: [NSMenuItem separatorItem]];
|
||||
}
|
||||
|
||||
// Services...
|
||||
NSMenuItem* services = [[[NSMenuItem alloc] initWithTitle: translateMenuName ("Services")
|
||||
action: nil keyEquivalent: nsEmptyString()] autorelease];
|
||||
[menu addItem: services];
|
||||
|
||||
NSMenu* servicesMenu = [[[NSMenu alloc] initWithTitle: translateMenuName ("Services")] autorelease];
|
||||
[menu setSubmenu: servicesMenu forItem: services];
|
||||
[NSApp setServicesMenu: servicesMenu];
|
||||
[menu addItem: [NSMenuItem separatorItem]];
|
||||
|
||||
createMenuItem (menu, TRANS ("Hide") + String (" ") + appName, @selector (hide:), nsStringLiteral ("h"));
|
||||
|
||||
[createMenuItem (menu, TRANS ("Hide Others"), @selector (hideOtherApplications:), nsStringLiteral ("h"))
|
||||
setKeyEquivalentModifierMask: NSEventModifierFlagCommand | NSEventModifierFlagOption];
|
||||
|
||||
createMenuItem (menu, TRANS ("Show All"), @selector (unhideAllApplications:), nsEmptyString());
|
||||
|
||||
[menu addItem: [NSMenuItem separatorItem]];
|
||||
|
||||
createMenuItem (menu, TRANS ("Quit") + String (" ") + appName, @selector (terminate:), nsStringLiteral ("q"));
|
||||
}
|
||||
|
||||
// Since our app has no NIB, this initialises a standard app menu...
|
||||
static void rebuildMainMenu (const PopupMenu* extraItems)
|
||||
{
|
||||
// this can't be used in a plugin!
|
||||
jassert (JUCEApplicationBase::isStandaloneApp());
|
||||
|
||||
if (auto* app = JUCEApplicationBase::getInstance())
|
||||
{
|
||||
if (auto* mainMenu = JuceMainMenuBarHolder::getInstance()->mainMenuBar)
|
||||
{
|
||||
if ([mainMenu numberOfItems] > 0)
|
||||
{
|
||||
if (auto appMenu = [[mainMenu itemAtIndex: 0] submenu])
|
||||
{
|
||||
[appMenu removeAllItems];
|
||||
MainMenuHelpers::createStandardAppMenu (appMenu, app->getApplicationName(), extraItems);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
|
||||
const PopupMenu* extraAppleMenuItems,
|
||||
const String& recentItemsMenuName)
|
||||
{
|
||||
if (getMacMainMenu() != newMenuBarModel)
|
||||
{
|
||||
JUCE_AUTORELEASEPOOL
|
||||
{
|
||||
if (newMenuBarModel == nullptr)
|
||||
{
|
||||
delete JuceMainMenuHandler::instance;
|
||||
jassert (JuceMainMenuHandler::instance == nullptr); // should be zeroed in the destructor
|
||||
jassert (extraAppleMenuItems == nullptr); // you can't specify some extra items without also supplying a model
|
||||
|
||||
extraAppleMenuItems = nullptr;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (JuceMainMenuHandler::instance == nullptr)
|
||||
JuceMainMenuHandler::instance = new JuceMainMenuHandler();
|
||||
|
||||
JuceMainMenuHandler::instance->setMenu (newMenuBarModel, extraAppleMenuItems, recentItemsMenuName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
|
||||
|
||||
if (newMenuBarModel != nullptr)
|
||||
newMenuBarModel->menuItemsChanged();
|
||||
}
|
||||
|
||||
MenuBarModel* MenuBarModel::getMacMainMenu()
|
||||
{
|
||||
if (auto* mm = JuceMainMenuHandler::instance)
|
||||
return mm->currentModel;
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const PopupMenu* MenuBarModel::getMacExtraAppleItemsMenu()
|
||||
{
|
||||
if (auto* mm = JuceMainMenuHandler::instance)
|
||||
return mm->extraAppleMenuItems.get();
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
using MenuTrackingChangedCallback = void (*)(bool);
|
||||
extern MenuTrackingChangedCallback menuTrackingChangedCallback;
|
||||
|
||||
static void mainMenuTrackingChanged (bool isTracking)
|
||||
{
|
||||
PopupMenu::dismissAllActiveMenus();
|
||||
|
||||
if (auto* menuHandler = JuceMainMenuHandler::instance)
|
||||
{
|
||||
menuHandler->isOpen = isTracking;
|
||||
|
||||
if (auto* model = menuHandler->currentModel)
|
||||
model->handleMenuBarActivate (isTracking);
|
||||
|
||||
if (menuHandler->defferedUpdateRequested && ! isTracking)
|
||||
{
|
||||
menuHandler->defferedUpdateRequested = false;
|
||||
menuHandler->menuBarItemsChanged (menuHandler->currentModel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void initialiseMacMainMenu()
|
||||
{
|
||||
menuTrackingChangedCallback = mainMenuTrackingChanged;
|
||||
|
||||
if (JuceMainMenuHandler::instance == nullptr)
|
||||
MainMenuHelpers::rebuildMainMenu (nullptr);
|
||||
}
|
||||
|
||||
// (used from other modules that need to create an NSMenu)
|
||||
NSMenu* createNSMenu (const PopupMenu&, const String&, int, int, bool);
|
||||
NSMenu* createNSMenu (const PopupMenu& menu, const String& name, int topLevelMenuId, int topLevelIndex, bool addDelegate)
|
||||
{
|
||||
initialiseMacMainMenu();
|
||||
|
||||
if (auto* mm = JuceMainMenuHandler::instance)
|
||||
return mm->createMenu (menu, name, topLevelMenuId, topLevelIndex, addDelegate);
|
||||
|
||||
jassertfalse; // calling this before making sure the OSX main menu stuff was initialised?
|
||||
return nil;
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,205 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#if JUCE_MAC
|
||||
|
||||
//==============================================================================
|
||||
class MouseCursor::PlatformSpecificHandle
|
||||
{
|
||||
public:
|
||||
PlatformSpecificHandle (const MouseCursor::StandardCursorType type)
|
||||
: cursorHandle (createCursor (type)) {}
|
||||
|
||||
PlatformSpecificHandle (const detail::CustomMouseCursorInfo& info)
|
||||
: cursorHandle (createCursor (info)) {}
|
||||
|
||||
~PlatformSpecificHandle()
|
||||
{
|
||||
[cursorHandle release];
|
||||
}
|
||||
|
||||
static void showInWindow (PlatformSpecificHandle* handle, ComponentPeer*)
|
||||
{
|
||||
auto c = [&]
|
||||
{
|
||||
if (handle == nullptr || handle->cursorHandle == nullptr)
|
||||
return [NSCursor arrowCursor];
|
||||
|
||||
return handle->cursorHandle;
|
||||
}();
|
||||
|
||||
[c set];
|
||||
}
|
||||
|
||||
private:
|
||||
static NSCursor* fromNSImage (NSImage* im, NSPoint hotspot)
|
||||
{
|
||||
NSCursor* c = [[NSCursor alloc] initWithImage: im
|
||||
hotSpot: hotspot];
|
||||
[im release];
|
||||
return c;
|
||||
}
|
||||
|
||||
static NSCursor* fromHIServices (const char* filename)
|
||||
{
|
||||
JUCE_AUTORELEASEPOOL
|
||||
{
|
||||
auto cursorPath = String ("/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/"
|
||||
"HIServices.framework/Versions/A/Resources/cursors/")
|
||||
+ filename;
|
||||
|
||||
NSImage* originalImage = [[NSImage alloc] initByReferencingFile: juceStringToNS (cursorPath + "/cursor.pdf")];
|
||||
NSSize originalSize = [originalImage size];
|
||||
NSImage* resultImage = [[NSImage alloc] initWithSize: originalSize];
|
||||
|
||||
for (int scale = 1; scale <= 4; ++scale)
|
||||
{
|
||||
NSAffineTransform* scaleTransform = [NSAffineTransform transform];
|
||||
[scaleTransform scaleBy: (float) scale];
|
||||
|
||||
if (CGImageRef rasterCGImage = [originalImage CGImageForProposedRect: nil
|
||||
context: nil
|
||||
hints: [NSDictionary dictionaryWithObjectsAndKeys: scaleTransform, NSImageHintCTM, nil]])
|
||||
{
|
||||
NSBitmapImageRep* imageRep = [[NSBitmapImageRep alloc] initWithCGImage: rasterCGImage];
|
||||
[imageRep setSize: originalSize];
|
||||
|
||||
[resultImage addRepresentation: imageRep];
|
||||
[imageRep release];
|
||||
}
|
||||
else
|
||||
{
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
[originalImage release];
|
||||
|
||||
NSDictionary* info = [NSDictionary dictionaryWithContentsOfFile: juceStringToNS (cursorPath + "/info.plist")];
|
||||
|
||||
auto hotspotX = (float) [[info valueForKey: nsStringLiteral ("hotx")] doubleValue];
|
||||
auto hotspotY = (float) [[info valueForKey: nsStringLiteral ("hoty")] doubleValue];
|
||||
|
||||
return fromNSImage (resultImage, NSMakePoint (hotspotX, hotspotY));
|
||||
}
|
||||
}
|
||||
static NSCursor* createCursor (const detail::CustomMouseCursorInfo& info)
|
||||
{
|
||||
return fromNSImage (imageToNSImage (info.image),
|
||||
NSMakePoint (info.hotspot.x, info.hotspot.y));
|
||||
}
|
||||
|
||||
static NSCursor* createCursor (const MouseCursor::StandardCursorType type)
|
||||
{
|
||||
JUCE_AUTORELEASEPOOL
|
||||
{
|
||||
NSCursor* c = nil;
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case NormalCursor:
|
||||
case ParentCursor: c = [NSCursor arrowCursor]; break;
|
||||
case NoCursor: return createCursor ({ ScaledImage (Image (Image::ARGB, 8, 8, true)), {} });
|
||||
case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
|
||||
case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
|
||||
case IBeamCursor: c = [NSCursor IBeamCursor]; break;
|
||||
case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
|
||||
case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
|
||||
case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
|
||||
case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
|
||||
|
||||
case CopyingCursor:
|
||||
{
|
||||
c = [NSCursor dragCopyCursor];
|
||||
break;
|
||||
}
|
||||
|
||||
case UpDownResizeCursor:
|
||||
case TopEdgeResizeCursor:
|
||||
case BottomEdgeResizeCursor:
|
||||
if (NSCursor* m = fromHIServices ("resizenorthsouth"))
|
||||
return m;
|
||||
|
||||
c = [NSCursor resizeUpDownCursor];
|
||||
break;
|
||||
|
||||
case LeftRightResizeCursor:
|
||||
if (NSCursor* m = fromHIServices ("resizeeastwest"))
|
||||
return m;
|
||||
|
||||
c = [NSCursor resizeLeftRightCursor];
|
||||
break;
|
||||
|
||||
case TopLeftCornerResizeCursor:
|
||||
case BottomRightCornerResizeCursor:
|
||||
return fromHIServices ("resizenorthwestsoutheast");
|
||||
|
||||
case TopRightCornerResizeCursor:
|
||||
case BottomLeftCornerResizeCursor:
|
||||
return fromHIServices ("resizenortheastsouthwest");
|
||||
|
||||
case UpDownLeftRightResizeCursor:
|
||||
return fromHIServices ("move");
|
||||
|
||||
case NumStandardCursorTypes:
|
||||
default:
|
||||
jassertfalse;
|
||||
break;
|
||||
}
|
||||
|
||||
[c retain];
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
NSCursor* cursorHandle;
|
||||
};
|
||||
|
||||
#else
|
||||
|
||||
class MouseCursor::PlatformSpecificHandle
|
||||
{
|
||||
public:
|
||||
PlatformSpecificHandle (const MouseCursor::StandardCursorType) {}
|
||||
PlatformSpecificHandle (const detail::CustomMouseCursorInfo&) {}
|
||||
|
||||
static void showInWindow (PlatformSpecificHandle*, ComponentPeer*) {}
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wzero-as-null-pointer-constant")
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
template <typename IDType>
|
||||
class MultiTouchMapper
|
||||
{
|
||||
public:
|
||||
MultiTouchMapper() {}
|
||||
|
||||
int getIndexOfTouch (ComponentPeer* peer, IDType touchID)
|
||||
{
|
||||
jassert (touchID != 0); // need to rethink this if IDs can be 0!
|
||||
TouchInfo info {touchID, peer};
|
||||
|
||||
int touchIndex = currentTouches.indexOf (info);
|
||||
|
||||
if (touchIndex < 0)
|
||||
{
|
||||
auto emptyTouchIndex = currentTouches.indexOf ({});
|
||||
touchIndex = (emptyTouchIndex >= 0 ? emptyTouchIndex : currentTouches.size());
|
||||
|
||||
currentTouches.set (touchIndex, info);
|
||||
}
|
||||
|
||||
return touchIndex;
|
||||
}
|
||||
|
||||
void clear()
|
||||
{
|
||||
currentTouches.clear();
|
||||
}
|
||||
|
||||
void clearTouch (int index)
|
||||
{
|
||||
currentTouches.set (index, {});
|
||||
}
|
||||
|
||||
bool areAnyTouchesActive() const noexcept
|
||||
{
|
||||
for (auto& t : currentTouches)
|
||||
if (t.touchId != 0)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void deleteAllTouchesForPeer (ComponentPeer* peer)
|
||||
{
|
||||
for (auto& t : currentTouches)
|
||||
if (t.owner == peer)
|
||||
t.touchId = 0;
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
struct TouchInfo
|
||||
{
|
||||
TouchInfo() noexcept : touchId (0), owner (nullptr) {}
|
||||
TouchInfo (IDType idToUse, ComponentPeer* peer) noexcept : touchId (idToUse), owner (peer) {}
|
||||
|
||||
TouchInfo (const TouchInfo&) = default;
|
||||
TouchInfo& operator= (const TouchInfo&) = default;
|
||||
TouchInfo (TouchInfo&&) noexcept = default;
|
||||
TouchInfo& operator= (TouchInfo&&) noexcept = default;
|
||||
|
||||
IDType touchId;
|
||||
ComponentPeer* owner;
|
||||
|
||||
bool operator== (const TouchInfo& o) const noexcept { return (touchId == o.touchId); }
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
Array<TouchInfo> currentTouches;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiTouchMapper)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::detail
|
||||
{
|
||||
|
||||
std::unique_ptr<ScopedMessageBoxInterface> ScopedMessageBoxInterface::create (const MessageBoxOptions& options)
|
||||
{
|
||||
class AndroidMessageBox final : public ScopedMessageBoxInterface
|
||||
{
|
||||
public:
|
||||
explicit AndroidMessageBox (const MessageBoxOptions& o) : opts (o) {}
|
||||
|
||||
void runAsync (std::function<void (std::optional<int>)> recipient) override
|
||||
{
|
||||
const auto makeDialogListener = [&recipient] (std::optional<int> result)
|
||||
{
|
||||
return new DialogListener ([recipient, result]
|
||||
{
|
||||
recipient (result);
|
||||
});
|
||||
};
|
||||
|
||||
auto* env = getEnv();
|
||||
|
||||
LocalRef<jobject> builder (env->NewObject (AndroidAlertDialogBuilder, AndroidAlertDialogBuilder.construct, getMainActivity().get()));
|
||||
|
||||
const auto setText = [&] (auto method, const String& text)
|
||||
{
|
||||
builder = LocalRef<jobject> (env->CallObjectMethod (builder, method, javaString (text).get()));
|
||||
};
|
||||
|
||||
setText (AndroidAlertDialogBuilder.setTitle, opts.getTitle());
|
||||
setText (AndroidAlertDialogBuilder.setMessage, opts.getMessage());
|
||||
|
||||
const auto& buttons = opts.getButtons();
|
||||
const auto cancelIter = buttons.size() == 1
|
||||
? buttons.begin()
|
||||
: std::find_if (buttons.begin(),
|
||||
buttons.end(),
|
||||
[] (const auto& b) { return b.getRole() == MessageBoxButtonRole::cancel; });
|
||||
|
||||
jboolean cancelable = cancelIter != buttons.end() || buttons.empty();
|
||||
builder = LocalRef<jobject> (env->CallObjectMethod (builder,
|
||||
AndroidAlertDialogBuilder.setCancelable,
|
||||
cancelable));
|
||||
|
||||
builder = LocalRef<jobject> (env->CallObjectMethod (builder,
|
||||
AndroidAlertDialogBuilder.setOnCancelListener,
|
||||
CreateJavaInterface (makeDialogListener (cancelIter != buttons.end() ? std::make_optional (cancelIter->getCode()) : std::nullopt),
|
||||
"android/content/DialogInterface$OnCancelListener").get()));
|
||||
|
||||
const jmethodID buttonTextSetters[] { AndroidAlertDialogBuilder.setPositiveButton,
|
||||
AndroidAlertDialogBuilder.setNegativeButton,
|
||||
AndroidAlertDialogBuilder.setNeutralButton };
|
||||
|
||||
const auto buttonOrder = AlertWindowHelpers::getSuggestedButtonOrder (opts);
|
||||
|
||||
for (const auto [index, method] : enumerate (buttonTextSetters, size_t{}))
|
||||
{
|
||||
if (buttonOrder.size() <= index)
|
||||
break;
|
||||
|
||||
const auto buttonIndex = buttonOrder[index];
|
||||
const auto& button = buttons[(size_t) buttonIndex];
|
||||
|
||||
if (button.getText().isEmpty())
|
||||
continue;
|
||||
|
||||
builder = LocalRef<jobject> (env->CallObjectMethod (builder,
|
||||
method,
|
||||
javaString (button.getText()).get(),
|
||||
CreateJavaInterface (makeDialogListener (button.getCode()),
|
||||
"android/content/DialogInterface$OnClickListener").get()));
|
||||
}
|
||||
|
||||
dialog = GlobalRef (LocalRef<jobject> (env->CallObjectMethod (builder, AndroidAlertDialogBuilder.create)));
|
||||
|
||||
LocalRef<jobject> window (env->CallObjectMethod (dialog, AndroidDialog.getWindow));
|
||||
|
||||
if (Desktop::getInstance().getKioskModeComponent() != nullptr)
|
||||
{
|
||||
env->CallVoidMethod (window, AndroidWindow.setFlags, FLAG_NOT_FOCUSABLE, FLAG_NOT_FOCUSABLE);
|
||||
LocalRef<jobject> decorView (env->CallObjectMethod (window, AndroidWindow.getDecorView));
|
||||
env->CallVoidMethod (decorView, AndroidView.setSystemUiVisibility, fullScreenFlags);
|
||||
}
|
||||
|
||||
env->CallVoidMethod (dialog, AndroidDialog.show);
|
||||
|
||||
if (Desktop::getInstance().getKioskModeComponent() != nullptr)
|
||||
env->CallVoidMethod (window, AndroidWindow.clearFlags, FLAG_NOT_FOCUSABLE);
|
||||
}
|
||||
|
||||
std::optional<int> runSync() override
|
||||
{
|
||||
// Not implemented on this platform.
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
void close() override
|
||||
{
|
||||
if (dialog != nullptr)
|
||||
getEnv()->CallVoidMethod (dialog, AndroidDialogInterface.dismiss);
|
||||
}
|
||||
|
||||
private:
|
||||
const MessageBoxOptions opts;
|
||||
GlobalRef dialog;
|
||||
};
|
||||
|
||||
return std::make_unique<AndroidMessageBox> (options);
|
||||
}
|
||||
|
||||
} // namespace juce::detail
|
||||
@@ -0,0 +1,188 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::detail
|
||||
{
|
||||
|
||||
std::unique_ptr<ScopedMessageBoxInterface> ScopedMessageBoxInterface::create (const MessageBoxOptions& options)
|
||||
{
|
||||
class MessageBox final : public ScopedMessageBoxInterface
|
||||
{
|
||||
public:
|
||||
explicit MessageBox (const MessageBoxOptions& opts) : options (opts) {}
|
||||
|
||||
void runAsync (std::function<void (std::optional<int>)> recipient) override
|
||||
{
|
||||
auto* peerToUse = std::invoke ([&]() -> UIViewComponentPeer*
|
||||
{
|
||||
if (auto* comp = options.getAssociatedComponent())
|
||||
if (auto* peer = comp->getPeer())
|
||||
return static_cast<UIViewComponentPeer*> (peer);
|
||||
|
||||
return iOSGlobals::currentlyFocusedPeer;
|
||||
});
|
||||
|
||||
if (peerToUse == nullptr)
|
||||
{
|
||||
// Since iOS8, alert windows need to be associated with a window, so you need to
|
||||
// have at least one window on screen when you use this
|
||||
jassertfalse;
|
||||
return;
|
||||
}
|
||||
|
||||
alert.reset ([[UIAlertController alertControllerWithTitle: juceStringToNS (options.getTitle())
|
||||
message: juceStringToNS (options.getMessage())
|
||||
preferredStyle: UIAlertControllerStyleAlert] retain]);
|
||||
|
||||
#if JUCE_IOS_API_VERSION_CAN_BE_BUILT (16, 0)
|
||||
if (@available (iOS 16, *))
|
||||
{
|
||||
const auto severity = options.getIconType() == MessageBoxIconType::WarningIcon
|
||||
? UIAlertControllerSeverityCritical
|
||||
: UIAlertControllerSeverityDefault;
|
||||
[alert.get() setSeverity: severity];
|
||||
}
|
||||
#endif
|
||||
|
||||
auto buttonOrder = AlertWindowHelpers::getSuggestedButtonOrder (options);
|
||||
|
||||
// The interface guidelines for iOS say that a two-button alert should have
|
||||
// the preferred action on the right, but buttons are presented left-to-right
|
||||
if (buttonOrder.size() == 2)
|
||||
std::reverse (buttonOrder.begin(), buttonOrder.end());
|
||||
|
||||
const auto& buttons = options.getButtons();
|
||||
|
||||
for (const auto buttonIndex : buttonOrder)
|
||||
{
|
||||
const auto& button = buttons[(size_t) buttonIndex];
|
||||
const auto text = button.getText();
|
||||
|
||||
if (text.isEmpty())
|
||||
continue;
|
||||
|
||||
const auto style = std::invoke ([&]
|
||||
{
|
||||
if (buttons.size() == 1)
|
||||
return UIAlertActionStyleCancel;
|
||||
|
||||
switch (button.getRole())
|
||||
{
|
||||
case MessageBoxButtonRole::normal:
|
||||
return UIAlertActionStyleDefault;
|
||||
|
||||
case MessageBoxButtonRole::cancel:
|
||||
return UIAlertActionStyleCancel;
|
||||
|
||||
case MessageBoxButtonRole::destroy:
|
||||
return UIAlertActionStyleDestructive;
|
||||
}
|
||||
|
||||
return UIAlertActionStyleDefault;
|
||||
});
|
||||
|
||||
auto* action = [UIAlertAction actionWithTitle: juceStringToNS (text)
|
||||
style: style
|
||||
handler: ^(UIAlertAction*)
|
||||
{
|
||||
const auto ind = buttonIndex;
|
||||
const auto opt = options;
|
||||
const auto r = recipient;
|
||||
MessageManager::callAsync ([ind, opt, r]
|
||||
{
|
||||
const auto code = opt.getButtons()[(size_t) ind].getCode();
|
||||
NullCheckedInvocation::invoke (r, code);
|
||||
});
|
||||
}];
|
||||
|
||||
[alert.get() addAction: action];
|
||||
|
||||
if (button.isPreferredAction())
|
||||
[alert.get() setPreferredAction: action];
|
||||
}
|
||||
|
||||
if ([alert.get() preferredAction] == nullptr)
|
||||
{
|
||||
const auto positionSelector = buttonOrder.size() == 2
|
||||
? @selector (lastObject)
|
||||
: @selector (firstObject);
|
||||
[alert.get() setPreferredAction: [[alert.get() actions] performSelector: positionSelector]];
|
||||
}
|
||||
|
||||
[peerToUse->controller presentViewController: alert.get()
|
||||
animated: YES
|
||||
completion: nil];
|
||||
}
|
||||
|
||||
std::optional<int> runSync() override
|
||||
{
|
||||
bool gotResult = false;
|
||||
std::optional<int> result;
|
||||
|
||||
JUCE_AUTORELEASEPOOL
|
||||
{
|
||||
runAsync ([&gotResult, &result] (std::optional<int> r)
|
||||
{
|
||||
gotResult = true;
|
||||
result = r;
|
||||
});
|
||||
|
||||
while (! gotResult)
|
||||
{
|
||||
JUCE_AUTORELEASEPOOL
|
||||
{
|
||||
[[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void close() override
|
||||
{
|
||||
if (auto* alertViewController = alert.get())
|
||||
[alertViewController dismissViewControllerAnimated: YES completion: nil];
|
||||
}
|
||||
|
||||
private:
|
||||
const MessageBoxOptions options;
|
||||
NSUniquePtr<UIAlertController> alert;
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageBox)
|
||||
};
|
||||
|
||||
return std::make_unique<MessageBox> (options);
|
||||
}
|
||||
|
||||
} // namespace juce::detail
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::detail
|
||||
{
|
||||
|
||||
std::unique_ptr<ScopedMessageBoxInterface> ScopedMessageBoxInterface::create (const MessageBoxOptions& options)
|
||||
{
|
||||
return detail::AlertWindowHelpers::create (options);
|
||||
}
|
||||
|
||||
} // namespace juce::detail
|
||||
@@ -0,0 +1,181 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::detail
|
||||
{
|
||||
|
||||
std::unique_ptr<ScopedMessageBoxInterface> ScopedMessageBoxInterface::create (const MessageBoxOptions& options)
|
||||
{
|
||||
class OSXMessageBox final : public ScopedMessageBoxInterface
|
||||
{
|
||||
public:
|
||||
explicit OSXMessageBox (const MessageBoxOptions& opts)
|
||||
: options (opts) {}
|
||||
|
||||
void runAsync (std::function<void (std::optional<int>)> recipient) override
|
||||
{
|
||||
const auto resultCodes = makeAlert();
|
||||
|
||||
const auto onDone = [resultCodes, recipient, opt = options] (NSModalResponse result)
|
||||
{
|
||||
const auto index = convertResult (result);
|
||||
const auto code = index.has_value() ? std::make_optional (resultCodes[*index]) : std::nullopt;
|
||||
|
||||
recipient (code);
|
||||
};
|
||||
|
||||
if (auto* comp = options.getAssociatedComponent())
|
||||
{
|
||||
if (auto* peer = comp->getPeer())
|
||||
{
|
||||
if (auto* view = static_cast<NSView*> (peer->getNativeHandle()))
|
||||
{
|
||||
if (auto* window = [view window])
|
||||
{
|
||||
[alertWindow.get() beginSheetModalForWindow: window completionHandler: ^(NSModalResponse result)
|
||||
{
|
||||
onDone (result);
|
||||
}];
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const NSUniquePtr<NSAlert> alert { [alertWindow.get() retain] };
|
||||
onDone ([alert.get() runModal]);
|
||||
}
|
||||
|
||||
std::optional<int> runSync() override
|
||||
{
|
||||
const auto resultCodes = makeAlert();
|
||||
const auto index = convertResult ([alertWindow.get() runModal]);
|
||||
|
||||
return index.has_value() ? std::make_optional (resultCodes[*index]) : std::nullopt;
|
||||
}
|
||||
|
||||
void close() override
|
||||
{
|
||||
if (alertWindow == nullptr)
|
||||
return;
|
||||
|
||||
auto* window = [alertWindow.get() window];
|
||||
|
||||
if ([NSApp modalWindow] == window)
|
||||
[NSApp stopModalWithCode: NSModalResponseAbort];
|
||||
else if (auto* parent = [window sheetParent])
|
||||
[parent endSheet: window returnCode: NSModalResponseAbort];
|
||||
|
||||
[window close];
|
||||
}
|
||||
|
||||
private:
|
||||
static std::optional<int> convertResult (NSModalResponse response)
|
||||
{
|
||||
switch (response)
|
||||
{
|
||||
case NSAlertFirstButtonReturn: return 0;
|
||||
case NSAlertSecondButtonReturn: return 1;
|
||||
case NSAlertThirdButtonReturn: return 2;
|
||||
default: break;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
Array<int> makeAlert()
|
||||
{
|
||||
NSAlert* alert = [[NSAlert alloc] init];
|
||||
|
||||
[alert setMessageText: juceStringToNS (options.getTitle())];
|
||||
[alert setInformativeText: juceStringToNS (options.getMessage())];
|
||||
|
||||
[alert setAlertStyle: options.getIconType() == MessageBoxIconType::WarningIcon ? NSAlertStyleCritical
|
||||
: NSAlertStyleInformational];
|
||||
|
||||
const auto buttonOrder = AlertWindowHelpers::getSuggestedButtonOrder (options);
|
||||
|
||||
const String defaultButtonStrings[] { TRANS ("OK"), String{}, String{} };
|
||||
Array<int> resultCodes;
|
||||
NSButton* cancelButton = nullptr;
|
||||
|
||||
for (const auto [index, fallback] : enumerate (defaultButtonStrings, size_t{}))
|
||||
{
|
||||
const auto* button = index < buttonOrder.size()
|
||||
? &options.getButtons()[(size_t) buttonOrder[index]]
|
||||
: nullptr;
|
||||
const auto text = button != nullptr ? button->getText() : fallback;
|
||||
|
||||
if (text.isEmpty())
|
||||
continue;
|
||||
|
||||
[alert addButtonWithTitle: juceStringToNS (text)];
|
||||
resultCodes.add (button != nullptr ? button->getCode() : resultCodes.size());
|
||||
|
||||
if (button == nullptr)
|
||||
continue;
|
||||
|
||||
if (button->getRole() == MessageBoxButtonRole::destroy)
|
||||
{
|
||||
if (@available (macOS 11, *))
|
||||
{
|
||||
[[[alert buttons] lastObject] setHasDestructiveAction: true];
|
||||
}
|
||||
}
|
||||
else if (button->getRole() == MessageBoxButtonRole::cancel)
|
||||
{
|
||||
cancelButton = [[alert buttons] lastObject];
|
||||
}
|
||||
}
|
||||
|
||||
if (cancelButton != nullptr && cancelButton != [[alert buttons] firstObject])
|
||||
[cancelButton setKeyEquivalent: @"\x1b"]; // The escape code from Events.h
|
||||
|
||||
alertWindow.reset (alert);
|
||||
|
||||
return resultCodes;
|
||||
}
|
||||
|
||||
NSUniquePtr<NSAlert> alertWindow;
|
||||
MessageBoxOptions options;
|
||||
std::unique_ptr<ModalComponentManager::Callback> callback;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OSXMessageBox)
|
||||
};
|
||||
|
||||
return std::make_unique<OSXMessageBox> (options);
|
||||
}
|
||||
|
||||
} // namespace juce::detail
|
||||
@@ -0,0 +1,239 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::detail
|
||||
{
|
||||
|
||||
std::unique_ptr<ScopedMessageBoxInterface> ScopedMessageBoxInterface::create (const MessageBoxOptions& options)
|
||||
{
|
||||
class WindowsTaskDialog : public ScopedMessageBoxInterface
|
||||
{
|
||||
public:
|
||||
explicit WindowsTaskDialog (const MessageBoxOptions& opts)
|
||||
: associatedComponent (opts.getAssociatedComponent()), options (opts) {}
|
||||
|
||||
void runAsync (std::function<void (std::optional<int>)> recipient) override
|
||||
{
|
||||
future = std::async (std::launch::async, [showMessageBox = getShowMessageBox(), recipient]
|
||||
{
|
||||
const auto messageResult = std::invoke ([&]() -> std::optional<int>
|
||||
{
|
||||
const auto initComResult = CoInitializeEx (nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
|
||||
|
||||
if (initComResult != S_OK)
|
||||
return {};
|
||||
|
||||
const ScopeGuard scope { [] { CoUninitialize(); } };
|
||||
|
||||
return showMessageBox != nullptr ? showMessageBox() : std::nullopt;
|
||||
});
|
||||
|
||||
NullCheckedInvocation::invoke (recipient, messageResult);
|
||||
});
|
||||
}
|
||||
|
||||
std::optional<int> runSync() override
|
||||
{
|
||||
if (auto showMessageBox = getShowMessageBox())
|
||||
return showMessageBox();
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void close() override
|
||||
{
|
||||
auto* toClose = std::invoke ([&]
|
||||
{
|
||||
const std::scoped_lock lock { mutex };
|
||||
closed = true;
|
||||
return std::exchange (windowHandle, nullptr);
|
||||
});
|
||||
|
||||
if (toClose != nullptr)
|
||||
EndDialog (toClose, 0);
|
||||
}
|
||||
|
||||
void setDialogWindowHandle (HWND dialogHandle)
|
||||
{
|
||||
const std::scoped_lock lock { mutex };
|
||||
windowHandle = dialogHandle;
|
||||
}
|
||||
|
||||
private:
|
||||
std::function<std::optional<int>()> getShowMessageBox()
|
||||
{
|
||||
const auto parent = associatedComponent != nullptr ? (HWND) associatedComponent->getWindowHandle() : nullptr;
|
||||
return getShowMessageBoxForParent (parent);
|
||||
}
|
||||
|
||||
/* Returns a function that should display a message box and return the result.
|
||||
|
||||
getShowMessageBoxForParent() will be called on the message thread.
|
||||
|
||||
The returned function will be called on a separate thread, in order to avoid blocking the
|
||||
message thread.
|
||||
|
||||
'this' is guaranteed to be alive when the returned function is called.
|
||||
*/
|
||||
std::function<std::optional<int>()> getShowMessageBoxForParent (const HWND parent)
|
||||
{
|
||||
JUCE_ASSERT_MESSAGE_THREAD
|
||||
|
||||
return [this, parent]() -> std::optional<int>
|
||||
{
|
||||
const auto title = options.getTitle();
|
||||
const auto message = options.getMessage();
|
||||
|
||||
static constexpr auto buttonIdOffset = 0x100;
|
||||
|
||||
TASKDIALOGCONFIG config{};
|
||||
|
||||
config.cbSize = sizeof (config);
|
||||
config.hwndParent = parent;
|
||||
config.pszWindowTitle = title.toWideCharPointer();
|
||||
config.pszContent = message.toWideCharPointer();
|
||||
config.hInstance = (HINSTANCE) Process::getCurrentModuleInstanceHandle();
|
||||
config.lpCallbackData = reinterpret_cast<LONG_PTR> (this);
|
||||
config.pfCallback = [] (HWND hwnd, UINT msg, WPARAM, LPARAM, LONG_PTR lpRefData)
|
||||
{
|
||||
if (auto* t = reinterpret_cast<WindowsTaskDialog*> (lpRefData))
|
||||
{
|
||||
switch (msg)
|
||||
{
|
||||
case TDN_CREATED:
|
||||
case TDN_DIALOG_CONSTRUCTED:
|
||||
t->setDialogWindowHandle (hwnd);
|
||||
break;
|
||||
|
||||
case TDN_DESTROYED:
|
||||
t->setDialogWindowHandle (nullptr);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return S_OK;
|
||||
};
|
||||
|
||||
const auto& buttons = options.getButtons();
|
||||
const auto cancelIter = buttons.size() == 1
|
||||
? buttons.begin()
|
||||
: std::find_if (buttons.begin(),
|
||||
buttons.end(),
|
||||
[] (const auto& b) { return b.getRole() == MessageBoxButtonRole::cancel; });
|
||||
|
||||
if (cancelIter != buttons.end() || buttons.empty())
|
||||
config.dwFlags |= TDF_ALLOW_DIALOG_CANCELLATION;
|
||||
|
||||
config.nDefaultButton = (int) std::invoke ([&]
|
||||
{
|
||||
const auto iter = std::find_if (buttons.begin(), buttons.end(), [] (const auto& b) { return b.isPreferredAction(); });
|
||||
return iter != buttons.end() ? buttonIdOffset + std::distance (buttons.begin(), iter) : 0;
|
||||
});
|
||||
|
||||
if (options.getIconType() == MessageBoxIconType::QuestionIcon)
|
||||
{
|
||||
if (auto* questionIcon = LoadIcon (nullptr, IDI_QUESTION))
|
||||
{
|
||||
config.hMainIcon = questionIcon;
|
||||
config.dwFlags |= TDF_USE_HICON_MAIN;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
config.pszMainIcon = std::invoke ([&]() -> LPWSTR
|
||||
{
|
||||
switch (options.getIconType())
|
||||
{
|
||||
case MessageBoxIconType::WarningIcon: return TD_WARNING_ICON;
|
||||
case MessageBoxIconType::InfoIcon: return TD_INFORMATION_ICON;
|
||||
|
||||
case MessageBoxIconType::QuestionIcon: JUCE_FALLTHROUGH
|
||||
case MessageBoxIconType::NoIcon:
|
||||
break;
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
});
|
||||
}
|
||||
|
||||
std::vector<String> buttonStrings;
|
||||
std::vector<TASKDIALOG_BUTTON> buttonLabels;
|
||||
Array<int> resultCodes;
|
||||
|
||||
for (const auto& buttonIndex : AlertWindowHelpers::getSuggestedButtonOrder (options))
|
||||
{
|
||||
const auto& button = options.getButtons()[(size_t) buttonIndex];
|
||||
if (const auto buttonText = button.getText(); buttonText.isNotEmpty())
|
||||
{
|
||||
buttonLabels.push_back ({ buttonIndex + buttonIdOffset,
|
||||
buttonStrings.emplace_back (buttonText).toWideCharPointer() });
|
||||
resultCodes.add (button.getCode());
|
||||
}
|
||||
}
|
||||
|
||||
config.pButtons = buttonLabels.data();
|
||||
config.cButtons = (UINT) buttonLabels.size();
|
||||
|
||||
int buttonId = 0;
|
||||
TaskDialogIndirect (&config, &buttonId, nullptr, nullptr);
|
||||
|
||||
const std::scoped_lock lock { mutex };
|
||||
|
||||
if (closed)
|
||||
return 0;
|
||||
|
||||
if (buttonId == IDCANCEL)
|
||||
return cancelIter != buttons.end() ? cancelIter->getCode() : 0;
|
||||
|
||||
const auto buttonIndex = buttonId - buttonIdOffset;
|
||||
|
||||
return isPositiveAndBelow (buttonIndex, buttons.size()) ? buttons[(size_t) buttonIndex].getCode() : 0;
|
||||
};
|
||||
}
|
||||
|
||||
Component::SafePointer<Component> associatedComponent;
|
||||
std::future<void> future;
|
||||
MessageBoxOptions options;
|
||||
|
||||
HWND windowHandle = nullptr;
|
||||
bool closed = false;
|
||||
std::mutex mutex;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTaskDialog)
|
||||
};
|
||||
|
||||
return std::make_unique<WindowsTaskDialog> (options);
|
||||
}
|
||||
|
||||
} // namespace juce::detail
|
||||
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce::detail
|
||||
{
|
||||
|
||||
/**
|
||||
Sets up a native control to be hosted on top of a JUCE component.
|
||||
*/
|
||||
class NativeModalWrapperComponent : public Component
|
||||
{
|
||||
public:
|
||||
void parentHierarchyChanged() final
|
||||
{
|
||||
auto* newPeer = dynamic_cast<UIViewComponentPeer*> (getPeer());
|
||||
|
||||
if (std::exchange (peer, newPeer) == newPeer)
|
||||
return;
|
||||
|
||||
if (peer == nullptr)
|
||||
return;
|
||||
|
||||
if (isIPad())
|
||||
{
|
||||
getViewController().preferredContentSize = peer->view.frame.size;
|
||||
|
||||
if (auto* popoverController = getViewController().popoverPresentationController)
|
||||
{
|
||||
popoverController.sourceView = peer->view;
|
||||
popoverController.sourceRect = CGRectMake (0.0f, (float) getHeight() - 10.0f, (float) getWidth(), 10.0f);
|
||||
popoverController.canOverlapSourceViewRect = YES;
|
||||
popoverController.delegate = popoverDelegate.get();
|
||||
}
|
||||
}
|
||||
|
||||
if (auto* parentController = peer->controller)
|
||||
[parentController showViewController: getViewController() sender: parentController];
|
||||
|
||||
peer->toFront (false);
|
||||
}
|
||||
|
||||
void displayNativeWindowModally (Component* parent)
|
||||
{
|
||||
setOpaque (false);
|
||||
|
||||
if (parent != nullptr)
|
||||
{
|
||||
[getViewController() setModalPresentationStyle: UIModalPresentationPageSheet];
|
||||
|
||||
setBounds (parent->getLocalBounds());
|
||||
|
||||
setAlwaysOnTop (true);
|
||||
parent->addAndMakeVisible (this);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (SystemStats::isRunningInAppExtensionSandbox())
|
||||
{
|
||||
// Opening a native top-level window in an AUv3 is not allowed (sandboxing). You need to specify a
|
||||
// parent component (for example your editor) to parent the native file chooser window. To do this
|
||||
// specify a parent component in the FileChooser's constructor!
|
||||
jassertfalse;
|
||||
return;
|
||||
}
|
||||
|
||||
auto chooserBounds = Desktop::getInstance().getDisplays().getPrimaryDisplay()->userBounds.getLargestIntegerWithin();
|
||||
setBounds (chooserBounds);
|
||||
|
||||
setAlwaysOnTop (true);
|
||||
setVisible (true);
|
||||
addToDesktop (0);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
virtual UIViewController* getViewController() const = 0;
|
||||
|
||||
static bool isIPad()
|
||||
{
|
||||
return [UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad;
|
||||
}
|
||||
|
||||
struct PopoverDelegateClass : public ObjCClass<NSObject<UIPopoverPresentationControllerDelegate>>
|
||||
{
|
||||
PopoverDelegateClass()
|
||||
: ObjCClass ("PopoverDelegateClass_")
|
||||
{
|
||||
addMethod (@selector (popoverPresentationController:willRepositionPopoverToRect:inView:), [] (id, SEL, UIPopoverPresentationController*, CGRect* rect, UIView** view)
|
||||
{
|
||||
const auto viewBounds = (*view).bounds;
|
||||
|
||||
rect->origin.x = 0.f;
|
||||
rect->origin.y = viewBounds.size.height - 10.f;
|
||||
rect->size.width = viewBounds.size.width;
|
||||
rect->size.height = 10.f;
|
||||
});
|
||||
|
||||
registerClass();
|
||||
}
|
||||
};
|
||||
|
||||
UIViewComponentPeer* peer = nullptr;
|
||||
NSUniquePtr<NSObject<UIPopoverPresentationControllerDelegate>> popoverDelegate { []
|
||||
{
|
||||
static PopoverDelegateClass cls;
|
||||
return cls.createInstance();
|
||||
}() };
|
||||
};
|
||||
|
||||
} // namespace juce::detail
|
||||
@@ -0,0 +1,261 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/*
|
||||
Manages the lifetime of a CVDisplayLinkRef for a single display, and automatically starts and
|
||||
stops it.
|
||||
*/
|
||||
|
||||
// From macOS 15+, warnings suggest the CVDisplayLink functions can be replaced with
|
||||
// NSView.displayLink(target:selector:), NSWindow.displayLink(target:selector:), or
|
||||
// NSScreen.displayLink(target:selector:) all of which were only introduced in macOS 14+ however,
|
||||
// it's not clear how these methods can be used to replace all use cases
|
||||
|
||||
JUCE_BEGIN_IGNORE_DEPRECATION_WARNINGS
|
||||
|
||||
class ScopedDisplayLink
|
||||
{
|
||||
public:
|
||||
static CGDirectDisplayID getDisplayIdForScreen (NSScreen* screen)
|
||||
{
|
||||
return (CGDirectDisplayID) [[screen.deviceDescription objectForKey: @"NSScreenNumber"] unsignedIntegerValue];
|
||||
}
|
||||
|
||||
ScopedDisplayLink (NSScreen* screenIn, std::function<void (double)> onCallbackIn)
|
||||
: displayId (getDisplayIdForScreen (screenIn)),
|
||||
link ([display = displayId]
|
||||
{
|
||||
CVDisplayLinkRef ptr = nullptr;
|
||||
[[maybe_unused]] const auto result = CVDisplayLinkCreateWithCGDisplay (display, &ptr);
|
||||
jassert (result == kCVReturnSuccess);
|
||||
jassert (ptr != nullptr);
|
||||
return ptr;
|
||||
}()),
|
||||
onCallback (std::move (onCallbackIn))
|
||||
{
|
||||
const auto callback = [] (CVDisplayLinkRef,
|
||||
const CVTimeStamp*,
|
||||
const CVTimeStamp* outputTime,
|
||||
CVOptionFlags,
|
||||
CVOptionFlags*,
|
||||
void* context) -> int
|
||||
{
|
||||
const auto outputTimeSec = (double) outputTime->videoTime / (double) outputTime->videoTimeScale;
|
||||
static_cast<const ScopedDisplayLink*> (context)->onCallback (outputTimeSec);
|
||||
return kCVReturnSuccess;
|
||||
};
|
||||
|
||||
[[maybe_unused]] const auto callbackResult = CVDisplayLinkSetOutputCallback (link.get(), callback, this);
|
||||
jassert (callbackResult == kCVReturnSuccess);
|
||||
|
||||
[[maybe_unused]] const auto startResult = CVDisplayLinkStart (link.get());
|
||||
jassert (startResult == kCVReturnSuccess);
|
||||
}
|
||||
|
||||
~ScopedDisplayLink() noexcept
|
||||
{
|
||||
if (link != nullptr)
|
||||
CVDisplayLinkStop (link.get());
|
||||
}
|
||||
|
||||
CGDirectDisplayID getDisplayId() const { return displayId; }
|
||||
|
||||
double getNominalVideoRefreshPeriodS() const
|
||||
{
|
||||
const auto nominalVideoRefreshPeriod = CVDisplayLinkGetNominalOutputVideoRefreshPeriod (link.get());
|
||||
|
||||
if ((nominalVideoRefreshPeriod.flags & kCVTimeIsIndefinite) == 0)
|
||||
return (double) nominalVideoRefreshPeriod.timeValue / (double) nominalVideoRefreshPeriod.timeScale;
|
||||
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
private:
|
||||
struct DisplayLinkDestructor
|
||||
{
|
||||
void operator() (CVDisplayLinkRef ptr) const
|
||||
{
|
||||
if (ptr != nullptr)
|
||||
CVDisplayLinkRelease (ptr);
|
||||
}
|
||||
};
|
||||
|
||||
CGDirectDisplayID displayId;
|
||||
std::unique_ptr<std::remove_pointer_t<CVDisplayLinkRef>, DisplayLinkDestructor> link;
|
||||
std::function<void (double)> onCallback;
|
||||
|
||||
// Instances can't be copied or moved, because 'this' is passed as context to
|
||||
// CVDisplayLinkSetOutputCallback
|
||||
JUCE_DECLARE_NON_COPYABLE (ScopedDisplayLink)
|
||||
JUCE_DECLARE_NON_MOVEABLE (ScopedDisplayLink)
|
||||
};
|
||||
|
||||
JUCE_END_IGNORE_DEPRECATION_WARNINGS
|
||||
|
||||
//==============================================================================
|
||||
/*
|
||||
Holds a ScopedDisplayLink for each screen. When the screen configuration changes, the
|
||||
ScopedDisplayLinks will be recreated automatically to match the new configuration.
|
||||
*/
|
||||
class PerScreenDisplayLinks
|
||||
{
|
||||
public:
|
||||
PerScreenDisplayLinks()
|
||||
{
|
||||
refreshScreens();
|
||||
}
|
||||
|
||||
using RefreshCallback = std::function<void (double)>;
|
||||
using Factory = std::function<RefreshCallback (CGDirectDisplayID)>;
|
||||
|
||||
/*
|
||||
Automatically unregisters a CVDisplayLink callback factory when ~Connection() is called.
|
||||
*/
|
||||
class Connection
|
||||
{
|
||||
public:
|
||||
Connection() = default;
|
||||
|
||||
Connection (PerScreenDisplayLinks& linksIn, std::list<Factory>::const_iterator it)
|
||||
: links (&linksIn), iter (it) {}
|
||||
|
||||
~Connection() noexcept
|
||||
{
|
||||
if (links != nullptr)
|
||||
links->unregisterFactory (iter);
|
||||
}
|
||||
|
||||
Connection (const Connection&) = delete;
|
||||
Connection& operator= (const Connection&) = delete;
|
||||
|
||||
Connection (Connection&& other) noexcept
|
||||
: links (std::exchange (other.links, nullptr)), iter (other.iter) {}
|
||||
|
||||
Connection& operator= (Connection&& other) noexcept
|
||||
{
|
||||
Connection { std::move (other) }.swap (*this);
|
||||
return *this;
|
||||
}
|
||||
|
||||
private:
|
||||
void swap (Connection& other) noexcept
|
||||
{
|
||||
std::swap (other.links, links);
|
||||
std::swap (other.iter, iter);
|
||||
}
|
||||
|
||||
PerScreenDisplayLinks* links = nullptr;
|
||||
std::list<Factory>::const_iterator iter;
|
||||
};
|
||||
|
||||
/* Stores the provided factory for as long as the returned Connection remains alive.
|
||||
|
||||
Whenever the screen configuration changes, the factory function will be called for each
|
||||
screen. The RefreshCallback returned by the factory will be called every time that screen's
|
||||
display link callback fires.
|
||||
*/
|
||||
[[nodiscard]] Connection registerFactory (Factory factory)
|
||||
{
|
||||
const ScopedLock lock (mutex);
|
||||
factories.push_front (std::move (factory));
|
||||
refreshScreens();
|
||||
return { *this, factories.begin() };
|
||||
}
|
||||
|
||||
double getNominalVideoRefreshPeriodSForScreen (CGDirectDisplayID display) const
|
||||
{
|
||||
const ScopedLock lock (mutex);
|
||||
|
||||
for (const auto& link : links)
|
||||
if (link.getDisplayId() == display)
|
||||
return link.getNominalVideoRefreshPeriodS();
|
||||
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
private:
|
||||
void unregisterFactory (std::list<Factory>::const_iterator iter)
|
||||
{
|
||||
const ScopedLock lock (mutex);
|
||||
factories.erase (iter);
|
||||
refreshScreens();
|
||||
}
|
||||
|
||||
void refreshScreens()
|
||||
{
|
||||
auto newLinks = [&]
|
||||
{
|
||||
std::list<ScopedDisplayLink> result;
|
||||
|
||||
for (NSScreen* screen in [NSScreen screens])
|
||||
{
|
||||
std::vector<RefreshCallback> callbacks;
|
||||
|
||||
for (auto& factory : factories)
|
||||
callbacks.push_back (factory (ScopedDisplayLink::getDisplayIdForScreen (screen)));
|
||||
|
||||
// This is the callback that will actually fire in response to this screen's display
|
||||
// link callback.
|
||||
result.emplace_back (screen, [cbs = std::move (callbacks)] (double timestampSec)
|
||||
{
|
||||
for (const auto& callback : cbs)
|
||||
callback (timestampSec);
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}();
|
||||
|
||||
const ScopedLock lock (mutex);
|
||||
links = std::move (newLinks);
|
||||
}
|
||||
|
||||
CriticalSection mutex;
|
||||
// This is a list rather than a vector so that the iterators are stable, even when items are
|
||||
// added/removed from the list. This is important because Connection objects store an iterator
|
||||
// internally, and may be created/destroyed arbitrarily.
|
||||
std::list<Factory> factories;
|
||||
// This is a list rather than a vector because ScopedDisplayLink is non-moveable.
|
||||
std::list<ScopedDisplayLink> links;
|
||||
|
||||
FunctionNotificationCenterObserver screenParamsObserver { NSApplicationDidChangeScreenParametersNotification,
|
||||
nullptr,
|
||||
[this] { refreshScreens(); } };
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#if ! JUCE_WINDOWS
|
||||
ScopedDPIAwarenessDisabler::ScopedDPIAwarenessDisabler() { ignoreUnused (previousContext); }
|
||||
ScopedDPIAwarenessDisabler::~ScopedDPIAwarenessDisabler() {}
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A Windows-specific class that temporarily sets the DPI awareness context of
|
||||
the current thread to be DPI unaware and resets it to the previous context
|
||||
when it goes out of scope.
|
||||
|
||||
If you create one of these before creating a top-level window, the window
|
||||
will be DPI unaware and bitmap stretched by the OS on a display with >100%
|
||||
scaling.
|
||||
|
||||
You shouldn't use this unless you really know what you are doing and
|
||||
are dealing with native HWNDs.
|
||||
|
||||
@tags{GUI}
|
||||
*/
|
||||
class JUCE_API ScopedDPIAwarenessDisabler
|
||||
{
|
||||
public:
|
||||
ScopedDPIAwarenessDisabler();
|
||||
~ScopedDPIAwarenessDisabler();
|
||||
|
||||
private:
|
||||
void* previousContext = nullptr;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
class [[nodiscard]] ScopedThreadDPIAwarenessSetter
|
||||
{
|
||||
public:
|
||||
explicit ScopedThreadDPIAwarenessSetter (void* nativeWindow);
|
||||
ScopedThreadDPIAwarenessSetter (ScopedThreadDPIAwarenessSetter&&) noexcept;
|
||||
ScopedThreadDPIAwarenessSetter& operator= (ScopedThreadDPIAwarenessSetter&&) noexcept;
|
||||
~ScopedThreadDPIAwarenessSetter();
|
||||
|
||||
class NativeImpl;
|
||||
|
||||
private:
|
||||
std::unique_ptr<NativeImpl> pimpl;
|
||||
|
||||
JUCE_LEAK_DETECTOR (ScopedThreadDPIAwarenessSetter)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
extern XContext windowHandleXContext;
|
||||
|
||||
/* Attaches a pointer to a given window, so that it can be retrieved with XFindContext on
|
||||
the windowHandleXContext.
|
||||
*/
|
||||
class ScopedWindowAssociation
|
||||
{
|
||||
public:
|
||||
ScopedWindowAssociation() = default;
|
||||
|
||||
ScopedWindowAssociation (void* associatedIn, Window windowIn)
|
||||
: associatedPointer ([&]() -> void*
|
||||
{
|
||||
if (associatedIn == nullptr)
|
||||
return nullptr;
|
||||
|
||||
// If you hit this, there's already a pointer associated with this window.
|
||||
const auto display = XWindowSystem::getInstance()->getDisplay();
|
||||
jassert (! getAssociatedPointer (display, windowIn).has_value());
|
||||
|
||||
if (X11Symbols::getInstance()->xSaveContext (display,
|
||||
static_cast<XID> (windowIn),
|
||||
windowHandleXContext,
|
||||
unalignedPointerCast<XPointer> (associatedIn)) != 0)
|
||||
{
|
||||
jassertfalse;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return associatedIn;
|
||||
}()),
|
||||
window (static_cast<XID> (windowIn)) {}
|
||||
|
||||
ScopedWindowAssociation (const ScopedWindowAssociation&) = delete;
|
||||
ScopedWindowAssociation& operator= (const ScopedWindowAssociation&) = delete;
|
||||
|
||||
ScopedWindowAssociation (ScopedWindowAssociation&& other) noexcept
|
||||
: associatedPointer (std::exchange (other.associatedPointer, nullptr)), window (other.window) {}
|
||||
|
||||
ScopedWindowAssociation& operator= (ScopedWindowAssociation&& other) noexcept
|
||||
{
|
||||
ScopedWindowAssociation { std::move (other) }.swap (*this);
|
||||
return *this;
|
||||
}
|
||||
|
||||
~ScopedWindowAssociation() noexcept
|
||||
{
|
||||
if (associatedPointer == nullptr)
|
||||
return;
|
||||
|
||||
const auto display = XWindowSystem::getInstance()->getDisplay();
|
||||
const auto ptr = getAssociatedPointer (display, window);
|
||||
|
||||
if (! ptr.has_value())
|
||||
{
|
||||
// If you hit this, something else has cleared this association before we were able to.
|
||||
jassertfalse;
|
||||
return;
|
||||
}
|
||||
|
||||
jassert (unalignedPointerCast<XPointer> (associatedPointer) == *ptr);
|
||||
|
||||
if (X11Symbols::getInstance()->xDeleteContext (display, window, windowHandleXContext) != 0)
|
||||
jassertfalse;
|
||||
}
|
||||
|
||||
bool isValid() const { return associatedPointer != nullptr; }
|
||||
|
||||
private:
|
||||
static std::optional<XPointer> getAssociatedPointer (Display* display, Window window)
|
||||
{
|
||||
XPointer ptr{};
|
||||
|
||||
if (X11Symbols::getInstance()->xFindContext (display, window, windowHandleXContext, &ptr) != 0)
|
||||
return std::nullopt;
|
||||
|
||||
return ptr;
|
||||
}
|
||||
|
||||
void swap (ScopedWindowAssociation& other) noexcept
|
||||
{
|
||||
std::swap (other.associatedPointer, associatedPointer);
|
||||
std::swap (other.window, window);
|
||||
}
|
||||
|
||||
void* associatedPointer = nullptr;
|
||||
XID window{};
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,300 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class VBlankThread : private Thread,
|
||||
private AsyncUpdater
|
||||
{
|
||||
public:
|
||||
using VBlankListener = ComponentPeer::VBlankListener;
|
||||
|
||||
VBlankThread (ComSmartPtr<IDXGIOutput> out,
|
||||
HMONITOR mon,
|
||||
VBlankListener& listener)
|
||||
: Thread (SystemStats::getJUCEVersion() + ": VBlankThread"),
|
||||
output (out),
|
||||
monitor (mon)
|
||||
{
|
||||
listeners.push_back (listener);
|
||||
startThread (Priority::highest);
|
||||
}
|
||||
|
||||
~VBlankThread() override
|
||||
{
|
||||
cancelPendingUpdate();
|
||||
|
||||
state |= flagExit;
|
||||
|
||||
stopThread (-1);
|
||||
}
|
||||
|
||||
void updateMonitor()
|
||||
{
|
||||
monitor = getMonitorFromOutput (output);
|
||||
}
|
||||
|
||||
HMONITOR getMonitor() const noexcept { return monitor; }
|
||||
|
||||
void addListener (VBlankListener& listener)
|
||||
{
|
||||
listeners.push_back (listener);
|
||||
}
|
||||
|
||||
bool removeListener (const VBlankListener& listener)
|
||||
{
|
||||
auto it = std::find_if (listeners.cbegin(),
|
||||
listeners.cend(),
|
||||
[&listener] (const auto& l) { return &(l.get()) == &listener; });
|
||||
|
||||
if (it != listeners.cend())
|
||||
{
|
||||
listeners.erase (it);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool hasNoListeners() const noexcept
|
||||
{
|
||||
return listeners.empty();
|
||||
}
|
||||
|
||||
bool hasListener (const VBlankListener& listener) const noexcept
|
||||
{
|
||||
return std::any_of (listeners.cbegin(),
|
||||
listeners.cend(),
|
||||
[&listener] (const auto& l) { return &(l.get()) == &listener; });
|
||||
}
|
||||
|
||||
static HMONITOR getMonitorFromOutput (ComSmartPtr<IDXGIOutput> output)
|
||||
{
|
||||
if (output == nullptr)
|
||||
return nullptr;
|
||||
|
||||
DXGI_OUTPUT_DESC desc = {};
|
||||
return (FAILED (output->GetDesc (&desc)) || ! desc.AttachedToDesktop)
|
||||
? nullptr
|
||||
: desc.Monitor;
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
void run() override
|
||||
{
|
||||
for (;;)
|
||||
{
|
||||
if (output->WaitForVBlank() == S_OK)
|
||||
{
|
||||
const auto now = Time::getMillisecondCounterHiRes();
|
||||
|
||||
if (now - lastVBlankEvent.exchange (now) < 1.0)
|
||||
sleep (1);
|
||||
|
||||
const auto stateToRead = state.fetch_or (flagPaintPending);
|
||||
|
||||
if ((stateToRead & flagExit) != 0)
|
||||
return;
|
||||
|
||||
if ((stateToRead & flagPaintPending) != 0)
|
||||
continue;
|
||||
|
||||
triggerAsyncUpdate();
|
||||
}
|
||||
else
|
||||
{
|
||||
sleep (1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void handleAsyncUpdate() override
|
||||
{
|
||||
const auto timestampSec = lastVBlankEvent / 1000.0;
|
||||
|
||||
for (auto& listener : listeners)
|
||||
listener.get().onVBlank (timestampSec);
|
||||
|
||||
state &= ~flagPaintPending;
|
||||
}
|
||||
|
||||
enum Flags
|
||||
{
|
||||
flagExit = 1 << 0,
|
||||
flagPaintPending = 1 << 1,
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
ComSmartPtr<IDXGIOutput> output;
|
||||
HMONITOR monitor = nullptr;
|
||||
std::vector<std::reference_wrapper<VBlankListener>> listeners;
|
||||
|
||||
std::atomic<double> lastVBlankEvent{};
|
||||
std::atomic<int> state{};
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VBlankThread)
|
||||
JUCE_DECLARE_NON_MOVEABLE (VBlankThread)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
class VBlankDispatcher final : public DeletedAtShutdown
|
||||
{
|
||||
public:
|
||||
void updateDisplay (ComponentPeer::VBlankListener& listener, HMONITOR monitor)
|
||||
{
|
||||
if (monitor == nullptr)
|
||||
{
|
||||
removeListener (listener);
|
||||
return;
|
||||
}
|
||||
|
||||
auto threadWithListener = threads.end();
|
||||
auto threadWithMonitor = threads.end();
|
||||
|
||||
for (auto it = threads.begin(); it != threads.end(); ++it)
|
||||
{
|
||||
if ((*it)->hasListener (listener))
|
||||
threadWithListener = it;
|
||||
|
||||
if ((*it)->getMonitor() == monitor)
|
||||
threadWithMonitor = it;
|
||||
|
||||
if (threadWithListener != threads.end()
|
||||
&& threadWithMonitor != threads.end())
|
||||
{
|
||||
if (threadWithListener == threadWithMonitor)
|
||||
return;
|
||||
|
||||
(*threadWithMonitor)->addListener (listener);
|
||||
|
||||
// This may invalidate iterators, so be careful!
|
||||
removeListener (threadWithListener, listener);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (threadWithMonitor != threads.end())
|
||||
{
|
||||
(*threadWithMonitor)->addListener (listener);
|
||||
return;
|
||||
}
|
||||
|
||||
if (threadWithListener != threads.end())
|
||||
removeListener (threadWithListener, listener);
|
||||
|
||||
for (const auto& adapter : directX->adapters.getAdapterArray())
|
||||
{
|
||||
for (UINT i = 0;; ++i)
|
||||
{
|
||||
ComSmartPtr<IDXGIOutput> output;
|
||||
const auto result = adapter->dxgiAdapter->EnumOutputs (i, output.resetAndGetPointerAddress());
|
||||
|
||||
if (result == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE)
|
||||
break;
|
||||
|
||||
if (result == DXGI_ERROR_NOT_FOUND)
|
||||
break;
|
||||
|
||||
if (VBlankThread::getMonitorFromOutput (output) != monitor)
|
||||
continue;
|
||||
|
||||
threads.emplace_back (std::make_unique<VBlankThread> (output, monitor, listener));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void removeListener (const ComponentPeer::VBlankListener& listener)
|
||||
{
|
||||
for (auto it = threads.begin(); it != threads.end(); ++it)
|
||||
if (removeListener (it, listener))
|
||||
return;
|
||||
}
|
||||
|
||||
void reconfigureDisplays()
|
||||
{
|
||||
directX->adapters.updateAdapters();
|
||||
|
||||
for (auto& thread : threads)
|
||||
thread->updateMonitor();
|
||||
|
||||
threads.erase (std::remove_if (threads.begin(),
|
||||
threads.end(),
|
||||
[] (const auto& thread) { return thread->getMonitor() == nullptr; }),
|
||||
threads.end());
|
||||
}
|
||||
|
||||
JUCE_DECLARE_SINGLETON_SINGLETHREADED_INLINE (VBlankDispatcher, false)
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
using Threads = std::vector<std::unique_ptr<VBlankThread>>;
|
||||
|
||||
VBlankDispatcher()
|
||||
{
|
||||
reconfigureDisplays();
|
||||
}
|
||||
|
||||
~VBlankDispatcher() override
|
||||
{
|
||||
threads.clear();
|
||||
clearSingletonInstance();
|
||||
}
|
||||
|
||||
// This may delete the corresponding thread and invalidate iterators,
|
||||
// so be careful!
|
||||
bool removeListener (Threads::iterator it, const ComponentPeer::VBlankListener& listener)
|
||||
{
|
||||
if ((*it)->removeListener (listener))
|
||||
{
|
||||
if ((*it)->hasNoListeners())
|
||||
threads.erase (it);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
Threads threads;
|
||||
SharedResourcePointer<DirectX> directX;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VBlankDispatcher)
|
||||
JUCE_DECLARE_NON_MOVEABLE (VBlankDispatcher)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
bool WindowUtils::areThereAnyAlwaysOnTopWindows()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
bool WindowUtils::areThereAnyAlwaysOnTopWindows()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
struct WindowUtilsInternal
|
||||
{
|
||||
inline static int numAlwaysOnTopPeers = 0;
|
||||
};
|
||||
|
||||
bool WindowUtils::areThereAnyAlwaysOnTopWindows()
|
||||
{
|
||||
return WindowUtilsInternal::numAlwaysOnTopPeers > 0;
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
bool WindowUtils::areThereAnyAlwaysOnTopWindows()
|
||||
{
|
||||
for (NSWindow* window in [NSApp windows])
|
||||
if ([window level] > NSNormalWindowLevel)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
static BOOL CALLBACK enumAlwaysOnTopWindows (HWND hwnd, LPARAM lParam)
|
||||
{
|
||||
if (IsWindowVisible (hwnd))
|
||||
{
|
||||
DWORD processID = 0;
|
||||
GetWindowThreadProcessId (hwnd, &processID);
|
||||
|
||||
if (processID == GetCurrentProcessId())
|
||||
{
|
||||
WINDOWINFO info{};
|
||||
|
||||
if (GetWindowInfo (hwnd, &info)
|
||||
&& (info.dwExStyle & WS_EX_TOPMOST) != 0)
|
||||
{
|
||||
*reinterpret_cast<bool*> (lParam) = true;
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
bool WindowUtils::areThereAnyAlwaysOnTopWindows()
|
||||
{
|
||||
bool anyAlwaysOnTopFound = false;
|
||||
EnumWindows (&enumAlwaysOnTopWindows, (LPARAM) &anyAlwaysOnTopFound);
|
||||
return anyAlwaysOnTopFound;
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,841 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
extern bool isIOSAppActive;
|
||||
|
||||
struct AppInactivityCallback // NB: careful, this declaration is duplicated in other modules
|
||||
{
|
||||
virtual ~AppInactivityCallback() = default;
|
||||
virtual void appBecomingInactive() = 0;
|
||||
};
|
||||
|
||||
// This is an internal list of callbacks (but currently used between modules)
|
||||
Array<AppInactivityCallback*> appBecomingInactiveCallbacks;
|
||||
|
||||
struct BadgeUpdateTrait
|
||||
{
|
||||
#if JUCE_IOS_API_VERSION_CAN_BE_BUILT (16, 0)
|
||||
API_AVAILABLE (ios (16))
|
||||
static void newFn (UIApplication*)
|
||||
{
|
||||
[[UNUserNotificationCenter currentNotificationCenter] setBadgeCount: 0 withCompletionHandler: nil];
|
||||
}
|
||||
#endif
|
||||
|
||||
static void oldFn (UIApplication* app)
|
||||
{
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
|
||||
app.applicationIconBadgeNumber = 0;
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}
|
||||
};
|
||||
|
||||
/* Each successful call to beginBackgroundTask must be balanced
|
||||
by a call to endBackgroundTask.
|
||||
*/
|
||||
class TaskHandle
|
||||
{
|
||||
public:
|
||||
TaskHandle() = default;
|
||||
|
||||
explicit TaskHandle (UIBackgroundTaskIdentifier t)
|
||||
: task (t) {}
|
||||
|
||||
~TaskHandle()
|
||||
{
|
||||
if (task != UIBackgroundTaskInvalid)
|
||||
[[UIApplication sharedApplication] endBackgroundTask:task];
|
||||
}
|
||||
|
||||
TaskHandle (TaskHandle&& other) noexcept
|
||||
{
|
||||
swap (other);
|
||||
}
|
||||
|
||||
TaskHandle& operator= (TaskHandle&& other) noexcept
|
||||
{
|
||||
TaskHandle { std::move (other) }.swap (*this);
|
||||
return *this;
|
||||
}
|
||||
|
||||
TaskHandle (const TaskHandle&) = delete;
|
||||
TaskHandle& operator= (const TaskHandle&) = delete;
|
||||
|
||||
private:
|
||||
void swap (TaskHandle& other) noexcept
|
||||
{
|
||||
std::swap (other.task, task);
|
||||
}
|
||||
|
||||
UIBackgroundTaskIdentifier task = UIBackgroundTaskInvalid;
|
||||
};
|
||||
|
||||
struct SceneUtils
|
||||
{
|
||||
// This will need to become more sophisticated to enable support for multiple scenes
|
||||
static void sceneDidBecomeActive()
|
||||
{
|
||||
ifelse_17_0<BadgeUpdateTrait> ([UIApplication sharedApplication]);
|
||||
isIOSAppActive = true;
|
||||
}
|
||||
|
||||
static void sceneWillResignActive()
|
||||
{
|
||||
isIOSAppActive = false;
|
||||
|
||||
for (int i = appBecomingInactiveCallbacks.size(); --i >= 0;)
|
||||
appBecomingInactiveCallbacks.getReference (i)->appBecomingInactive();
|
||||
}
|
||||
|
||||
template <typename Self>
|
||||
static void sceneDidEnterBackground ([[maybe_unused]] Self* s)
|
||||
{
|
||||
if (auto* app = JUCEApplicationBase::getInstance())
|
||||
{
|
||||
#if JUCE_EXECUTE_APP_SUSPEND_ON_BACKGROUND_TASK
|
||||
s->appSuspendTask = TaskHandle { [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"JUCE Suspend Task"
|
||||
expirationHandler:^{ s->appSuspendTask = {}; }] };
|
||||
|
||||
MessageManager::callAsync ([app, s]
|
||||
{
|
||||
app->suspended();
|
||||
s->appSuspendTask = {};
|
||||
});
|
||||
#else
|
||||
app->suspended();
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
static void sceneWillEnterForeground()
|
||||
{
|
||||
if (auto* app = JUCEApplicationBase::getInstance())
|
||||
app->resumed();
|
||||
}
|
||||
|
||||
SceneUtils() = delete;
|
||||
};
|
||||
} // namespace juce
|
||||
|
||||
API_AVAILABLE (ios (13.0))
|
||||
@interface JuceAppSceneDelegate : NSObject<UIWindowSceneDelegate>
|
||||
{
|
||||
@public
|
||||
TaskHandle appSuspendTask;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation JuceAppSceneDelegate
|
||||
{
|
||||
SharedResourcePointer<WindowSceneTracker> windowSceneTracker;
|
||||
}
|
||||
|
||||
- (void) scene: (UIScene*) scene
|
||||
willConnectToSession: (UISceneSession*) session
|
||||
options: (UISceneConnectionOptions*) connectionOptions
|
||||
{
|
||||
if ([scene isKindOfClass: UIWindowScene.class])
|
||||
windowSceneTracker->setWindowScene (static_cast<UIWindowScene*> (scene));
|
||||
else
|
||||
jassertfalse;
|
||||
}
|
||||
|
||||
- (void) sceneDidDisconnect: (UIScene*) scene
|
||||
{
|
||||
if (scene == windowSceneTracker->getWindowScene())
|
||||
windowSceneTracker->setWindowScene (nullptr);
|
||||
}
|
||||
|
||||
- (void) sceneDidBecomeActive: (UIScene*) scene
|
||||
{
|
||||
SceneUtils::sceneDidBecomeActive();
|
||||
}
|
||||
|
||||
- (void) sceneWillResignActive: (UIScene*) scene
|
||||
{
|
||||
SceneUtils::sceneWillResignActive();
|
||||
}
|
||||
|
||||
- (void) sceneDidEnterBackground: (UIScene*) scene
|
||||
{
|
||||
SceneUtils::sceneDidEnterBackground (self);
|
||||
}
|
||||
|
||||
- (void) sceneWillEnterForeground: (UIScene*) scene
|
||||
{
|
||||
SceneUtils::sceneWillEnterForeground();
|
||||
}
|
||||
|
||||
- (void) windowScene: (UIWindowScene*) windowScene
|
||||
didUpdateCoordinateSpace: (id<UICoordinateSpace>) previousCoordinateSpace
|
||||
interfaceOrientation: (UIInterfaceOrientation) previousInterfaceOrientation
|
||||
traitCollection: (UITraitCollection*) previousTraitCollection
|
||||
{
|
||||
windowSceneTracker->setWindowScene (windowScene);
|
||||
}
|
||||
@end
|
||||
|
||||
#if JUCE_PUSH_NOTIFICATIONS
|
||||
@interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate, UNUserNotificationCenterDelegate>
|
||||
#else
|
||||
@interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
|
||||
#endif
|
||||
{
|
||||
@public
|
||||
TaskHandle appSuspendTask;
|
||||
std::optional<ScopedJuceInitialiser_GUI> initialiser;
|
||||
}
|
||||
|
||||
- (id) init;
|
||||
- (void) dealloc;
|
||||
- (void) applicationDidFinishLaunching: (UIApplication*) application;
|
||||
- (void) applicationWillTerminate: (UIApplication*) application;
|
||||
- (void) applicationDidEnterBackground: (UIApplication*) application;
|
||||
- (void) applicationWillEnterForeground: (UIApplication*) application;
|
||||
- (void) applicationDidBecomeActive: (UIApplication*) application;
|
||||
- (void) applicationWillResignActive: (UIApplication*) application;
|
||||
- (void) application: (UIApplication*) application handleEventsForBackgroundURLSession: (NSString*) identifier
|
||||
completionHandler: (void (^)(void)) completionHandler;
|
||||
- (void) applicationDidReceiveMemoryWarning: (UIApplication *) application;
|
||||
|
||||
- (UISceneConfiguration*) application: (UIApplication*) application
|
||||
configurationForConnectingSceneSession: (UISceneSession*) connectingSceneSession
|
||||
options: (UISceneConnectionOptions*) options API_AVAILABLE (ios (13.0));
|
||||
|
||||
#if JUCE_PUSH_NOTIFICATIONS
|
||||
|
||||
- (void) application: (UIApplication*) application
|
||||
didRegisterForRemoteNotificationsWithDeviceToken: (NSData*) deviceToken;
|
||||
- (void) application: (UIApplication*) application
|
||||
didFailToRegisterForRemoteNotificationsWithError: (NSError*) error;
|
||||
- (void) application: (UIApplication*) application
|
||||
didReceiveRemoteNotification: (NSDictionary*) userInfo;
|
||||
- (void) application: (UIApplication*) application
|
||||
didReceiveRemoteNotification: (NSDictionary*) userInfo
|
||||
fetchCompletionHandler: (void (^)(UIBackgroundFetchResult result)) completionHandler;
|
||||
- (void) application: (UIApplication*) application
|
||||
handleActionWithIdentifier: (NSString*) identifier
|
||||
forRemoteNotification: (NSDictionary*) userInfo
|
||||
withResponseInfo: (NSDictionary*) responseInfo
|
||||
completionHandler: (void(^)()) completionHandler;
|
||||
|
||||
- (void) userNotificationCenter: (UNUserNotificationCenter*) center
|
||||
willPresentNotification: (UNNotification*) notification
|
||||
withCompletionHandler: (void (^)(UNNotificationPresentationOptions options)) completionHandler;
|
||||
- (void) userNotificationCenter: (UNUserNotificationCenter*) center
|
||||
didReceiveNotificationResponse: (UNNotificationResponse*) response
|
||||
withCompletionHandler: (void(^)())completionHandler;
|
||||
|
||||
#endif
|
||||
|
||||
@end
|
||||
|
||||
@implementation JuceAppStartupDelegate
|
||||
{
|
||||
NSObject* _pushNotificationsDelegate;
|
||||
}
|
||||
|
||||
- (id) init
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
#if JUCE_PUSH_NOTIFICATIONS
|
||||
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
|
||||
#endif
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void) dealloc
|
||||
{
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (void) applicationDidFinishLaunching: (UIApplication*) application
|
||||
{
|
||||
ignoreUnused (application);
|
||||
initialiser.emplace();
|
||||
|
||||
if (auto* app = JUCEApplicationBase::createInstance())
|
||||
{
|
||||
if (! app->initialiseApp())
|
||||
exit (app->shutdownApp());
|
||||
}
|
||||
else
|
||||
{
|
||||
jassertfalse; // you must supply an application object for an iOS app!
|
||||
}
|
||||
}
|
||||
|
||||
- (void) applicationWillTerminate: (UIApplication*) application
|
||||
{
|
||||
ignoreUnused (application);
|
||||
JUCEApplicationBase::appWillTerminateByForce();
|
||||
}
|
||||
|
||||
- (void) applicationDidEnterBackground: (UIApplication*) application
|
||||
{
|
||||
SceneUtils::sceneDidEnterBackground (self);
|
||||
}
|
||||
|
||||
- (void) applicationWillEnterForeground: (UIApplication*) application
|
||||
{
|
||||
SceneUtils::sceneWillEnterForeground();
|
||||
}
|
||||
|
||||
- (void) applicationDidBecomeActive: (UIApplication*) application
|
||||
{
|
||||
SceneUtils::sceneDidBecomeActive();
|
||||
}
|
||||
|
||||
- (void) applicationWillResignActive: (UIApplication*) application
|
||||
{
|
||||
SceneUtils::sceneWillResignActive();
|
||||
}
|
||||
|
||||
- (void) application: (UIApplication*) application handleEventsForBackgroundURLSession: (NSString*)identifier
|
||||
completionHandler: (void (^)(void))completionHandler
|
||||
{
|
||||
ignoreUnused (application);
|
||||
URL::DownloadTask::juce_iosURLSessionNotify (nsStringToJuce (identifier));
|
||||
completionHandler();
|
||||
}
|
||||
|
||||
- (void) applicationDidReceiveMemoryWarning: (UIApplication*) application
|
||||
{
|
||||
ignoreUnused (application);
|
||||
|
||||
if (auto* app = JUCEApplicationBase::getInstance())
|
||||
app->memoryWarningReceived();
|
||||
}
|
||||
|
||||
- (UISceneConfiguration*) application: (UIApplication*) application
|
||||
configurationForConnectingSceneSession: (UISceneSession*) connectingSceneSession
|
||||
options: (UISceneConnectionOptions*) options
|
||||
{
|
||||
auto* config = connectingSceneSession.configuration;
|
||||
config.delegateClass = JuceAppSceneDelegate.class;
|
||||
return config;
|
||||
}
|
||||
|
||||
- (void) setPushNotificationsDelegateToUse: (NSObject*) delegate
|
||||
{
|
||||
_pushNotificationsDelegate = delegate;
|
||||
}
|
||||
|
||||
#if JUCE_PUSH_NOTIFICATIONS
|
||||
|
||||
- (void) application: (UIApplication*) application
|
||||
didRegisterForRemoteNotificationsWithDeviceToken: (NSData*) deviceToken
|
||||
{
|
||||
ignoreUnused (application);
|
||||
|
||||
SEL selector = @selector (application:didRegisterForRemoteNotificationsWithDeviceToken:);
|
||||
|
||||
if (_pushNotificationsDelegate != nil && [_pushNotificationsDelegate respondsToSelector: selector])
|
||||
{
|
||||
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [_pushNotificationsDelegate methodSignatureForSelector: selector]];
|
||||
[invocation setSelector: selector];
|
||||
[invocation setTarget: _pushNotificationsDelegate];
|
||||
[invocation setArgument: &application atIndex:2];
|
||||
[invocation setArgument: &deviceToken atIndex:3];
|
||||
|
||||
[invocation invoke];
|
||||
}
|
||||
}
|
||||
|
||||
- (void) application: (UIApplication*) application
|
||||
didFailToRegisterForRemoteNotificationsWithError: (NSError*) error
|
||||
{
|
||||
ignoreUnused (application);
|
||||
|
||||
SEL selector = @selector (application:didFailToRegisterForRemoteNotificationsWithError:);
|
||||
|
||||
if (_pushNotificationsDelegate != nil && [_pushNotificationsDelegate respondsToSelector: selector])
|
||||
{
|
||||
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [_pushNotificationsDelegate methodSignatureForSelector: selector]];
|
||||
[invocation setSelector: selector];
|
||||
[invocation setTarget: _pushNotificationsDelegate];
|
||||
[invocation setArgument: &application atIndex:2];
|
||||
[invocation setArgument: &error atIndex:3];
|
||||
|
||||
[invocation invoke];
|
||||
}
|
||||
}
|
||||
|
||||
- (void) application: (UIApplication*) application
|
||||
didReceiveRemoteNotification: (NSDictionary*) userInfo
|
||||
{
|
||||
ignoreUnused (application);
|
||||
|
||||
SEL selector = @selector (application:didReceiveRemoteNotification:);
|
||||
|
||||
if (_pushNotificationsDelegate != nil && [_pushNotificationsDelegate respondsToSelector: selector])
|
||||
{
|
||||
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [_pushNotificationsDelegate methodSignatureForSelector: selector]];
|
||||
[invocation setSelector: selector];
|
||||
[invocation setTarget: _pushNotificationsDelegate];
|
||||
[invocation setArgument: &application atIndex:2];
|
||||
[invocation setArgument: &userInfo atIndex:3];
|
||||
|
||||
[invocation invoke];
|
||||
}
|
||||
}
|
||||
|
||||
- (void) application: (UIApplication*) application
|
||||
didReceiveRemoteNotification: (NSDictionary*) userInfo
|
||||
fetchCompletionHandler: (void (^)(UIBackgroundFetchResult result)) completionHandler
|
||||
{
|
||||
ignoreUnused (application);
|
||||
|
||||
SEL selector = @selector (application:didReceiveRemoteNotification:fetchCompletionHandler:);
|
||||
|
||||
if (_pushNotificationsDelegate != nil && [_pushNotificationsDelegate respondsToSelector: selector])
|
||||
{
|
||||
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [_pushNotificationsDelegate methodSignatureForSelector: selector]];
|
||||
[invocation setSelector: selector];
|
||||
[invocation setTarget: _pushNotificationsDelegate];
|
||||
[invocation setArgument: &application atIndex:2];
|
||||
[invocation setArgument: &userInfo atIndex:3];
|
||||
[invocation setArgument: &completionHandler atIndex:4];
|
||||
|
||||
[invocation invoke];
|
||||
}
|
||||
}
|
||||
|
||||
- (void) application: (UIApplication*) application
|
||||
handleActionWithIdentifier: (NSString*) identifier
|
||||
forRemoteNotification: (NSDictionary*) userInfo
|
||||
withResponseInfo: (NSDictionary*) responseInfo
|
||||
completionHandler: (void(^)()) completionHandler
|
||||
{
|
||||
ignoreUnused (application);
|
||||
|
||||
SEL selector = @selector (application:handleActionWithIdentifier:forRemoteNotification:withResponseInfo:completionHandler:);
|
||||
|
||||
if (_pushNotificationsDelegate != nil && [_pushNotificationsDelegate respondsToSelector: selector])
|
||||
{
|
||||
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [_pushNotificationsDelegate methodSignatureForSelector: selector]];
|
||||
[invocation setSelector: selector];
|
||||
[invocation setTarget: _pushNotificationsDelegate];
|
||||
[invocation setArgument: &application atIndex:2];
|
||||
[invocation setArgument: &identifier atIndex:3];
|
||||
[invocation setArgument: &userInfo atIndex:4];
|
||||
[invocation setArgument: &responseInfo atIndex:5];
|
||||
[invocation setArgument: &completionHandler atIndex:6];
|
||||
|
||||
[invocation invoke];
|
||||
}
|
||||
}
|
||||
|
||||
- (void) userNotificationCenter: (UNUserNotificationCenter*) center
|
||||
willPresentNotification: (UNNotification*) notification
|
||||
withCompletionHandler: (void (^)(UNNotificationPresentationOptions options)) completionHandler
|
||||
{
|
||||
ignoreUnused (center);
|
||||
|
||||
SEL selector = @selector (userNotificationCenter:willPresentNotification:withCompletionHandler:);
|
||||
|
||||
if (_pushNotificationsDelegate != nil && [_pushNotificationsDelegate respondsToSelector: selector])
|
||||
{
|
||||
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [_pushNotificationsDelegate methodSignatureForSelector: selector]];
|
||||
[invocation setSelector: selector];
|
||||
[invocation setTarget: _pushNotificationsDelegate];
|
||||
[invocation setArgument: ¢er atIndex:2];
|
||||
[invocation setArgument: ¬ification atIndex:3];
|
||||
[invocation setArgument: &completionHandler atIndex:4];
|
||||
|
||||
[invocation invoke];
|
||||
}
|
||||
}
|
||||
|
||||
- (void) userNotificationCenter: (UNUserNotificationCenter*) center
|
||||
didReceiveNotificationResponse: (UNNotificationResponse*) response
|
||||
withCompletionHandler: (void(^)()) completionHandler
|
||||
{
|
||||
ignoreUnused (center);
|
||||
|
||||
SEL selector = @selector (userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:);
|
||||
|
||||
if (_pushNotificationsDelegate != nil && [_pushNotificationsDelegate respondsToSelector: selector])
|
||||
{
|
||||
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [_pushNotificationsDelegate methodSignatureForSelector: selector]];
|
||||
[invocation setSelector: selector];
|
||||
[invocation setTarget: _pushNotificationsDelegate];
|
||||
[invocation setArgument: ¢er atIndex:2];
|
||||
[invocation setArgument: &response atIndex:3];
|
||||
[invocation setArgument: &completionHandler atIndex:4];
|
||||
|
||||
[invocation invoke];
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@end
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
int juce_iOSMain (int argc, const char* argv[], void* customDelegatePtr);
|
||||
int juce_iOSMain (int argc, const char* argv[], void* customDelegatePtr)
|
||||
{
|
||||
Class delegateClass = (customDelegatePtr != nullptr ? reinterpret_cast<Class> (customDelegatePtr) : [JuceAppStartupDelegate class]);
|
||||
|
||||
return UIApplicationMain (argc, const_cast<char**> (argv), nil, NSStringFromClass (delegateClass));
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void LookAndFeel::playAlertSound()
|
||||
{
|
||||
// TODO
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray&, bool, Component*, std::function<void()>)
|
||||
{
|
||||
jassertfalse; // no such thing on iOS!
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DragAndDropContainer::performExternalDragDropOfText (const String&, Component*, std::function<void()>)
|
||||
{
|
||||
jassertfalse; // no such thing on iOS!
|
||||
return false;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void Desktop::setScreenSaverEnabled (const bool isEnabled)
|
||||
{
|
||||
if (! SystemStats::isRunningInAppExtensionSandbox())
|
||||
[[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
|
||||
}
|
||||
|
||||
bool Desktop::isScreenSaverEnabled()
|
||||
{
|
||||
if (SystemStats::isRunningInAppExtensionSandbox())
|
||||
return true;
|
||||
|
||||
return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
Image detail::WindowingHelpers::createIconForFile (const File&)
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void SystemClipboard::copyTextToClipboard (const String& text)
|
||||
{
|
||||
[[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
|
||||
forPasteboardType: @"public.text"];
|
||||
}
|
||||
|
||||
String SystemClipboard::getTextFromClipboard()
|
||||
{
|
||||
return nsStringToJuce ([[UIPasteboard generalPasteboard] string]);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
bool detail::MouseInputSourceList::addSource()
|
||||
{
|
||||
addSource (sources.size(), MouseInputSource::InputSourceType::touch);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool detail::MouseInputSourceList::canUseTouch() const
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Desktop::canUseSemiTransparentWindows() noexcept
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
|
||||
static const auto darkModeSelector = @selector (darkModeChanged:);
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
class Desktop::NativeDarkModeChangeDetectorImpl
|
||||
{
|
||||
public:
|
||||
NativeDarkModeChangeDetectorImpl()
|
||||
{
|
||||
static DelegateClass delegateClass;
|
||||
delegate.reset ([delegateClass.createInstance() init]);
|
||||
observer.emplace (delegate.get(), darkModeSelector, UIViewComponentPeer::getDarkModeNotificationName(), nil);
|
||||
}
|
||||
|
||||
private:
|
||||
struct DelegateClass final : public ObjCClass<NSObject>
|
||||
{
|
||||
DelegateClass()
|
||||
: ObjCClass ("JUCEDelegate_")
|
||||
{
|
||||
addMethod (darkModeSelector, [] (id, SEL, NSNotification*) { Desktop::getInstance().darkModeChanged(); });
|
||||
registerClass();
|
||||
}
|
||||
};
|
||||
|
||||
NSUniquePtr<NSObject> delegate;
|
||||
Optional<ScopedNotificationCenterObserver> observer;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeDarkModeChangeDetectorImpl)
|
||||
};
|
||||
|
||||
std::unique_ptr<Desktop::NativeDarkModeChangeDetectorImpl> Desktop::createNativeDarkModeChangeDetectorImpl()
|
||||
{
|
||||
return std::make_unique<NativeDarkModeChangeDetectorImpl>();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
Point<float> MouseInputSource::getCurrentRawMousePosition()
|
||||
{
|
||||
return juce_lastMousePos;
|
||||
}
|
||||
|
||||
void MouseInputSource::setRawMousePosition (Point<float>)
|
||||
{
|
||||
}
|
||||
|
||||
double Desktop::getDefaultMasterScale()
|
||||
{
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
|
||||
{
|
||||
UIInterfaceOrientation orientation = SystemStats::isRunningInAppExtensionSandbox() ? UIInterfaceOrientationPortrait
|
||||
: getWindowOrientation();
|
||||
|
||||
return Orientations::convertToJuce (orientation);
|
||||
}
|
||||
|
||||
struct WindowInfo
|
||||
{
|
||||
explicit WindowInfo (const UIWindow* window)
|
||||
: WindowInfo (window, convertToRectInt (window.frame))
|
||||
{}
|
||||
|
||||
WindowInfo (const UIWindow* window, Rectangle<int> boundsIn)
|
||||
: screen (window.screen),
|
||||
bounds (boundsIn),
|
||||
safeInsets (window.safeAreaInsets.top,
|
||||
window.safeAreaInsets.left,
|
||||
window.safeAreaInsets.bottom,
|
||||
window.safeAreaInsets.right)
|
||||
{}
|
||||
|
||||
UIScreen* screen;
|
||||
Rectangle<int> bounds;
|
||||
BorderSize<double> safeInsets;
|
||||
};
|
||||
|
||||
static const UIWindow* findWindow (const UIView* view)
|
||||
{
|
||||
if (view == nullptr)
|
||||
return nullptr;
|
||||
|
||||
if (view.window != nullptr)
|
||||
return view.window;
|
||||
|
||||
return findWindow (view.superview);
|
||||
}
|
||||
|
||||
static const UIWindow* findWindow (const Desktop& desktop)
|
||||
{
|
||||
if (auto* c = desktop.getComponent (0))
|
||||
if (auto* p = static_cast<UIViewComponentPeer*> (c->getPeer()))
|
||||
if (auto* w = findWindow (p->view))
|
||||
return w;
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
API_AVAILABLE (ios (13.0))
|
||||
static CGRect getSceneBounds (UIWindowScene* scene)
|
||||
{
|
||||
#if JUCE_IOS_API_VERSION_MIN_REQUIRED_AT_LEAST (26, 0)
|
||||
return scene.effectiveGeometry.coordinateSpace.bounds;
|
||||
#else
|
||||
return scene.coordinateSpace.bounds;
|
||||
#endif
|
||||
}
|
||||
|
||||
static WindowInfo getWindowInfo (const Desktop& desktop)
|
||||
{
|
||||
if (! JUCEApplication::isStandaloneApp())
|
||||
if (const auto* window = findWindow (desktop))
|
||||
return WindowInfo { window };
|
||||
|
||||
if (@available (iOS 13, *))
|
||||
{
|
||||
SharedResourcePointer<WindowSceneTracker> windowSceneTracker;
|
||||
|
||||
// The display info window's frame may lag behind a scene resize until UIKit gets
|
||||
// around to laying it out, so take the bounds from the scene itself. The window is
|
||||
// still the right place to read the safe area insets from.
|
||||
if (const auto* window = windowSceneTracker->getDisplayInfoWindow())
|
||||
if (auto* scene = windowSceneTracker->getWindowScene())
|
||||
return WindowInfo { window, convertToRectInt (getSceneBounds (scene)) };
|
||||
}
|
||||
|
||||
// A window scene may not have connected yet, so a window without one is still needed on iOS 13 and later.
|
||||
JUCE_BEGIN_IGNORE_DEPRECATION_WARNINGS
|
||||
const NSUniquePtr<UIWindow> window { [[UIWindow alloc] init] };
|
||||
JUCE_END_IGNORE_DEPRECATION_WARNINGS
|
||||
|
||||
return WindowInfo { window.get() };
|
||||
}
|
||||
|
||||
bool Desktop::isDarkModeActive() const
|
||||
{
|
||||
return getWindowInfo (*this).screen.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void Displays::findDisplays (const Desktop& desktop)
|
||||
{
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
|
||||
static const auto keyboardShownSelector = @selector (juceKeyboardShown:);
|
||||
static const auto keyboardHiddenSelector = @selector (juceKeyboardHidden:);
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
class OnScreenKeyboardChangeDetectorImpl
|
||||
{
|
||||
public:
|
||||
OnScreenKeyboardChangeDetectorImpl()
|
||||
{
|
||||
static DelegateClass delegateClass;
|
||||
delegate.reset ([delegateClass.createInstance() init]);
|
||||
object_setInstanceVariable (delegate.get(), "owner", this);
|
||||
observers.emplace_back (delegate.get(), keyboardShownSelector, UIKeyboardDidShowNotification, nil);
|
||||
observers.emplace_back (delegate.get(), keyboardHiddenSelector, UIKeyboardDidHideNotification, nil);
|
||||
}
|
||||
|
||||
auto getInsets() const { return insets; }
|
||||
|
||||
private:
|
||||
struct DelegateClass final : public ObjCClass<NSObject>
|
||||
{
|
||||
DelegateClass()
|
||||
: ObjCClass ("JUCEOnScreenKeyboardObserver_")
|
||||
{
|
||||
addIvar<OnScreenKeyboardChangeDetectorImpl*> ("owner");
|
||||
|
||||
addMethod (keyboardShownSelector, [] (id self, SEL, NSNotification* notification)
|
||||
{
|
||||
setKeyboardScreenBounds (self, std::invoke ([&]() -> BorderSize<double>
|
||||
{
|
||||
auto* info = [notification userInfo];
|
||||
|
||||
if (info == nullptr)
|
||||
return {};
|
||||
|
||||
auto* value = static_cast<NSValue*> ([info objectForKey: UIKeyboardFrameEndUserInfoKey]);
|
||||
|
||||
if (value == nullptr)
|
||||
return {};
|
||||
|
||||
auto* display = Desktop::getInstance().getDisplays().getPrimaryDisplay();
|
||||
|
||||
if (display == nullptr)
|
||||
return {};
|
||||
|
||||
const auto rect = convertToRectInt ([value CGRectValue]);
|
||||
|
||||
BorderSize<double> result;
|
||||
|
||||
if (rect.getY() == display->logicalBounds.toNearestInt().getY())
|
||||
result.setTop (rect.getHeight());
|
||||
|
||||
if (rect.getBottom() == display->logicalBounds.toNearestInt().getBottom())
|
||||
result.setBottom (rect.getHeight());
|
||||
|
||||
return result;
|
||||
}));
|
||||
});
|
||||
|
||||
addMethod (keyboardHiddenSelector, [] (id self, SEL, NSNotification*)
|
||||
{
|
||||
setKeyboardScreenBounds (self, {});
|
||||
});
|
||||
|
||||
registerClass();
|
||||
}
|
||||
|
||||
private:
|
||||
static void setKeyboardScreenBounds (id self, BorderSize<double> insets)
|
||||
{
|
||||
if (std::exchange (getIvar<OnScreenKeyboardChangeDetectorImpl*> (self, "owner")->insets, insets) != insets)
|
||||
Desktop::getInstance().displays->refresh();
|
||||
}
|
||||
};
|
||||
|
||||
BorderSize<double> insets;
|
||||
NSUniquePtr<NSObject> delegate;
|
||||
std::vector<ScopedNotificationCenterObserver> observers;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OnScreenKeyboardChangeDetectorImpl)
|
||||
};
|
||||
|
||||
JUCE_AUTORELEASEPOOL
|
||||
{
|
||||
static OnScreenKeyboardChangeDetectorImpl keyboardChangeDetector;
|
||||
|
||||
// The main screen is not necessarily the one showing the app: an unfolded iPhone Duo
|
||||
// presents its scene on a separate, larger screen.
|
||||
const auto info = getWindowInfo (desktop);
|
||||
UIScreen* s = info.screen;
|
||||
|
||||
Display d;
|
||||
const auto masterScale = desktop.getGlobalScaleFactor();
|
||||
d.physicalBounds = convertToRectInt ([s bounds]) * s.nativeScale;
|
||||
const auto inverseScale = 1.0 / (double) masterScale;
|
||||
d.logicalBounds = convertToRectFloat ([s bounds]) * inverseScale;
|
||||
d.userBounds = info.bounds.toFloat() * inverseScale;
|
||||
d.safeAreaInsets = detail::WindowingHelpers::roundToInt (info.safeInsets.multipliedBy (inverseScale));
|
||||
d.keyboardInsets = detail::WindowingHelpers::roundToInt (keyboardChangeDetector.getInsets().multipliedBy (inverseScale));
|
||||
d.isMain = true;
|
||||
d.scale = masterScale * s.scale;
|
||||
d.dpi = 160 * d.scale;
|
||||
|
||||
displays.add (d);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,665 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
void LookAndFeel::playAlertSound()
|
||||
{
|
||||
NSBeep();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
static NSRect getDragRect (NSView* view, NSEvent* event)
|
||||
{
|
||||
auto eventPos = [event locationInWindow];
|
||||
|
||||
return [view convertRect: NSMakeRect (eventPos.x - 16.0f, eventPos.y - 16.0f, 32.0f, 32.0f)
|
||||
fromView: nil];
|
||||
}
|
||||
|
||||
static NSView* getNSViewForDragEvent (Component* sourceComp)
|
||||
{
|
||||
if (sourceComp == nullptr)
|
||||
if (auto* draggingSource = Desktop::getInstance().getDraggingMouseSource (0))
|
||||
sourceComp = draggingSource->getComponentUnderMouse();
|
||||
|
||||
if (sourceComp != nullptr)
|
||||
return (NSView*) sourceComp->getWindowHandle();
|
||||
|
||||
jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
|
||||
return nil;
|
||||
}
|
||||
|
||||
class NSDraggingSourceHelper final : public ObjCClass<NSObject<NSDraggingSource, NSPasteboardItemDataProvider>>
|
||||
{
|
||||
public:
|
||||
struct DataMembers
|
||||
{
|
||||
std::function<void()> callback;
|
||||
String text;
|
||||
NSDragOperation operation;
|
||||
Component::SafePointer<Component> originator;
|
||||
};
|
||||
|
||||
static auto* create (DataMembers members)
|
||||
{
|
||||
static NSDraggingSourceHelper draggingSourceHelper;
|
||||
auto* result = [[draggingSourceHelper.createInstance() init] autorelease];
|
||||
object_setInstanceVariable (result, "members", new DataMembers (std::move (members)));
|
||||
return result;
|
||||
}
|
||||
|
||||
private:
|
||||
static DataMembers* getMembers (id self)
|
||||
{
|
||||
return getIvar<DataMembers*> (self, "members");
|
||||
}
|
||||
|
||||
NSDraggingSourceHelper()
|
||||
: ObjCClass ("JUCENSDraggingSourceHelper_")
|
||||
{
|
||||
addIvar<DataMembers*> ("members");
|
||||
|
||||
addMethod (@selector (dealloc), [] (id self, SEL)
|
||||
{
|
||||
delete getMembers (self);
|
||||
sendSuperclassMessage<void> (self, @selector (dealloc));
|
||||
});
|
||||
|
||||
addMethod (@selector (pasteboard:item:provideDataForType:),
|
||||
[] (id self, SEL, NSPasteboard* sender, NSPasteboardItem*, NSString* type)
|
||||
{
|
||||
if ([type compare: NSPasteboardTypeString] == NSOrderedSame)
|
||||
if (auto* members = getMembers (self))
|
||||
[sender setData: [juceStringToNS (members->text) dataUsingEncoding: NSUTF8StringEncoding]
|
||||
forType: NSPasteboardTypeString];
|
||||
});
|
||||
|
||||
addMethod (@selector (draggingSession:sourceOperationMaskForDraggingContext:),
|
||||
[] (id self, SEL, NSDraggingSession*, NSDraggingContext) -> NSDragOperation
|
||||
{
|
||||
if (auto* members = getMembers (self))
|
||||
return members->operation;
|
||||
|
||||
return {};
|
||||
});
|
||||
|
||||
addMethod (@selector (draggingSession:endedAtPoint:operation:),
|
||||
[] (id self, SEL, NSDraggingSession*, NSPoint p, NSDragOperation)
|
||||
{
|
||||
// Our view doesn't receive a mouse up when the drag ends so we need to generate one here and send it...
|
||||
auto* members = getMembers (self);
|
||||
|
||||
if (members == nullptr)
|
||||
return;
|
||||
|
||||
auto* cgEvent = CGEventCreateMouseEvent (nullptr,
|
||||
kCGEventLeftMouseUp,
|
||||
CGPointMake (p.x, p.y),
|
||||
kCGMouseButtonLeft);
|
||||
|
||||
if (cgEvent != nullptr)
|
||||
if (id e = [NSEvent eventWithCGEvent: cgEvent])
|
||||
if (auto* view = getNSViewForDragEvent (members->originator))
|
||||
[view mouseUp: e];
|
||||
|
||||
NullCheckedInvocation::invoke (members->callback);
|
||||
});
|
||||
|
||||
addProtocol (@protocol (NSPasteboardItemDataProvider));
|
||||
addProtocol (@protocol (NSDraggingSource));
|
||||
|
||||
registerClass();
|
||||
}
|
||||
};
|
||||
|
||||
bool DragAndDropContainer::performExternalDragDropOfText (const String& text, Component* sourceComponent,
|
||||
std::function<void()> callback)
|
||||
{
|
||||
if (text.isEmpty())
|
||||
return false;
|
||||
|
||||
if (auto* view = getNSViewForDragEvent (sourceComponent))
|
||||
{
|
||||
JUCE_AUTORELEASEPOOL
|
||||
{
|
||||
if (auto event = [[view window] currentEvent])
|
||||
{
|
||||
auto* helper = NSDraggingSourceHelper::create ({ std::move (callback),
|
||||
text,
|
||||
NSDragOperationCopy,
|
||||
sourceComponent });
|
||||
|
||||
auto pasteboardItem = [[NSPasteboardItem new] autorelease];
|
||||
[pasteboardItem setDataProvider: helper
|
||||
forTypes: [NSArray arrayWithObjects: NSPasteboardTypeString, nil]];
|
||||
|
||||
auto dragItem = [[[NSDraggingItem alloc] initWithPasteboardWriter: pasteboardItem] autorelease];
|
||||
|
||||
NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: nsEmptyString()];
|
||||
[dragItem setDraggingFrame: getDragRect (view, event) contents: image];
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wnullable-to-nonnull-conversion")
|
||||
if (auto session = [view beginDraggingSessionWithItems: [NSArray arrayWithObject: dragItem]
|
||||
event: event
|
||||
source: helper])
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
{
|
||||
session.animatesToStartingPositionsOnCancelOrFail = YES;
|
||||
session.draggingFormation = NSDraggingFormationNone;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles,
|
||||
Component* sourceComponent, std::function<void()> callback)
|
||||
{
|
||||
if (files.isEmpty())
|
||||
return false;
|
||||
|
||||
if (auto* view = getNSViewForDragEvent (sourceComponent))
|
||||
{
|
||||
JUCE_AUTORELEASEPOOL
|
||||
{
|
||||
if (auto event = [[view window] currentEvent])
|
||||
{
|
||||
auto dragItems = [[[NSMutableArray alloc] init] autorelease];
|
||||
|
||||
for (auto& filename : files)
|
||||
{
|
||||
auto* nsFilename = juceStringToNS (filename);
|
||||
auto fileURL = [NSURL fileURLWithPath: nsFilename];
|
||||
auto dragItem = [[NSDraggingItem alloc] initWithPasteboardWriter: fileURL];
|
||||
|
||||
auto eventPos = [event locationInWindow];
|
||||
auto dragRect = [view convertRect: NSMakeRect (eventPos.x - 16.0f, eventPos.y - 16.0f, 32.0f, 32.0f)
|
||||
fromView: nil];
|
||||
auto dragImage = [[NSWorkspace sharedWorkspace] iconForFile: nsFilename];
|
||||
[dragItem setDraggingFrame: dragRect
|
||||
contents: dragImage];
|
||||
|
||||
[dragItems addObject: dragItem];
|
||||
[dragItem release];
|
||||
}
|
||||
|
||||
auto* helper = NSDraggingSourceHelper::create ({ std::move (callback),
|
||||
"",
|
||||
canMoveFiles ? NSDragOperationMove : NSDragOperationCopy,
|
||||
sourceComponent });
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wnullable-to-nonnull-conversion")
|
||||
return [view beginDraggingSessionWithItems: dragItems
|
||||
event: event
|
||||
source: helper] != nullptr;
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
bool Desktop::canUseSemiTransparentWindows() noexcept
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
Point<float> MouseInputSource::getCurrentRawMousePosition()
|
||||
{
|
||||
JUCE_AUTORELEASEPOOL
|
||||
{
|
||||
auto p = [NSEvent mouseLocation];
|
||||
return { (float) p.x, (float) (getMainScreenHeight() - p.y) };
|
||||
}
|
||||
}
|
||||
|
||||
static ComponentPeer* findPeerContainingPoint (Point<float> globalPos)
|
||||
{
|
||||
for (int i = 0; i < juce::ComponentPeer::getNumPeers(); ++i)
|
||||
{
|
||||
auto* peer = juce::ComponentPeer::getPeer (i);
|
||||
|
||||
if (peer->contains (peer->globalToLocal (globalPos).toInt(), false))
|
||||
return peer;
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void MouseInputSource::setRawMousePosition (Point<float> newPosition)
|
||||
{
|
||||
const auto oldPosition = Desktop::getInstance().getMainMouseSource().getRawScreenPosition();
|
||||
|
||||
// this rubbish needs to be done around the warp call, to avoid causing a
|
||||
// bizarre glitch..
|
||||
CGAssociateMouseAndMouseCursorPosition (false);
|
||||
CGWarpMouseCursorPosition (convertToCGPoint (newPosition));
|
||||
CGAssociateMouseAndMouseCursorPosition (true);
|
||||
|
||||
// Mouse enter and exit events seem to be always generated as a consequence of programmatically
|
||||
// moving the mouse. However, when the mouse stays within the same peer no mouse move event is
|
||||
// generated, and we lose track of the correct Component under the mouse. Hence, we need to
|
||||
// generate this missing event here.
|
||||
if (auto* peer = findPeerContainingPoint (newPosition); peer != nullptr
|
||||
&& peer == findPeerContainingPoint (oldPosition))
|
||||
{
|
||||
peer->handleMouseEvent (MouseInputSource::InputSourceType::mouse,
|
||||
peer->globalToLocal (newPosition),
|
||||
ModifierKeys::currentModifiers,
|
||||
0.0f,
|
||||
0.0f,
|
||||
Time::currentTimeMillis());
|
||||
}
|
||||
}
|
||||
|
||||
double Desktop::getDefaultMasterScale()
|
||||
{
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
|
||||
{
|
||||
return upright;
|
||||
}
|
||||
|
||||
bool Desktop::isDarkModeActive() const
|
||||
{
|
||||
return [[[NSUserDefaults standardUserDefaults] stringForKey: nsStringLiteral ("AppleInterfaceStyle")]
|
||||
isEqualToString: nsStringLiteral ("Dark")];
|
||||
}
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
|
||||
static const auto darkModeSelector = @selector (darkModeChanged:);
|
||||
static const auto keyboardVisibilitySelector = @selector (keyboardVisiblityChanged:);
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
|
||||
class Desktop::NativeDarkModeChangeDetectorImpl
|
||||
{
|
||||
public:
|
||||
NativeDarkModeChangeDetectorImpl()
|
||||
{
|
||||
static DelegateClass delegateClass;
|
||||
delegate.reset ([delegateClass.createInstance() init]);
|
||||
observer.emplace (delegate.get(),
|
||||
darkModeSelector,
|
||||
@"AppleInterfaceThemeChangedNotification",
|
||||
nil,
|
||||
[NSDistributedNotificationCenter class]);
|
||||
}
|
||||
|
||||
private:
|
||||
struct DelegateClass final : public ObjCClass<NSObject>
|
||||
{
|
||||
DelegateClass()
|
||||
: ObjCClass ("JUCEDelegate_")
|
||||
{
|
||||
addMethod (darkModeSelector, [] (id, SEL, NSNotification*) { Desktop::getInstance().darkModeChanged(); });
|
||||
registerClass();
|
||||
}
|
||||
};
|
||||
|
||||
NSUniquePtr<NSObject> delegate;
|
||||
Optional<ScopedNotificationCenterObserver> observer;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeDarkModeChangeDetectorImpl)
|
||||
};
|
||||
|
||||
std::unique_ptr<Desktop::NativeDarkModeChangeDetectorImpl> Desktop::createNativeDarkModeChangeDetectorImpl()
|
||||
{
|
||||
return std::make_unique<NativeDarkModeChangeDetectorImpl>();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
class ScreenSaverDefeater final : public Timer
|
||||
{
|
||||
public:
|
||||
ScreenSaverDefeater()
|
||||
{
|
||||
startTimer (5000);
|
||||
timerCallback();
|
||||
}
|
||||
|
||||
void timerCallback() override
|
||||
{
|
||||
if (Process::isForegroundProcess())
|
||||
{
|
||||
if (assertion == nullptr)
|
||||
assertion.reset (new PMAssertion());
|
||||
}
|
||||
else
|
||||
{
|
||||
assertion.reset();
|
||||
}
|
||||
}
|
||||
|
||||
struct PMAssertion
|
||||
{
|
||||
PMAssertion() : assertionID (kIOPMNullAssertionID)
|
||||
{
|
||||
[[maybe_unused]] IOReturn res = IOPMAssertionCreateWithName (kIOPMAssertionTypePreventUserIdleDisplaySleep,
|
||||
kIOPMAssertionLevelOn,
|
||||
CFSTR ("JUCE Playback"),
|
||||
&assertionID);
|
||||
jassert (res == kIOReturnSuccess);
|
||||
}
|
||||
|
||||
~PMAssertion()
|
||||
{
|
||||
if (assertionID != kIOPMNullAssertionID)
|
||||
IOPMAssertionRelease (assertionID);
|
||||
}
|
||||
|
||||
IOPMAssertionID assertionID;
|
||||
};
|
||||
|
||||
std::unique_ptr<PMAssertion> assertion;
|
||||
};
|
||||
|
||||
static std::unique_ptr<ScreenSaverDefeater> screenSaverDefeater;
|
||||
|
||||
void Desktop::setScreenSaverEnabled (const bool isEnabled)
|
||||
{
|
||||
if (isEnabled)
|
||||
screenSaverDefeater.reset();
|
||||
else if (screenSaverDefeater == nullptr)
|
||||
screenSaverDefeater.reset (new ScreenSaverDefeater());
|
||||
}
|
||||
|
||||
bool Desktop::isScreenSaverEnabled()
|
||||
{
|
||||
return screenSaverDefeater == nullptr;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
struct DisplaySettingsChangeCallback final : private DeletedAtShutdown
|
||||
{
|
||||
DisplaySettingsChangeCallback()
|
||||
{
|
||||
CGDisplayRegisterReconfigurationCallback (displayReconfigurationCallback, this);
|
||||
}
|
||||
|
||||
~DisplaySettingsChangeCallback()
|
||||
{
|
||||
CGDisplayRemoveReconfigurationCallback (displayReconfigurationCallback, this);
|
||||
clearSingletonInstance();
|
||||
}
|
||||
|
||||
static void displayReconfigurationCallback (CGDirectDisplayID, CGDisplayChangeSummaryFlags, void* userInfo)
|
||||
{
|
||||
if (auto* thisPtr = static_cast<DisplaySettingsChangeCallback*> (userInfo))
|
||||
NullCheckedInvocation::invoke (thisPtr->forceDisplayUpdate);
|
||||
}
|
||||
|
||||
std::function<void()> forceDisplayUpdate;
|
||||
|
||||
JUCE_DECLARE_SINGLETON_INLINE (DisplaySettingsChangeCallback, false)
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DisplaySettingsChangeCallback)
|
||||
};
|
||||
|
||||
static Rectangle<float> convertDisplayRect (NSRect r, CGFloat mainScreenBottom)
|
||||
{
|
||||
r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
|
||||
return convertToRectFloat (r);
|
||||
}
|
||||
|
||||
static Displays::Display getDisplayFromScreen (NSScreen* s, CGFloat& mainScreenBottom, const float masterScale)
|
||||
{
|
||||
Displays::Display d;
|
||||
|
||||
d.isMain = (approximatelyEqual (mainScreenBottom, 0.0));
|
||||
|
||||
if (d.isMain)
|
||||
mainScreenBottom = [s frame].size.height;
|
||||
|
||||
d.userBounds = convertDisplayRect ([s visibleFrame], mainScreenBottom) / masterScale;
|
||||
d.logicalBounds = convertDisplayRect ([s frame], mainScreenBottom) / masterScale;
|
||||
d.physicalBounds = (convertDisplayRect ([s frame], mainScreenBottom) * s.backingScaleFactor).toNearestInt();
|
||||
d.scale = masterScale;
|
||||
|
||||
if ([s respondsToSelector: @selector (backingScaleFactor)])
|
||||
d.scale *= s.backingScaleFactor;
|
||||
|
||||
NSSize dpi = [[[s deviceDescription] objectForKey: NSDeviceResolution] sizeValue];
|
||||
d.dpi = (dpi.width + dpi.height) / 2.0;
|
||||
|
||||
#if JUCE_MAC_API_VERSION_CAN_BE_BUILT (12, 0)
|
||||
if (@available (macOS 12.0, *))
|
||||
{
|
||||
const auto safeInsets = [s safeAreaInsets];
|
||||
d.safeAreaInsets = detail::WindowingHelpers::roundToInt (BorderSize<double> { safeInsets.top,
|
||||
safeInsets.left,
|
||||
safeInsets.bottom,
|
||||
safeInsets.right }.multipliedBy (1.0 / (double) masterScale));
|
||||
}
|
||||
#endif
|
||||
|
||||
return d;
|
||||
}
|
||||
|
||||
void Displays::findDisplays (const Desktop& desktop)
|
||||
{
|
||||
JUCE_AUTORELEASEPOOL
|
||||
{
|
||||
if (DisplaySettingsChangeCallback::getInstanceWithoutCreating() == nullptr)
|
||||
DisplaySettingsChangeCallback::getInstance()->forceDisplayUpdate = [this] { refresh(); };
|
||||
|
||||
CGFloat mainScreenBottom = 0;
|
||||
|
||||
for (NSScreen* s in [NSScreen screens])
|
||||
displays.add (getDisplayFromScreen (s, mainScreenBottom, desktop.getGlobalScaleFactor()));
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
static void selectImageForDrawing (const Image& image)
|
||||
{
|
||||
[NSGraphicsContext saveGraphicsState];
|
||||
[NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithCGContext: juce_getImageContext (image)
|
||||
flipped: false]];
|
||||
}
|
||||
|
||||
static void releaseImageAfterDrawing()
|
||||
{
|
||||
[[NSGraphicsContext currentContext] flushGraphics];
|
||||
[NSGraphicsContext restoreGraphicsState];
|
||||
}
|
||||
|
||||
Image detail::WindowingHelpers::createIconForFile (const File& file)
|
||||
{
|
||||
JUCE_AUTORELEASEPOOL
|
||||
{
|
||||
NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
|
||||
|
||||
Image result (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
|
||||
|
||||
selectImageForDrawing (result);
|
||||
[image drawAtPoint: NSMakePoint (0, 0)
|
||||
fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
|
||||
operation: NSCompositingOperationSourceOver fraction: 1.0f];
|
||||
releaseImageAfterDrawing();
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
static Image createNSWindowSnapshot (NSWindow* nsWindow)
|
||||
{
|
||||
JUCE_AUTORELEASEPOOL
|
||||
{
|
||||
const auto createImageFromCGImage = [&] (CGImageRef cgImage)
|
||||
{
|
||||
jassert (cgImage != nullptr);
|
||||
|
||||
const auto width = CGImageGetWidth (cgImage);
|
||||
const auto height = CGImageGetHeight (cgImage);
|
||||
const auto cgRect = CGRectMake (0, 0, (CGFloat) width, (CGFloat) height);
|
||||
const Image image (Image::ARGB, (int) width, (int) height, true);
|
||||
|
||||
CGContextDrawImage (juce_getImageContext (image), cgRect, cgImage);
|
||||
|
||||
return image;
|
||||
};
|
||||
|
||||
#if JUCE_MAC_API_VERSION_MIN_REQUIRED_AT_LEAST (14, 4)
|
||||
|
||||
if (dlopen ("/System/Library/Frameworks/ScreenCaptureKit.framework/ScreenCaptureKit", RTLD_LAZY) == nullptr)
|
||||
{
|
||||
DBG (dlerror());
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
std::promise<Image> result;
|
||||
|
||||
const auto windowId = nsWindow.windowNumber;
|
||||
const auto windowRect = [nsWindow.screen convertRectToBacking: nsWindow.frame].size;
|
||||
|
||||
const auto onSharableContent = [&] (SCShareableContent* content, NSError* contentError)
|
||||
{
|
||||
if (contentError != nullptr)
|
||||
{
|
||||
jassertfalse;
|
||||
result.set_value (Image{});
|
||||
return;
|
||||
}
|
||||
|
||||
const auto window = std::invoke ([&]() -> SCWindow*
|
||||
{
|
||||
for (SCWindow* w in content.windows)
|
||||
if (w.windowID == windowId)
|
||||
return w;
|
||||
|
||||
return nullptr;
|
||||
});
|
||||
|
||||
if (window == nullptr)
|
||||
{
|
||||
jassertfalse;
|
||||
result.set_value (Image{});
|
||||
return;
|
||||
}
|
||||
|
||||
Class contentFilterClass = NSClassFromString (@"SCContentFilter");
|
||||
SCContentFilter* filter = [[[contentFilterClass alloc] initWithDesktopIndependentWindow: window] autorelease];
|
||||
|
||||
Class streamConfigurationClass = NSClassFromString (@"SCStreamConfiguration");
|
||||
SCStreamConfiguration* config = [[[streamConfigurationClass alloc] init] autorelease];
|
||||
config.colorSpaceName = kCGColorSpaceSRGB;
|
||||
config.showsCursor = NO;
|
||||
config.ignoreShadowsSingleWindow = YES;
|
||||
config.captureResolution = SCCaptureResolutionBest;
|
||||
config.ignoreGlobalClipSingleWindow = YES;
|
||||
config.includeChildWindows = NO;
|
||||
config.width = (size_t) windowRect.width;
|
||||
config.height = (size_t) windowRect.height;
|
||||
|
||||
const auto onScreenshot = [&] (CGImageRef screenshot, NSError* screenshotError)
|
||||
{
|
||||
jassert (screenshotError == nullptr);
|
||||
result.set_value (screenshotError == nullptr ? createImageFromCGImage (screenshot) : Image{});
|
||||
};
|
||||
|
||||
Class screenshotManagerClass = NSClassFromString (@"SCScreenshotManager");
|
||||
[screenshotManagerClass captureImageWithFilter: filter
|
||||
configuration: config
|
||||
completionHandler: onScreenshot];
|
||||
};
|
||||
|
||||
Class shareableContentClass = NSClassFromString (@"SCShareableContent");
|
||||
[shareableContentClass getCurrentProcessShareableContentWithCompletionHandler: onSharableContent];
|
||||
|
||||
return result.get_future().get();
|
||||
|
||||
#else
|
||||
|
||||
JUCE_BEGIN_IGNORE_DEPRECATION_WARNINGS
|
||||
|
||||
if (auto cgImage = CGWindowListCreateImage (CGRectNull,
|
||||
kCGWindowListOptionIncludingWindow,
|
||||
(CGWindowID) [nsWindow windowNumber],
|
||||
kCGWindowImageBoundsIgnoreFraming))
|
||||
{
|
||||
return createImageFromCGImage ((CGImageRef) CFAutorelease (cgImage));
|
||||
}
|
||||
|
||||
JUCE_END_IGNORE_DEPRECATION_WARNINGS
|
||||
|
||||
// A screenshot couldn't be created, possibly a permissions issue?
|
||||
jassertfalse;
|
||||
return {};
|
||||
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
Image createSnapshotOfNativeWindow (void* nativeWindowHandle)
|
||||
{
|
||||
if (id windowOrView = (id) nativeWindowHandle)
|
||||
{
|
||||
if ([windowOrView isKindOfClass: [NSWindow class]])
|
||||
return createNSWindowSnapshot ((NSWindow*) windowOrView);
|
||||
|
||||
if ([windowOrView isKindOfClass: [NSView class]])
|
||||
return createNSWindowSnapshot ([(NSView*) windowOrView window]);
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void SystemClipboard::copyTextToClipboard (const String& text)
|
||||
{
|
||||
NSPasteboard* pb = [NSPasteboard generalPasteboard];
|
||||
|
||||
[pb declareTypes: [NSArray arrayWithObject: NSPasteboardTypeString]
|
||||
owner: nil];
|
||||
|
||||
[pb setString: juceStringToNS (text)
|
||||
forType: NSPasteboardTypeString];
|
||||
}
|
||||
|
||||
String SystemClipboard::getTextFromClipboard()
|
||||
{
|
||||
return nsStringToJuce ([[NSPasteboard generalPasteboard] stringForType: NSPasteboardTypeString]);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
#if JUCE_WINDOWS
|
||||
|
||||
namespace juce::detail
|
||||
{
|
||||
|
||||
class WindowsHooks::Hooks
|
||||
{
|
||||
public:
|
||||
Hooks() = default;
|
||||
|
||||
~Hooks()
|
||||
{
|
||||
if (keyboardHook != nullptr)
|
||||
UnhookWindowsHookEx (keyboardHook);
|
||||
}
|
||||
|
||||
static inline std::weak_ptr<Hooks> weak;
|
||||
|
||||
private:
|
||||
static LRESULT CALLBACK keyboardHookCallback (int nCode, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
auto& msg = *reinterpret_cast<MSG*> (lParam);
|
||||
|
||||
if (nCode == HC_ACTION && wParam == PM_REMOVE && HWNDComponentPeer::offerKeyMessageToJUCEWindow (msg))
|
||||
{
|
||||
msg = {};
|
||||
msg.message = WM_USER;
|
||||
return 0;
|
||||
}
|
||||
|
||||
return CallNextHookEx (getSingleton()->keyboardHook, nCode, wParam, lParam);
|
||||
}
|
||||
|
||||
HHOOK keyboardHook = SetWindowsHookEx (WH_GETMESSAGE,
|
||||
keyboardHookCallback,
|
||||
(HINSTANCE) juce::Process::getCurrentModuleInstanceHandle(),
|
||||
GetCurrentThreadId());
|
||||
};
|
||||
|
||||
auto WindowsHooks::getSingleton() -> std::shared_ptr<Hooks>
|
||||
{
|
||||
auto& weak = Hooks::weak;
|
||||
|
||||
if (auto locked = weak.lock())
|
||||
return locked;
|
||||
|
||||
auto strong = std::make_shared<Hooks>();
|
||||
weak = strong;
|
||||
return strong;
|
||||
}
|
||||
|
||||
} // namespace juce::detail
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
#if JUCE_WINDOWS
|
||||
|
||||
namespace juce::detail
|
||||
{
|
||||
|
||||
class WindowsHooks
|
||||
{
|
||||
public:
|
||||
WindowsHooks() = default;
|
||||
|
||||
private:
|
||||
class Hooks;
|
||||
|
||||
static std::shared_ptr<Hooks> getSingleton();
|
||||
|
||||
std::shared_ptr<Hooks> hooks = getSingleton();
|
||||
};
|
||||
|
||||
} // namespace juce::detail
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,261 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
namespace X11SymbolHelpers
|
||||
{
|
||||
|
||||
template <typename FuncPtr>
|
||||
struct SymbolBinding
|
||||
{
|
||||
FuncPtr& func;
|
||||
const char* name;
|
||||
};
|
||||
|
||||
template <typename FuncPtr>
|
||||
SymbolBinding<FuncPtr> makeSymbolBinding (FuncPtr& func, const char* name)
|
||||
{
|
||||
return { func, name };
|
||||
}
|
||||
|
||||
template <typename FuncPtr>
|
||||
bool loadSymbols (DynamicLibrary& lib, SymbolBinding<FuncPtr> binding)
|
||||
{
|
||||
if (auto* func = lib.getFunction (binding.name))
|
||||
{
|
||||
binding.func = reinterpret_cast<FuncPtr> (func);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename FuncPtr, typename... Args>
|
||||
bool loadSymbols (DynamicLibrary& lib1, DynamicLibrary& lib2, SymbolBinding<FuncPtr> binding)
|
||||
{
|
||||
return loadSymbols (lib1, binding) || loadSymbols (lib2, binding);
|
||||
}
|
||||
|
||||
template <typename FuncPtr, typename... Args>
|
||||
bool loadSymbols (DynamicLibrary& lib, SymbolBinding<FuncPtr> binding, Args... args)
|
||||
{
|
||||
return loadSymbols (lib, binding) && loadSymbols (lib, args...);
|
||||
}
|
||||
|
||||
template <typename FuncPtr, typename... Args>
|
||||
bool loadSymbols (DynamicLibrary& lib1, DynamicLibrary& lib2, SymbolBinding<FuncPtr> binding, Args... args)
|
||||
{
|
||||
return loadSymbols (lib1, lib2, binding) && loadSymbols (lib1, lib2, args...);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
bool X11Symbols::loadAllSymbols()
|
||||
{
|
||||
using namespace X11SymbolHelpers;
|
||||
|
||||
if (! loadSymbols (xLib, xextLib,
|
||||
makeSymbolBinding (xAllocClassHint, "XAllocClassHint"),
|
||||
makeSymbolBinding (xAllocSizeHints, "XAllocSizeHints"),
|
||||
makeSymbolBinding (xAllocWMHints, "XAllocWMHints"),
|
||||
makeSymbolBinding (xBitmapBitOrder, "XBitmapBitOrder"),
|
||||
makeSymbolBinding (xBitmapUnit, "XBitmapUnit"),
|
||||
makeSymbolBinding (xChangeActivePointerGrab, "XChangeActivePointerGrab"),
|
||||
makeSymbolBinding (xChangeProperty, "XChangeProperty"),
|
||||
makeSymbolBinding (xCheckTypedWindowEvent, "XCheckTypedWindowEvent"),
|
||||
makeSymbolBinding (xCheckWindowEvent, "XCheckWindowEvent"),
|
||||
makeSymbolBinding (xClearArea, "XClearArea"),
|
||||
makeSymbolBinding (xCloseDisplay, "XCloseDisplay"),
|
||||
makeSymbolBinding (xConnectionNumber, "XConnectionNumber"),
|
||||
makeSymbolBinding (xConvertSelection, "XConvertSelection"),
|
||||
makeSymbolBinding (xCreateColormap, "XCreateColormap"),
|
||||
makeSymbolBinding (xCreateFontCursor, "XCreateFontCursor"),
|
||||
makeSymbolBinding (xCreateGC, "XCreateGC"),
|
||||
makeSymbolBinding (xCreateImage, "XCreateImage"),
|
||||
makeSymbolBinding (xCreatePixmap, "XCreatePixmap"),
|
||||
makeSymbolBinding (xCreatePixmapCursor, "XCreatePixmapCursor"),
|
||||
makeSymbolBinding (xCreatePixmapFromBitmapData, "XCreatePixmapFromBitmapData"),
|
||||
makeSymbolBinding (xCreateWindow, "XCreateWindow"),
|
||||
makeSymbolBinding (xDefaultRootWindow, "XDefaultRootWindow"),
|
||||
makeSymbolBinding (xDefaultScreen, "XDefaultScreen"),
|
||||
makeSymbolBinding (xDefaultScreenOfDisplay, "XDefaultScreenOfDisplay"),
|
||||
makeSymbolBinding (xDefaultVisual, "XDefaultVisual"),
|
||||
makeSymbolBinding (xDefineCursor, "XDefineCursor"),
|
||||
makeSymbolBinding (xDeleteContext, "XDeleteContext"),
|
||||
makeSymbolBinding (xDeleteProperty, "XDeleteProperty"),
|
||||
makeSymbolBinding (xDestroyImage, "XDestroyImage"),
|
||||
makeSymbolBinding (xDestroyWindow, "XDestroyWindow"),
|
||||
makeSymbolBinding (xDisplayHeight, "XDisplayHeight"),
|
||||
makeSymbolBinding (xDisplayHeightMM, "XDisplayHeightMM"),
|
||||
makeSymbolBinding (xDisplayWidth, "XDisplayWidth"),
|
||||
makeSymbolBinding (xDisplayWidthMM, "XDisplayWidthMM"),
|
||||
makeSymbolBinding (xEventsQueued, "XEventsQueued"),
|
||||
makeSymbolBinding (xFindContext, "XFindContext"),
|
||||
makeSymbolBinding (xFlush, "XFlush"),
|
||||
makeSymbolBinding (xFree, "XFree"),
|
||||
makeSymbolBinding (xFreeCursor, "XFreeCursor"),
|
||||
makeSymbolBinding (xFreeColormap, "XFreeColormap"),
|
||||
makeSymbolBinding (xFreeEventData, "XFreeEventData"),
|
||||
makeSymbolBinding (xFreeGC, "XFreeGC"),
|
||||
makeSymbolBinding (xFreeModifiermap, "XFreeModifiermap"),
|
||||
makeSymbolBinding (xFreePixmap, "XFreePixmap"),
|
||||
makeSymbolBinding (xGetAtomName, "XGetAtomName"),
|
||||
makeSymbolBinding (xGetErrorDatabaseText, "XGetErrorDatabaseText"),
|
||||
makeSymbolBinding (xGetErrorText, "XGetErrorText"),
|
||||
makeSymbolBinding (xGetEventData, "XGetEventData"),
|
||||
makeSymbolBinding (xGetGeometry, "XGetGeometry"),
|
||||
makeSymbolBinding (xGetImage, "XGetImage"),
|
||||
makeSymbolBinding (xGetInputFocus, "XGetInputFocus"),
|
||||
makeSymbolBinding (xGetModifierMapping, "XGetModifierMapping"),
|
||||
makeSymbolBinding (xGetPointerMapping, "XGetPointerMapping"),
|
||||
makeSymbolBinding (xGetSelectionOwner, "XGetSelectionOwner"),
|
||||
makeSymbolBinding (xGetVisualInfo, "XGetVisualInfo"),
|
||||
makeSymbolBinding (xGetWMHints, "XGetWMHints"),
|
||||
makeSymbolBinding (xGetWindowAttributes, "XGetWindowAttributes"),
|
||||
makeSymbolBinding (xGetWindowProperty, "XGetWindowProperty"),
|
||||
makeSymbolBinding (xGrabPointer, "XGrabPointer"),
|
||||
makeSymbolBinding (xGrabServer, "XGrabServer"),
|
||||
makeSymbolBinding (xImageByteOrder, "XImageByteOrder"),
|
||||
makeSymbolBinding (xInitImage, "XInitImage"),
|
||||
makeSymbolBinding (xInitThreads, "XInitThreads"),
|
||||
makeSymbolBinding (xInstallColormap, "XInstallColormap"),
|
||||
makeSymbolBinding (xInternAtom, "XInternAtom"),
|
||||
makeSymbolBinding (xkbKeycodeToKeysym, "XkbKeycodeToKeysym"),
|
||||
makeSymbolBinding (xKeysymToKeycode, "XKeysymToKeycode"),
|
||||
makeSymbolBinding (xListProperties, "XListProperties"),
|
||||
makeSymbolBinding (xLockDisplay, "XLockDisplay"),
|
||||
makeSymbolBinding (xLookupString, "XLookupString"),
|
||||
makeSymbolBinding (xMapRaised, "XMapRaised"),
|
||||
makeSymbolBinding (xMapWindow, "XMapWindow"),
|
||||
makeSymbolBinding (xMoveResizeWindow, "XMoveResizeWindow"),
|
||||
makeSymbolBinding (xNextEvent, "XNextEvent"),
|
||||
makeSymbolBinding (xNextRequest, "XNextRequest"),
|
||||
makeSymbolBinding (xOpenDisplay, "XOpenDisplay"),
|
||||
makeSymbolBinding (xPeekEvent, "XPeekEvent"),
|
||||
makeSymbolBinding (xPending, "XPending"),
|
||||
makeSymbolBinding (xPutImage, "XPutImage"),
|
||||
makeSymbolBinding (xPutPixel, "XPutPixel"),
|
||||
makeSymbolBinding (xQueryBestCursor, "XQueryBestCursor"),
|
||||
makeSymbolBinding (xQueryExtension, "XQueryExtension"),
|
||||
makeSymbolBinding (xQueryPointer, "XQueryPointer"),
|
||||
makeSymbolBinding (xQueryTree, "XQueryTree"),
|
||||
makeSymbolBinding (xRefreshKeyboardMapping, "XRefreshKeyboardMapping"),
|
||||
makeSymbolBinding (xReparentWindow, "XReparentWindow"),
|
||||
makeSymbolBinding (xResizeWindow, "XResizeWindow"),
|
||||
makeSymbolBinding (xRestackWindows, "XRestackWindows"),
|
||||
makeSymbolBinding (xRootWindow, "XRootWindow"),
|
||||
makeSymbolBinding (xSaveContext, "XSaveContext"),
|
||||
makeSymbolBinding (xScreenCount, "XScreenCount"),
|
||||
makeSymbolBinding (xScreenNumberOfScreen, "XScreenNumberOfScreen"),
|
||||
makeSymbolBinding (xSelectInput, "XSelectInput"),
|
||||
makeSymbolBinding (xSendEvent, "XSendEvent"),
|
||||
makeSymbolBinding (xSetClassHint, "XSetClassHint"),
|
||||
makeSymbolBinding (xSetAfterFunction, "XSetAfterFunction"),
|
||||
makeSymbolBinding (xSetErrorHandler, "XSetErrorHandler"),
|
||||
makeSymbolBinding (xSetIOErrorHandler, "XSetIOErrorHandler"),
|
||||
makeSymbolBinding (xSetInputFocus, "XSetInputFocus"),
|
||||
makeSymbolBinding (xSetSelectionOwner, "XSetSelectionOwner"),
|
||||
makeSymbolBinding (xSetTransientForHint, "XSetTransientForHint"),
|
||||
makeSymbolBinding (xSetWMHints, "XSetWMHints"),
|
||||
makeSymbolBinding (xSetWMIconName, "XSetWMIconName"),
|
||||
makeSymbolBinding (xSetWMName, "XSetWMName"),
|
||||
makeSymbolBinding (xSetWMNormalHints, "XSetWMNormalHints"),
|
||||
makeSymbolBinding (xStringListToTextProperty, "XStringListToTextProperty"),
|
||||
makeSymbolBinding (xSync, "XSync"),
|
||||
makeSymbolBinding (xSynchronize, "XSynchronize"),
|
||||
makeSymbolBinding (xTranslateCoordinates, "XTranslateCoordinates"),
|
||||
makeSymbolBinding (xrmUniqueQuark, "XrmUniqueQuark"),
|
||||
makeSymbolBinding (xUngrabPointer, "XUngrabPointer"),
|
||||
makeSymbolBinding (xUngrabServer, "XUngrabServer"),
|
||||
makeSymbolBinding (xUnlockDisplay, "XUnlockDisplay"),
|
||||
makeSymbolBinding (xUnmapWindow, "XUnmapWindow"),
|
||||
makeSymbolBinding (xutf8TextListToTextProperty, "Xutf8TextListToTextProperty"),
|
||||
makeSymbolBinding (xWarpPointer, "XWarpPointer")))
|
||||
return false;
|
||||
|
||||
#if JUCE_USE_XCURSOR
|
||||
loadSymbols (xcursorLib,
|
||||
makeSymbolBinding (xcursorImageCreate, "XcursorImageCreate"),
|
||||
makeSymbolBinding (xcursorImageLoadCursor, "XcursorImageLoadCursor"),
|
||||
makeSymbolBinding (xcursorImageDestroy, "XcursorImageDestroy"));
|
||||
#endif
|
||||
#if JUCE_USE_XINERAMA
|
||||
loadSymbols (xineramaLib,
|
||||
makeSymbolBinding (xineramaIsActive, "XineramaIsActive"),
|
||||
makeSymbolBinding (xineramaQueryScreens, "XineramaQueryScreens"));
|
||||
#endif
|
||||
#if JUCE_USE_XRENDER
|
||||
loadSymbols (xrenderLib,
|
||||
makeSymbolBinding (xRenderQueryVersion, "XRenderQueryVersion"),
|
||||
makeSymbolBinding (xRenderFindStandardFormat, "XRenderFindStandardFormat"),
|
||||
makeSymbolBinding (xRenderFindFormat, "XRenderFindFormat"),
|
||||
makeSymbolBinding (xRenderFindVisualFormat, "XRenderFindVisualFormat"));
|
||||
#endif
|
||||
#if JUCE_USE_XRANDR
|
||||
loadSymbols (xrandrLib,
|
||||
makeSymbolBinding (xRRGetScreenResources, "XRRGetScreenResources"),
|
||||
makeSymbolBinding (xRRFreeScreenResources, "XRRFreeScreenResources"),
|
||||
makeSymbolBinding (xRRGetOutputInfo, "XRRGetOutputInfo"),
|
||||
makeSymbolBinding (xRRFreeOutputInfo, "XRRFreeOutputInfo"),
|
||||
makeSymbolBinding (xRRGetCrtcInfo, "XRRGetCrtcInfo"),
|
||||
makeSymbolBinding (xRRFreeCrtcInfo, "XRRFreeCrtcInfo"),
|
||||
makeSymbolBinding (xRRGetOutputPrimary, "XRRGetOutputPrimary"));
|
||||
#endif
|
||||
#if JUCE_USE_XSHM
|
||||
loadSymbols (xLib, xextLib,
|
||||
makeSymbolBinding (xShmAttach, "XShmAttach"),
|
||||
makeSymbolBinding (xShmCreateImage, "XShmCreateImage"),
|
||||
makeSymbolBinding (xShmDetach, "XShmDetach"),
|
||||
makeSymbolBinding (xShmGetEventBase, "XShmGetEventBase"),
|
||||
makeSymbolBinding (xShmPutImage, "XShmPutImage"),
|
||||
makeSymbolBinding (xShmQueryVersion, "XShmQueryVersion"));
|
||||
#endif
|
||||
#if JUCE_USE_XINPUT
|
||||
loadSymbols (xinputLib,
|
||||
makeSymbolBinding (xiQueryVersion, "XIQueryVersion"),
|
||||
makeSymbolBinding (xiQueryDevice, "XIQueryDevice"),
|
||||
makeSymbolBinding (xiFreeDeviceInfo, "XIFreeDeviceInfo"),
|
||||
makeSymbolBinding (xiSelectEvents, "XISelectEvents"),
|
||||
makeSymbolBinding (xiGetClientPointer, "XIGetClientPointer"),
|
||||
makeSymbolBinding (xiGrabDevice, "XIGrabDevice"),
|
||||
makeSymbolBinding (xiUngrabDevice, "XIUngrabDevice"));
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,690 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
namespace ReturnHelpers
|
||||
{
|
||||
template <typename Type>
|
||||
Type returnDefaultConstructedAnyType() { return {}; }
|
||||
|
||||
template <>
|
||||
inline void returnDefaultConstructedAnyType<void>() {}
|
||||
}
|
||||
|
||||
#define JUCE_GENERATE_FUNCTION_WITH_DEFAULT(functionName, objectName, args, returnType) \
|
||||
using functionName = returnType (*) args; \
|
||||
functionName objectName = [] args -> returnType { return ReturnHelpers::returnDefaultConstructedAnyType<returnType>(); };
|
||||
|
||||
#define JUCE_GENERATE_FUNCTION_WITH_DEFAULT_RESULT(functionName, objectName, args, returnType, defaultResult) \
|
||||
using functionName = returnType (*) args; \
|
||||
functionName objectName = [] args -> returnType { return defaultResult; };
|
||||
|
||||
|
||||
//==============================================================================
|
||||
class JUCE_API X11Symbols
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
bool loadAllSymbols();
|
||||
|
||||
//==============================================================================
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XAllocClassHint, xAllocClassHint,
|
||||
(),
|
||||
XClassHint*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XAllocSizeHints, xAllocSizeHints,
|
||||
(),
|
||||
XSizeHints*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XAllocWMHints, xAllocWMHints,
|
||||
(),
|
||||
XWMHints*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XBitmapBitOrder, xBitmapBitOrder,
|
||||
(::Display*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XBitmapUnit, xBitmapUnit,
|
||||
(::Display*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XChangeActivePointerGrab, xChangeActivePointerGrab,
|
||||
(::Display*, unsigned int, Cursor, ::Time),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XChangeProperty, xChangeProperty,
|
||||
(::Display*, ::Window, Atom, Atom, int, int, const unsigned char*, int),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XCheckTypedWindowEvent, xCheckTypedWindowEvent,
|
||||
(::Display*, ::Window, int, XEvent*),
|
||||
Bool)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XCheckWindowEvent, xCheckWindowEvent,
|
||||
(::Display*, ::Window, long, XEvent*),
|
||||
Bool)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XClearArea, xClearArea,
|
||||
(::Display*, ::Window, int, int, unsigned int, unsigned int, Bool),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XCloseDisplay, xCloseDisplay,
|
||||
(::Display*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XConnectionNumber, xConnectionNumber,
|
||||
(::Display*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XConvertSelection, xConvertSelection,
|
||||
(::Display*, Atom, Atom, Atom, ::Window, ::Time),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XCreateColormap, xCreateColormap,
|
||||
(::Display*, ::Window, Visual*, int),
|
||||
Colormap)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XCreateFontCursor, xCreateFontCursor,
|
||||
(::Display*, unsigned int),
|
||||
Cursor)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XCreateGC, xCreateGC,
|
||||
(::Display*, ::Drawable, unsigned long, XGCValues*),
|
||||
GC)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XCreateImage, xCreateImage,
|
||||
(::Display*, Visual*, unsigned int, int, int, const char*, unsigned int, unsigned int, int, int),
|
||||
XImage*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XCreatePixmap, xCreatePixmap,
|
||||
(::Display*, ::Drawable, unsigned int, unsigned int, unsigned int),
|
||||
Pixmap)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XCreatePixmapCursor, xCreatePixmapCursor,
|
||||
(::Display*, Pixmap, Pixmap, XColor*, XColor*, unsigned int, unsigned int),
|
||||
Cursor)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XCreatePixmapFromBitmapData, xCreatePixmapFromBitmapData,
|
||||
(::Display*, ::Drawable, const char*, unsigned int, unsigned int, unsigned long, unsigned long, unsigned int),
|
||||
Pixmap)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XCreateWindow, xCreateWindow,
|
||||
(::Display*, ::Window, int, int, unsigned int, unsigned int, unsigned int, int, unsigned int, Visual*, unsigned long, XSetWindowAttributes*),
|
||||
::Window)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDefaultRootWindow, xDefaultRootWindow,
|
||||
(::Display*),
|
||||
::Window)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDefaultScreen, xDefaultScreen,
|
||||
(::Display*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDefaultScreenOfDisplay, xDefaultScreenOfDisplay,
|
||||
(::Display*),
|
||||
Screen*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDefaultVisual, xDefaultVisual,
|
||||
(::Display*, int),
|
||||
Visual*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDefineCursor, xDefineCursor,
|
||||
(::Display*, ::Window, Cursor),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDeleteContext, xDeleteContext,
|
||||
(::Display*, XID, XContext),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDeleteProperty, xDeleteProperty,
|
||||
(::Display*, Window, Atom),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDestroyImage, xDestroyImage,
|
||||
(XImage*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDestroyWindow, xDestroyWindow,
|
||||
(::Display*, ::Window),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDisplayHeight, xDisplayHeight,
|
||||
(::Display*, int),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDisplayHeightMM, xDisplayHeightMM,
|
||||
(::Display*, int),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDisplayWidth, xDisplayWidth,
|
||||
(::Display*, int),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XDisplayWidthMM, xDisplayWidthMM,
|
||||
(::Display*, int),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XEventsQueued, xEventsQueued,
|
||||
(::Display*, int),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XFindContext, xFindContext,
|
||||
(::Display*, XID, XContext, XPointer*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XFlush, xFlush,
|
||||
(::Display*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XFree, xFree,
|
||||
(void*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XFreeCursor, xFreeCursor,
|
||||
(::Display*, Cursor),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XFreeColormap ,xFreeColormap,
|
||||
(::Display*, Colormap),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XFreeEventData, xFreeEventData,
|
||||
(::Display*, XGenericEventCookie*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XFreeGC, xFreeGC,
|
||||
(::Display*, GC),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XFreeModifiermap, xFreeModifiermap,
|
||||
(XModifierKeymap*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XFreePixmap, xFreePixmap,
|
||||
(::Display*, Pixmap),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetAtomName, xGetAtomName,
|
||||
(::Display*, Atom),
|
||||
char*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetErrorDatabaseText, xGetErrorDatabaseText,
|
||||
(::Display*, const char*, const char*, const char*, const char*, int),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetErrorText, xGetErrorText,
|
||||
(::Display*, int, const char*, int),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetEventData, xGetEventData,
|
||||
(::Display*, XGenericEventCookie*),
|
||||
Bool)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetGeometry, xGetGeometry,
|
||||
(::Display*, ::Drawable, ::Window*, int*, int*, unsigned int*, unsigned int*, unsigned int*, unsigned int*),
|
||||
Status)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetImage, xGetImage,
|
||||
(::Display*, ::Drawable, int, int, unsigned int, unsigned int, unsigned long, int),
|
||||
XImage*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetInputFocus, xGetInputFocus,
|
||||
(::Display*, ::Window*, int*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetModifierMapping, xGetModifierMapping,
|
||||
(::Display*),
|
||||
XModifierKeymap*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetPointerMapping, xGetPointerMapping,
|
||||
(::Display*, unsigned char[], int),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetSelectionOwner, xGetSelectionOwner,
|
||||
(::Display*, Atom),
|
||||
::Window)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetVisualInfo, xGetVisualInfo,
|
||||
(::Display*, long, XVisualInfo*, int*),
|
||||
XVisualInfo*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetWMHints, xGetWMHints,
|
||||
(::Display*, ::Window),
|
||||
XWMHints*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetWindowAttributes, xGetWindowAttributes,
|
||||
(::Display*, ::Window, XWindowAttributes*),
|
||||
Status)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGetWindowProperty, xGetWindowProperty,
|
||||
(::Display*, ::Window, Atom, long, long, Bool, Atom, Atom*, int*, unsigned long*, unsigned long*, unsigned char**),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGrabPointer, xGrabPointer,
|
||||
(::Display*, ::Window, Bool, unsigned int, int, int, ::Window, Cursor, ::Time),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XGrabServer, xGrabServer,
|
||||
(::Display*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XImageByteOrder, xImageByteOrder,
|
||||
(::Display*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XInitImage, xInitImage,
|
||||
(XImage*),
|
||||
Status)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XInitThreads, xInitThreads,
|
||||
(),
|
||||
Status)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XInstallColormap, xInstallColormap,
|
||||
(::Display*, Colormap),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XInternAtom, xInternAtom,
|
||||
(::Display*, const char*, Bool),
|
||||
Atom)
|
||||
|
||||
#if JUCE_USE_XINPUT
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT_RESULT (XIQueryVersion, xiQueryVersion,
|
||||
(::Display*, int*, int*),
|
||||
Status,
|
||||
BadRequest)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XIQueryDevice, xiQueryDevice,
|
||||
(::Display*, int, int*),
|
||||
XIDeviceInfo*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XIFreeDeviceInfo, xiFreeDeviceInfo,
|
||||
(XIDeviceInfo*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XISelectEvents, xiSelectEvents,
|
||||
(::Display*, ::Window, XIEventMask*, int),
|
||||
Status)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XIGetClientPointer, xiGetClientPointer,
|
||||
(::Display*, ::Window, int*),
|
||||
Bool)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT_RESULT (XIGrabDevice, xiGrabDevice,
|
||||
(::Display*, int, ::Window, ::Time, Cursor, int, int, Bool, XIEventMask*),
|
||||
Status,
|
||||
BadRequest)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XIUngrabDevice, xiUngrabDevice,
|
||||
(::Display*, int, ::Time),
|
||||
Status)
|
||||
#endif
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XkbKeycodeToKeysym, xkbKeycodeToKeysym,
|
||||
(::Display*, KeyCode, unsigned int, unsigned int),
|
||||
KeySym)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XKeysymToKeycode, xKeysymToKeycode,
|
||||
(::Display*, KeySym),
|
||||
KeyCode)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XListProperties, xListProperties,
|
||||
(::Display*, Window, int*),
|
||||
Atom*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XLockDisplay, xLockDisplay,
|
||||
(::Display*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XLookupString, xLookupString,
|
||||
(XKeyEvent*, const char*, int, KeySym*, XComposeStatus*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XMapRaised, xMapRaised,
|
||||
(::Display*, ::Window),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XMapWindow, xMapWindow,
|
||||
(::Display*, ::Window),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XMoveResizeWindow, xMoveResizeWindow,
|
||||
(::Display*, ::Window, int, int, unsigned int, unsigned int),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XNextEvent, xNextEvent,
|
||||
(::Display*, XEvent*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XNextRequest, xNextRequest,
|
||||
(::Display*),
|
||||
unsigned long)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XOpenDisplay, xOpenDisplay,
|
||||
(const char*),
|
||||
::Display*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XPeekEvent, xPeekEvent,
|
||||
(::Display*, XEvent*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XPending, xPending,
|
||||
(::Display*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XPutImage, xPutImage,
|
||||
(::Display*, ::Drawable, GC, XImage*, int, int, int, int, unsigned int, unsigned int),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XPutPixel, xPutPixel,
|
||||
(XImage*, int, int, unsigned long),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XQueryBestCursor, xQueryBestCursor,
|
||||
(::Display*, ::Drawable, unsigned int, unsigned int, unsigned int*, unsigned int*),
|
||||
Status)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XQueryExtension, xQueryExtension,
|
||||
(::Display*, const char*, int*, int*, int*),
|
||||
Bool)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XQueryPointer, xQueryPointer,
|
||||
(::Display*, ::Window, ::Window*, ::Window*, int*, int*, int*, int*, unsigned int*),
|
||||
Bool)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XQueryTree, xQueryTree,
|
||||
(::Display*, ::Window, ::Window*, ::Window*, ::Window**, unsigned int*),
|
||||
Status)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRefreshKeyboardMapping, xRefreshKeyboardMapping,
|
||||
(XMappingEvent*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XReparentWindow, xReparentWindow,
|
||||
(::Display*, ::Window, ::Window, int, int),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XResizeWindow, xResizeWindow,
|
||||
(::Display*, Window, unsigned int, unsigned int),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRestackWindows, xRestackWindows,
|
||||
(::Display*, ::Window[], int),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRootWindow, xRootWindow,
|
||||
(::Display*, int),
|
||||
::Window)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSaveContext, xSaveContext,
|
||||
(::Display*, XID, XContext, XPointer),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XScreenCount, xScreenCount,
|
||||
(::Display*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XScreenNumberOfScreen, xScreenNumberOfScreen,
|
||||
(Screen*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSelectInput, xSelectInput,
|
||||
(::Display*, ::Window, long),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSendEvent, xSendEvent,
|
||||
(::Display*, ::Window, Bool, long, XEvent*),
|
||||
Status)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSetClassHint, xSetClassHint,
|
||||
(::Display*, ::Window, XClassHint*),
|
||||
void)
|
||||
|
||||
using XAfterFunction = int (*) (::Display*);
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSetAfterFunction, xSetAfterFunction,
|
||||
(::Display*, XAfterFunction),
|
||||
XAfterFunction)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSetErrorHandler, xSetErrorHandler,
|
||||
(XErrorHandler),
|
||||
XErrorHandler)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSetIOErrorHandler, xSetIOErrorHandler,
|
||||
(XIOErrorHandler),
|
||||
XIOErrorHandler)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSetInputFocus, xSetInputFocus,
|
||||
(::Display*, ::Window, int, ::Time),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSetSelectionOwner, xSetSelectionOwner,
|
||||
(::Display*, Atom, ::Window, ::Time),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSetTransientForHint, xSetTransientForHint,
|
||||
(::Display*, ::Window, ::Window),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSetWMHints, xSetWMHints,
|
||||
(::Display*, ::Window, XWMHints*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSetWMIconName, xSetWMIconName,
|
||||
(::Display*, ::Window, XTextProperty*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSetWMName, xSetWMName,
|
||||
(::Display*, ::Window, XTextProperty*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSetWMNormalHints, xSetWMNormalHints,
|
||||
(::Display*, ::Window, XSizeHints*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XStringListToTextProperty, xStringListToTextProperty,
|
||||
(char**, int, XTextProperty*),
|
||||
Status)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (Xutf8TextListToTextProperty, xutf8TextListToTextProperty,
|
||||
(::Display*, char**, int, XICCEncodingStyle, XTextProperty*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSync, xSync,
|
||||
(::Display*, Bool),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XSynchronize, xSynchronize,
|
||||
(::Display*, Bool),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XTranslateCoordinates, xTranslateCoordinates,
|
||||
(::Display*, ::Window, ::Window, int, int, int*, int*, ::Window*),
|
||||
Bool)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XrmUniqueQuark, xrmUniqueQuark,
|
||||
(),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XUngrabPointer, xUngrabPointer,
|
||||
(::Display*, ::Time),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XUngrabServer, xUngrabServer,
|
||||
(::Display*),
|
||||
int)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XUnlockDisplay, xUnlockDisplay,
|
||||
(::Display*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XUnmapWindow, xUnmapWindow,
|
||||
(::Display*, ::Window),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XWarpPointer, xWarpPointer,
|
||||
(::Display*, ::Window, ::Window, int, int, unsigned int, unsigned int, int, int),
|
||||
void)
|
||||
#if JUCE_USE_XCURSOR
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XcursorImageCreate, xcursorImageCreate,
|
||||
(int, int),
|
||||
XcursorImage*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XcursorImageLoadCursor, xcursorImageLoadCursor,
|
||||
(::Display*, XcursorImage*),
|
||||
Cursor)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XcursorImageDestroy, xcursorImageDestroy,
|
||||
(XcursorImage*),
|
||||
void)
|
||||
#endif
|
||||
#if JUCE_USE_XINERAMA
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XineramaIsActive, xineramaIsActive,
|
||||
(::Display*),
|
||||
Bool)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XineramaQueryScreens, xineramaQueryScreens,
|
||||
(::Display*, int*),
|
||||
XineramaScreenInfo*)
|
||||
#endif
|
||||
#if JUCE_USE_XRENDER
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRenderQueryVersion, xRenderQueryVersion,
|
||||
(::Display*, int*, int*),
|
||||
Status)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRenderFindStandardFormat, xRenderFindStandardFormat,
|
||||
(Display*, int),
|
||||
XRenderPictFormat*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRenderFindFormat, xRenderFindFormat,
|
||||
(Display*, unsigned long, XRenderPictFormat*, int),
|
||||
XRenderPictFormat*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRenderFindVisualFormat, xRenderFindVisualFormat,
|
||||
(Display*, Visual*),
|
||||
XRenderPictFormat*)
|
||||
#endif
|
||||
#if JUCE_USE_XRANDR
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRRGetScreenResources, xRRGetScreenResources,
|
||||
(::Display*, Window),
|
||||
XRRScreenResources*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRRFreeScreenResources, xRRFreeScreenResources,
|
||||
(XRRScreenResources*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRRGetOutputInfo, xRRGetOutputInfo,
|
||||
(::Display*, XRRScreenResources*, RROutput),
|
||||
XRROutputInfo*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRRFreeOutputInfo, xRRFreeOutputInfo,
|
||||
(XRROutputInfo*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRRGetCrtcInfo, xRRGetCrtcInfo,
|
||||
(::Display*, XRRScreenResources*, RRCrtc),
|
||||
XRRCrtcInfo*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRRFreeCrtcInfo, xRRFreeCrtcInfo,
|
||||
(XRRCrtcInfo*),
|
||||
void)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XRRGetOutputPrimary, xRRGetOutputPrimary,
|
||||
(::Display*, ::Window),
|
||||
RROutput)
|
||||
#endif
|
||||
#if JUCE_USE_XSHM
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XShmAttach, xShmAttach,
|
||||
(::Display*, XShmSegmentInfo*),
|
||||
Bool)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XShmCreateImage, xShmCreateImage,
|
||||
(::Display*, Visual*, unsigned int, int, const char*, XShmSegmentInfo*, unsigned int, unsigned int),
|
||||
XImage*)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XShmDetach, xShmDetach,
|
||||
(::Display*, XShmSegmentInfo*),
|
||||
Bool)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XShmGetEventBase, xShmGetEventBase,
|
||||
(::Display*),
|
||||
Status)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XShmPutImage, xShmPutImage,
|
||||
(::Display*, ::Drawable, GC, XImage*, int, int, int, int, unsigned int, unsigned int, bool),
|
||||
Bool)
|
||||
|
||||
JUCE_GENERATE_FUNCTION_WITH_DEFAULT (XShmQueryVersion, xShmQueryVersion,
|
||||
(::Display*, int*, int*, Bool*),
|
||||
Bool)
|
||||
#endif
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_SINGLETON_INLINE (X11Symbols, false)
|
||||
|
||||
private:
|
||||
X11Symbols() = default;
|
||||
|
||||
~X11Symbols()
|
||||
{
|
||||
clearSingletonInstance();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
DynamicLibrary xLib { "libX11.so.6" }, xextLib { "libXext.so.6" };
|
||||
|
||||
#if JUCE_USE_XCURSOR
|
||||
DynamicLibrary xcursorLib { "libXcursor.so.1" };
|
||||
#endif
|
||||
#if JUCE_USE_XINERAMA
|
||||
DynamicLibrary xineramaLib { "libXinerama.so.1" };
|
||||
#endif
|
||||
#if JUCE_USE_XRENDER
|
||||
DynamicLibrary xrenderLib { "libXrender.so.1" };
|
||||
#endif
|
||||
#if JUCE_USE_XRANDR
|
||||
DynamicLibrary xrandrLib { "libXrandr.so.2" };
|
||||
#endif
|
||||
#if JUCE_USE_XINPUT
|
||||
DynamicLibrary xinputLib { "libXi.so.6" };
|
||||
#endif
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (X11Symbols)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,406 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
namespace XWindowSystemUtilities
|
||||
{
|
||||
//==============================================================================
|
||||
/** A handy struct that uses XLockDisplay and XUnlockDisplay to lock the X server
|
||||
using RAII.
|
||||
|
||||
@tags{GUI}
|
||||
*/
|
||||
struct ScopedXLock
|
||||
{
|
||||
ScopedXLock();
|
||||
~ScopedXLock();
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** Gets a specified window property and stores its associated data, freeing it
|
||||
on deletion.
|
||||
|
||||
@tags{GUI}
|
||||
*/
|
||||
struct GetXProperty
|
||||
{
|
||||
GetXProperty (::Display* display, ::Window windowH, Atom property,
|
||||
long offset, long length, bool shouldDelete, Atom requestedType);
|
||||
~GetXProperty();
|
||||
|
||||
bool success = false;
|
||||
unsigned char* data = nullptr;
|
||||
unsigned long numItems = 0, bytesLeft = 0;
|
||||
Atom actualType;
|
||||
int actualFormat = -1;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** Initialises and stores some atoms for the display.
|
||||
|
||||
@tags{GUI}
|
||||
*/
|
||||
struct Atoms
|
||||
{
|
||||
enum ProtocolItems
|
||||
{
|
||||
TAKE_FOCUS = 0,
|
||||
DELETE_WINDOW = 1,
|
||||
PING = 2
|
||||
};
|
||||
|
||||
Atoms() = default;
|
||||
explicit Atoms (::Display*);
|
||||
|
||||
static Atom getIfExists (::Display*, const char* name);
|
||||
static Atom getCreating (::Display*, const char* name);
|
||||
|
||||
static String getName (::Display*, Atom);
|
||||
static bool isMimeTypeFile (::Display*, Atom);
|
||||
|
||||
static constexpr unsigned long DndVersion = 3;
|
||||
|
||||
Atom protocols, protocolList[3], changeState, state, userTime, activeWin, pid, windowType, windowState,
|
||||
windowStateHidden, windowStateMaximisedHorz, windowStateMaximisedVert,
|
||||
XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus, XdndDrop, XdndFinished, XdndSelection,
|
||||
XdndTypeList, XdndActionList, XdndActionDescription, XdndActionCopy, XdndActionPrivate,
|
||||
XembedMsgType, XembedInfo, allowedActions[5], allowedMimeTypes[4], utf8String, clipboard, targets;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** Represents a setting according to the XSETTINGS specification.
|
||||
|
||||
@tags{GUI}
|
||||
*/
|
||||
struct XSetting
|
||||
{
|
||||
enum class Type
|
||||
{
|
||||
integer,
|
||||
string,
|
||||
colour,
|
||||
invalid
|
||||
};
|
||||
|
||||
XSetting() = default;
|
||||
|
||||
XSetting (const String& n, int v) : name (n), type (Type::integer), integerValue (v) {}
|
||||
XSetting (const String& n, const String& v) : name (n), type (Type::string), stringValue (v) {}
|
||||
XSetting (const String& n, const Colour& v) : name (n), type (Type::colour), colourValue (v) {}
|
||||
|
||||
bool isValid() const noexcept { return type != Type::invalid; }
|
||||
|
||||
String name;
|
||||
Type type = Type::invalid;
|
||||
|
||||
int integerValue = -1;
|
||||
String stringValue;
|
||||
Colour colourValue;
|
||||
};
|
||||
|
||||
/** Parses and stores the X11 settings for a display according to the XSETTINGS
|
||||
specification.
|
||||
|
||||
@tags{GUI}
|
||||
*/
|
||||
class XSettings
|
||||
{
|
||||
public:
|
||||
static std::unique_ptr<XSettings> createXSettings (::Display*);
|
||||
|
||||
//==============================================================================
|
||||
void update();
|
||||
::Window getSettingsWindow() const noexcept { return settingsWindow; }
|
||||
|
||||
XSetting getSetting (const String& settingName) const;
|
||||
|
||||
//==============================================================================
|
||||
struct Listener
|
||||
{
|
||||
virtual ~Listener() = default;
|
||||
virtual void settingChanged (const XSetting& settingThatHasChanged) = 0;
|
||||
};
|
||||
|
||||
void addListener (Listener* listenerToAdd) { listeners.add (listenerToAdd); }
|
||||
void removeListener (Listener* listenerToRemove) { listeners.remove (listenerToRemove); }
|
||||
|
||||
private:
|
||||
::Display* display = nullptr;
|
||||
::Window settingsWindow = None;
|
||||
Atom settingsAtom;
|
||||
|
||||
int lastUpdateSerial = -1;
|
||||
|
||||
std::unordered_map<String, XSetting> settings;
|
||||
ListenerList<Listener> listeners;
|
||||
|
||||
XSettings (::Display*, Atom, ::Window);
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XSettings)
|
||||
};
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
class LinuxComponentPeer;
|
||||
|
||||
class XWindowSystem : public DeletedAtShutdown
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
::Window createWindow (::Window parentWindow, LinuxComponentPeer*);
|
||||
void destroyWindow (::Window);
|
||||
|
||||
void setTitle (::Window, const String&) const;
|
||||
void setTransientFor (::Window, ::Window parentWindow) const;
|
||||
::Window getTransientFor (::Window) const;
|
||||
::Window findTopLevelClientWindowOf (::Window) const;
|
||||
void setIcon (::Window , const Image&) const;
|
||||
void setVisible (::Window, bool shouldBeVisible) const;
|
||||
[[nodiscard]] std::optional<unsigned long> setBounds (::Window, Rectangle<int>, bool fullScreen) const;
|
||||
void updateSizeHints (::Window, ComponentPeer&, Rectangle<int> physicalBounds) const;
|
||||
|
||||
ComponentPeer::OptionalBorderSize getBorderSize (::Window) const;
|
||||
Rectangle<int> getWindowBounds (::Window, ::Window parentWindow);
|
||||
Point<int> getPhysicalParentScreenPosition() const;
|
||||
Point<int> getScreenPosition (::Window) const;
|
||||
|
||||
bool contains (::Window, Point<int> localPos) const;
|
||||
|
||||
void setMinimised (::Window, bool shouldBeMinimised) const;
|
||||
bool isMinimised (::Window) const;
|
||||
bool isFullScreen (::Window) const;
|
||||
|
||||
void setMaximised (::Window, bool shouldBeMinimised) const;
|
||||
|
||||
void toFront (::Window, bool makeActive) const;
|
||||
void toBehind (::Window, ::Window otherWindow) const;
|
||||
|
||||
bool isFocused (::Window) const;
|
||||
bool grabFocus (::Window) const;
|
||||
|
||||
bool canUseSemiTransparentWindows() const;
|
||||
bool canUseARGBImages() const;
|
||||
bool canUseMultiTouch() const;
|
||||
bool isDarkModeActive() const;
|
||||
|
||||
int getNumPaintsPendingForWindow (::Window);
|
||||
void processPendingPaintsForWindow (::Window);
|
||||
void addPendingPaintForWindow (::Window);
|
||||
void removePendingPaintForWindow (::Window);
|
||||
|
||||
Image createImage (bool isSemiTransparentWindow, int width, int height, bool argb) const;
|
||||
void blitToWindow (::Window, Image, Rectangle<int> destinationRect, Rectangle<int> totalRect) const;
|
||||
|
||||
void setScreenSaverEnabled (bool enabled) const;
|
||||
|
||||
Point<float> getCurrentMousePosition() const;
|
||||
void setMousePosition (Point<float> pos) const;
|
||||
|
||||
Cursor createCustomMouseCursorInfo (const Image&, Point<int> hotspot) const;
|
||||
void deleteMouseCursor (Cursor cursorHandle) const;
|
||||
Cursor createStandardMouseCursor (MouseCursor::StandardCursorType) const;
|
||||
void showCursor (::Window, Cursor cursorHandle) const;
|
||||
|
||||
bool isKeyCurrentlyDown (int keyCode) const;
|
||||
ModifierKeys getNativeRealtimeModifiers() const;
|
||||
|
||||
Array<Displays::Display> findDisplays (float masterScale) const;
|
||||
|
||||
::Window createKeyProxy (::Window);
|
||||
void deleteKeyProxy (::Window) const;
|
||||
|
||||
bool externalDragFileInit (LinuxComponentPeer*, const StringArray& files, bool canMove, std::function<void()>&& callback) const;
|
||||
bool externalDragTextInit (LinuxComponentPeer*, const String& text, std::function<void()>&& callback) const;
|
||||
|
||||
void copyTextToClipboard (const String&);
|
||||
String getTextFromClipboard() const;
|
||||
String getLocalClipboardContent() const noexcept { return localClipboardContent; }
|
||||
|
||||
::Display* getDisplay() const noexcept { return display; }
|
||||
const XWindowSystemUtilities::Atoms& getAtoms() const noexcept { return atoms; }
|
||||
XWindowSystemUtilities::XSettings* getXSettings() const noexcept { return xSettings.get(); }
|
||||
|
||||
bool isX11Available() const noexcept { return xIsAvailable; }
|
||||
|
||||
void startHostManagedResize (::Window window,
|
||||
ResizableBorderComponent::Zone zone);
|
||||
|
||||
bool grabPointerForExternalDrag (::Window, Cursor) const;
|
||||
void ungrabPointer() const;
|
||||
|
||||
static String getWindowScalingFactorSettingName() { return "Gdk/WindowScalingFactor"; }
|
||||
static String getThemeNameSettingName() { return "Net/ThemeName"; }
|
||||
|
||||
//==============================================================================
|
||||
void handleWindowMessage (LinuxComponentPeer*, XEvent&) const;
|
||||
bool isParentWindowOf (::Window, ::Window possibleChild) const;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_SINGLETON_INLINE (XWindowSystem, false)
|
||||
|
||||
private:
|
||||
XWindowSystem();
|
||||
~XWindowSystem();
|
||||
|
||||
//==============================================================================
|
||||
struct VisualAndDepth
|
||||
{
|
||||
Visual* visual;
|
||||
int depth;
|
||||
};
|
||||
|
||||
struct DisplayVisuals
|
||||
{
|
||||
explicit DisplayVisuals (::Display*);
|
||||
|
||||
VisualAndDepth getBestVisualForWindow (bool) const;
|
||||
bool isValid() const noexcept;
|
||||
|
||||
Visual* visual16Bit = nullptr;
|
||||
Visual* visual24Bit = nullptr;
|
||||
Visual* visual32Bit = nullptr;
|
||||
};
|
||||
|
||||
bool initialiseXDisplay();
|
||||
void destroyXDisplay();
|
||||
void dispatchPendingEvents();
|
||||
static int afterXRequest (::Display*);
|
||||
|
||||
//==============================================================================
|
||||
::Window getFocusWindow (::Window) const;
|
||||
|
||||
bool isFrontWindow (::Window) const;
|
||||
|
||||
//==============================================================================
|
||||
void xchangeProperty (::Window, Atom, Atom, int, const void*, int) const;
|
||||
|
||||
void removeWindowDecorations (::Window) const;
|
||||
void addWindowButtons (::Window, int) const;
|
||||
void setWindowType (::Window, int) const;
|
||||
|
||||
void initialisePointerMap();
|
||||
void deleteIconPixmaps (::Window) const;
|
||||
void updateModifierMappings() const;
|
||||
|
||||
long getUserTime (::Window) const;
|
||||
bool isHidden (Window) const;
|
||||
bool isIconic (Window) const;
|
||||
|
||||
void initialiseXSettings();
|
||||
|
||||
//==============================================================================
|
||||
void handleKeyPressEvent (LinuxComponentPeer*, XKeyEvent&) const;
|
||||
void handleKeyReleaseEvent (LinuxComponentPeer*, const XKeyEvent&) const;
|
||||
void handleWheelEvent (LinuxComponentPeer*, int64, Point<float>, float) const;
|
||||
void handleButtonPressEvent (LinuxComponentPeer*, int64, Point<float>, int) const;
|
||||
void handleButtonPressEvent (LinuxComponentPeer*, int, int, ::Time, Point<double>) const;
|
||||
void handleButtonPressEvent (LinuxComponentPeer*, const XButtonPressedEvent&) const;
|
||||
void handleButtonReleaseEvent (LinuxComponentPeer*, int, int, ::Time, Point<double>) const;
|
||||
void handleButtonReleaseEvent (LinuxComponentPeer*, const XButtonReleasedEvent&) const;
|
||||
void handleMotionNotifyEvent (LinuxComponentPeer*, int, ::Time, Point<double>) const;
|
||||
void handleMotionNotifyEvent (LinuxComponentPeer*, const XPointerMovedEvent&) const;
|
||||
void handleEnterNotifyEvent (LinuxComponentPeer*, const XEnterWindowEvent&) const;
|
||||
void handleLeaveNotifyEvent (LinuxComponentPeer*, const XLeaveWindowEvent&) const;
|
||||
void handleFocusInEvent (LinuxComponentPeer*) const;
|
||||
void handleFocusOutEvent (LinuxComponentPeer*) const;
|
||||
void handleExposeEvent (LinuxComponentPeer*, XExposeEvent&) const;
|
||||
void handleConfigureNotifyEvent (LinuxComponentPeer*, XConfigureEvent&) const;
|
||||
void handleGravityNotify (LinuxComponentPeer*) const;
|
||||
void propertyNotifyEvent (LinuxComponentPeer*, const XPropertyEvent&) const;
|
||||
void handleMappingNotify (XMappingEvent&) const;
|
||||
void handleClientMessageEvent (LinuxComponentPeer*, XClientMessageEvent&, XEvent&) const;
|
||||
void handleXEmbedMessage (LinuxComponentPeer*, XClientMessageEvent&) const;
|
||||
|
||||
#if JUCE_USE_XINPUT
|
||||
void handleXIDeviceEvent (LinuxComponentPeer*, int, XIDeviceEvent&) const;
|
||||
#endif
|
||||
|
||||
void dismissBlockingModals (LinuxComponentPeer*) const;
|
||||
void dismissBlockingModals (LinuxComponentPeer*, const XConfigureEvent&) const;
|
||||
|
||||
::Window findTopLevelWindowOf (::Window) const;
|
||||
Point<int> queryPointerPosition() const;
|
||||
void clickForwarded (const XButtonEvent&);
|
||||
void pointerSeenByServer();
|
||||
|
||||
static void windowMessageReceive (XEvent&);
|
||||
|
||||
//==============================================================================
|
||||
bool xIsAvailable = false;
|
||||
|
||||
XWindowSystemUtilities::Atoms atoms;
|
||||
::Display* display = nullptr;
|
||||
int (*previousAfterFunction) (::Display*) = nullptr;
|
||||
std::atomic<bool> dispatchPosted { false };
|
||||
std::unique_ptr<DisplayVisuals> displayVisuals;
|
||||
std::unique_ptr<XWindowSystemUtilities::XSettings> xSettings;
|
||||
|
||||
#if JUCE_USE_XSHM
|
||||
std::map<::Window, int> shmPaintsPendingMap;
|
||||
#endif
|
||||
|
||||
int shmCompletionEvent = 0;
|
||||
unsigned char pointerMap[9]{};
|
||||
String localClipboardContent;
|
||||
|
||||
Point<int> parentScreenPosition;
|
||||
|
||||
// A click that another client forwards to one of our windows carries its position on the
|
||||
// screen, but the X server hasn't seen the pointer there. Under Xwayland the server only
|
||||
// sees the pointer while it is over an X window, and reports the position where it last saw
|
||||
// it until then. That report is the only sign of the pointer moving over another client's
|
||||
// window, so the click is kept until the report changes, not only until the next pointer
|
||||
// event.
|
||||
struct ForwardedClick
|
||||
{
|
||||
Point<int> screenPosition;
|
||||
Point<int> positionReportedByServer;
|
||||
|
||||
bool isCurrent (Point<int> currentReportedPosition) const
|
||||
{
|
||||
return currentReportedPosition == positionReportedByServer;
|
||||
}
|
||||
};
|
||||
|
||||
std::optional<ForwardedClick> lastForwardedClick;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XWindowSystem)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
Reference in new issue
Block a user