merge development

Signed-off-by: chcurran <82187351+carlitosan@users.noreply.github.com>
This commit is contained in:
chcurran
2021-08-17 15:37:30 -07:00
322 changed files with 5753 additions and 7185 deletions
@@ -728,6 +728,7 @@ namespace AZ
DestroyReflectionManager();
static_cast<SettingsRegistryImpl*>(m_settingsRegistry.get())->ClearNotifiers();
static_cast<SettingsRegistryImpl*>(m_settingsRegistry.get())->ClearMergeEvents();
// Uninit and unload any dynamic modules.
m_moduleManager->UnloadModules();
@@ -58,6 +58,12 @@ namespace AZ
Event& operator=(Event&& rhs);
//! Take the handlers registered with the other event
//! and move them to this event. The other will event
//! will be cleared after call
//! @param other event to move handlers
Event& ClaimHandlers(Event&& other);
//! Returns true if at least one handler is connected to this event.
bool HasHandlerConnected() const;
@@ -207,6 +207,32 @@ namespace AZ
}
template <typename... Params>
auto Event<Params...>::ClaimHandlers(Event&& other) -> Event&
{
auto handlers = AZStd::move(other.m_handlers);
auto addList = AZStd::move(other.m_addList);
other.m_freeList = {};
other.m_updating = false;
AZStd::array handlerContainers{ &handlers, &addList };
for (AZStd::vector<Handler*>* handlerList : handlerContainers)
{
for (Handler* handler : *handlerList)
{
if (handler != nullptr)
{
handler->m_index = 0;
handler->m_event = this;
Connect(*handler);
}
}
}
return *this;
}
template <typename... Params>
bool Event<Params...>::HasHandlerConnected() const
{
@@ -123,6 +123,36 @@ namespace AZ
using NotifyEvent = AZ::Event<AZStd::string_view, Type>;
using NotifyEventHandler = typename NotifyEvent::Handler;
using PreMergeEventCallback = AZStd::function<void(AZStd::string_view path, AZStd::string_view rootKey)>;
using PostMergeEventCallback = AZStd::function<void(AZStd::string_view path, AZStd::string_view rootKey)>;
using PreMergeEvent = AZ::Event<AZStd::string_view, AZStd::string_view>;
using PostMergeEvent = AZ::Event<AZStd::string_view, AZStd::string_view>;
using PreMergeEventHandler = typename PreMergeEvent::Handler;
using PostMergeEventHandler = typename PostMergeEvent::Handler;
struct ScopedMergeEvent
{
ScopedMergeEvent(
PreMergeEvent& preMergeEvent, PostMergeEvent& postMergeEvent, AZStd::string_view filePath, AZStd::string_view rootKey)
: m_preMergeEvent{ preMergeEvent }
, m_postMergeEvent{ postMergeEvent }
, m_filePath{ filePath }
, m_rootKey{ rootKey }
{
preMergeEvent.Signal(m_filePath, m_rootKey);
}
~ScopedMergeEvent()
{
m_postMergeEvent.Signal(m_filePath, m_rootKey);
}
PreMergeEvent& m_preMergeEvent;
PostMergeEvent& m_postMergeEvent;
AZStd::string_view m_filePath;
AZStd::string_view m_rootKey;
};
using VisitorCallback =
AZStd::function<VisitResponse(AZStd::string_view path, AZStd::string_view valueName, VisitAction action, Type type)>;
//! Base class for the visitor class during traversal over the Settings Registry. The type-agnostic function is always
@@ -169,6 +199,20 @@ namespace AZ
//! @callback The function to call when an entry gets a new/updated value.
[[nodiscard]] virtual NotifyEventHandler RegisterNotifier(NotifyCallback&& callback) = 0;
//! Register a function that will be called before a file is merged.
//! @callback The function to call before a file is merged.
[[nodiscard]] virtual PreMergeEventHandler RegisterPreMergeEvent(const PreMergeEventCallback& callback) = 0;
//! Register a function that will be called before a file is merged.
//! @callback The function to call before a file is merged.
[[nodiscard]] virtual PreMergeEventHandler RegisterPreMergeEvent (PreMergeEventCallback&& callback) = 0;
//! Register a function that will be called after a file is merged.
//! @callback The function to call after a file is merged.
[[nodiscard]] virtual PostMergeEventHandler RegisterPostMergeEvent(const PostMergeEventCallback& callback) = 0;
//! Register a function that will be called after a file is merged.
//! @callback The function to call after a file is merged.
[[nodiscard]] virtual PostMergeEventHandler RegisterPostMergeEvent (PostMergeEventCallback&& callback) = 0;
//! Gets the boolean value at the provided path.
//! @param result The target to write the result to.
//! @param path The path to the value.
@@ -20,7 +20,7 @@
namespace AZ
{
template<typename T>
bool SettingsRegistryImpl::SetValueInternal(AZStd::string_view path, T value, SettingsRegistryInterface::Type type)
bool SettingsRegistryImpl::SetValueInternal(AZStd::string_view path, T value)
{
if (path.empty())
{
@@ -56,7 +56,6 @@ namespace AZ
static_assert(!AZStd::is_same_v<T, T>, "SettingsRegistryImpl::SetValueInternal called with unsupported type.");
}
m_notifiers.Signal(path, type);
return true;
}
return false;
@@ -157,11 +156,11 @@ namespace AZ
// Setting to empty string to prevent assert
path = "";
}
AZStd::scoped_lock lock(m_settingMutex);
rapidjson::Pointer pointer(path.data(), path.length());
if (pointer.IsValid())
{
AZStd::scoped_lock lock(m_settingMutex);
const rapidjson::Value* value = pointer.Get(m_settings);
if (value)
{
@@ -207,7 +206,7 @@ namespace AZ
{
NotifyEventHandler notifyHandler{ callback };
{
AZStd::scoped_lock lock(m_settingMutex);
AZStd::scoped_lock lock(m_notifierMutex);
notifyHandler.Connect(m_notifiers);
}
return notifyHandler;
@@ -217,7 +216,7 @@ namespace AZ
{
NotifyEventHandler notifyHandler{ AZStd::move(callback) };
{
AZStd::scoped_lock lock(m_settingMutex);
AZStd::scoped_lock lock(m_notifierMutex);
notifyHandler.Connect(m_notifiers);
}
return notifyHandler;
@@ -225,10 +224,82 @@ namespace AZ
void SettingsRegistryImpl::ClearNotifiers()
{
AZStd::scoped_lock lock(m_settingMutex);
AZStd::scoped_lock lock(m_notifierMutex);
m_notifiers.DisconnectAllHandlers();
}
auto SettingsRegistryImpl::RegisterPreMergeEvent(const PreMergeEventCallback& callback) -> PreMergeEventHandler
{
PreMergeEventHandler preMergeHandler{ callback };
{
AZStd::scoped_lock lock(m_settingMutex);
preMergeHandler.Connect(m_preMergeEvent);
}
return preMergeHandler;
}
auto SettingsRegistryImpl::RegisterPreMergeEvent(PreMergeEventCallback&& callback) -> PreMergeEventHandler
{
PreMergeEventHandler preMergeHandler{ AZStd::move(callback) };
{
AZStd::scoped_lock lock(m_settingMutex);
preMergeHandler.Connect(m_preMergeEvent);
}
return preMergeHandler;
}
auto SettingsRegistryImpl::RegisterPostMergeEvent(const PostMergeEventCallback& callback) -> PostMergeEventHandler
{
PostMergeEventHandler postMergeHandler{ callback };
{
AZStd::scoped_lock lock(m_settingMutex);
postMergeHandler.Connect(m_postMergeEvent);
}
return postMergeHandler;
}
auto SettingsRegistryImpl::RegisterPostMergeEvent(PostMergeEventCallback&& callback) -> PostMergeEventHandler
{
PostMergeEventHandler postMergeHandler{ AZStd::move(callback) };
{
AZStd::scoped_lock lock(m_settingMutex);
postMergeHandler.Connect(m_postMergeEvent);
}
return postMergeHandler;
}
void SettingsRegistryImpl::ClearMergeEvents()
{
AZStd::scoped_lock lock(m_settingMutex);
m_preMergeEvent.DisconnectAllHandlers();
m_postMergeEvent.DisconnectAllHandlers();
}
void SettingsRegistryImpl::SignalNotifier(AZStd::string_view jsonPath, Type type)
{
// Move the Notifier AZ::Event to a local AZ::Event in order to allow
// the notifier handlers to be signaled outside of the notifier mutex
// This allows other threads to register notifiers while this thread
// is invoking the handlers
decltype(m_notifiers) localNotifierEvent;
{
AZStd::scoped_lock lock(m_notifierMutex);
localNotifierEvent = AZStd::move(m_notifiers);
}
localNotifierEvent.Signal(jsonPath, type);
{
// Swap the local handlers with the current m_notifiers which
// will contain any handlers added during the signaling of the
// local event
AZStd::scoped_lock lock(m_notifierMutex);
AZStd::swap(m_notifiers, localNotifierEvent);
// Append any added handlers to the m_notifier structure
m_notifiers.ClaimHandlers(AZStd::move(localNotifierEvent));
}
}
SettingsRegistryInterface::Type SettingsRegistryImpl::GetType(AZStd::string_view path) const
{
if (path.empty())
@@ -239,11 +310,11 @@ namespace AZ
path = "";
}
AZStd::scoped_lock lock(m_settingMutex);
rapidjson::Pointer pointer(path.data(), path.length());
if (pointer.IsValid())
{
AZStd::scoped_lock lock(m_settingMutex);
const rapidjson::Value* value = pointer.Get(m_settings);
if (value)
{
@@ -316,11 +387,11 @@ namespace AZ
// Setting to empty string to prevent assert
path = "";
}
AZStd::scoped_lock lock(m_settingMutex);
rapidjson::Pointer pointer(path.data(), path.length());
if (pointer.IsValid())
{
AZStd::scoped_lock lock(m_settingMutex);
const rapidjson::Value* value = pointer.Get(m_settings);
if (value)
{
@@ -333,32 +404,52 @@ namespace AZ
bool SettingsRegistryImpl::Set(AZStd::string_view path, bool value)
{
AZStd::scoped_lock lock(m_settingMutex);
return SetValueInternal(path, value, Type::Boolean);
if (AZStd::scoped_lock lock(m_settingMutex); !SetValueInternal(path, value))
{
return false;
}
SignalNotifier(path, Type::Boolean);
return true;
}
bool SettingsRegistryImpl::Set(AZStd::string_view path, s64 value)
{
AZStd::scoped_lock lock(m_settingMutex);
return SetValueInternal(path, value, Type::Integer);
if (AZStd::scoped_lock lock(m_settingMutex); !SetValueInternal(path, value))
{
return false;
}
SignalNotifier(path, Type::Integer);
return true;
}
bool SettingsRegistryImpl::Set(AZStd::string_view path, u64 value)
{
AZStd::scoped_lock lock(m_settingMutex);
return SetValueInternal(path, value, Type::Integer);
if (AZStd::scoped_lock lock(m_settingMutex); !SetValueInternal(path, value))
{
return false;
}
SignalNotifier(path, Type::Integer);
return true;
}
bool SettingsRegistryImpl::Set(AZStd::string_view path, double value)
{
AZStd::scoped_lock lock(m_settingMutex);
return SetValueInternal(path, value, Type::FloatingPoint);
if (AZStd::scoped_lock lock(m_settingMutex); !SetValueInternal(path, value))
{
return false;
}
SignalNotifier(path, Type::FloatingPoint);
return true;
}
bool SettingsRegistryImpl::Set(AZStd::string_view path, AZStd::string_view value)
{
AZStd::scoped_lock lock(m_settingMutex);
return SetValueInternal(path, value, Type::String);
if (AZStd::scoped_lock lock(m_settingMutex); !SetValueInternal(path, value))
{
return false;
}
SignalNotifier(path, Type::String);
return true;
}
bool SettingsRegistryImpl::Set(AZStd::string_view path, const char* value)
@@ -376,7 +467,6 @@ namespace AZ
path = "";
}
AZStd::scoped_lock lock(m_settingMutex);
rapidjson::Pointer pointer(path.data(), path.length());
if (pointer.IsValid())
@@ -386,9 +476,10 @@ namespace AZ
value, nullptr, valueTypeID, m_serializationSettings);
if (jsonResult.GetProcessing() != JsonSerializationResult::Processing::Halted)
{
AZStd::scoped_lock lock(m_settingMutex);
rapidjson::Value& setting = pointer.Create(m_settings, m_settings.GetAllocator());
setting = AZStd::move(store);
m_notifiers.Signal(path, Type::Object);
SignalNotifier(path, Type::Object);
return true;
}
}
@@ -404,13 +495,13 @@ namespace AZ
// Setting to empty string to prevent assert
path = "";
}
AZStd::scoped_lock lock(m_settingMutex);
rapidjson::Pointer pointerPath(path.data(), path.size());
if (!pointerPath.IsValid())
{
return false;
}
AZStd::scoped_lock lock(m_settingMutex);
return pointerPath.Erase(m_settings);
}
@@ -540,7 +631,7 @@ namespace AZ
return false;
}
m_notifiers.Signal("", Type::Object);
SignalNotifier("", Type::Object);
return true;
}
@@ -562,8 +653,6 @@ namespace AZ
scratchBuffer = &buffer;
}
AZStd::scoped_lock lock(m_settingMutex);
bool result = false;
if (path[path.length()] == 0)
{
@@ -577,6 +666,8 @@ namespace AZ
R"(Path "%.*s" is too long. Either make sure that the provided path is terminated or use a shorter path.)",
static_cast<int>(path.length()), path.data());
Pointer pointer(AZ_SETTINGS_REGISTRY_HISTORY_KEY "/-");
AZStd::scoped_lock lock(m_settingMutex);
Value pathValue(path.data(), aznumeric_caster(path.length()), m_settings.GetAllocator());
pointer.Create(m_settings, m_settings.GetAllocator()).SetObject()
.AddMember(StringRef("Error"), StringRef("Unable to read registry file."), m_settings.GetAllocator())
@@ -622,6 +713,7 @@ namespace AZ
{
AZ_Error("Settings Registry", false, "Folder path for the Setting Registry is too long: %.*s",
static_cast<int>(path.size()), path.data());
AZStd::scoped_lock lock(m_settingMutex);
pointer.Create(m_settings, m_settings.GetAllocator()).SetObject()
.AddMember(StringRef("Error"), StringRef("Folder path for the Setting Registry is too long."), m_settings.GetAllocator())
.AddMember(StringRef("Path"), Value(path.data(), aznumeric_caster(path.length()), m_settings.GetAllocator()), m_settings.GetAllocator());
@@ -659,6 +751,7 @@ namespace AZ
if (fileList.size() >= MaxRegistryFolderEntries)
{
AZ_Error("Settings Registry", false, "Too many files in registry folder.");
AZStd::scoped_lock lock(m_settingMutex);
pointer.Create(m_settings, m_settings.GetAllocator()).SetObject()
.AddMember(StringRef("Error"), StringRef("Too many files in registry folder."), m_settings.GetAllocator())
.AddMember(StringRef("Path"), Value(folderPath.c_str(), aznumeric_caster(folderPath.size()), m_settings.GetAllocator()), m_settings.GetAllocator())
@@ -678,7 +771,6 @@ namespace AZ
SystemFile::FindFiles(folderPath.c_str(), callback);
AZStd::scoped_lock lock(m_settingMutex);
if (!platform.empty())
{
// Move the folderPath prefix back to the supplied path before the wildcard
@@ -696,6 +788,7 @@ namespace AZ
if (fileList.size() >= MaxRegistryFolderEntries)
{
AZ_Error("Settings Registry", false, "Too many files in registry folder.");
AZStd::scoped_lock lock(m_settingMutex);
pointer.Create(m_settings, m_settings.GetAllocator()).SetObject()
.AddMember(StringRef("Error"), StringRef("Too many files in registry folder."), m_settings.GetAllocator())
.AddMember(StringRef("Path"), Value(folderPath.c_str(), aznumeric_caster(folderPath.size()), m_settings.GetAllocator()), m_settings.GetAllocator())
@@ -923,6 +1016,8 @@ namespace AZ
collisionFound = true;
AZ_Error("Settings Registry", false, R"(Two registry files in "%.*s" point to the same specialization: "%s" and "%s")",
AZ_STRING_ARG(folderPath), lhs.m_relativePath.c_str(), rhs.m_relativePath.c_str());
AZStd::scoped_lock lock(m_settingMutex);
historyPointer.Create(m_settings, m_settings.GetAllocator()).SetObject()
.AddMember(StringRef("Error"), StringRef("Too many files in registry folder."), m_settings.GetAllocator())
.AddMember(StringRef("Path"),
@@ -1077,6 +1172,7 @@ namespace AZ
}
}
AZStd::scoped_lock lock(m_settingMutex);
pointer.Create(m_settings, m_settings.GetAllocator()).SetObject()
.AddMember(StringRef("Error"), StringRef("Unable to parse registry file due to invalid json."), m_settings.GetAllocator())
.AddMember(StringRef("Path"), Value(path, m_settings.GetAllocator()), m_settings.GetAllocator())
@@ -1102,6 +1198,7 @@ namespace AZ
R"(To merge the supplied settings registry file, the settings within it must be placed within a JSON Object '{}')"
R"( in order to allow moving of its fields using the root-key as an anchor.)", path);
AZStd::scoped_lock lock(m_settingMutex);
pointer.Create(m_settings, m_settings.GetAllocator()).SetObject()
.AddMember(StringRef("Error"), StringRef("Cannot merge registry file with a root which is not a JSON Object,"
" an empty root key and a merge approach of JsonMergePatch. Otherwise the Settings Registry would be overridden."
@@ -1115,9 +1212,12 @@ namespace AZ
return false;
}
ScopedMergeEvent scopedMergeEvent(m_preMergeEvent, m_postMergeEvent, path, rootKey);
JsonSerializationResult::ResultCode mergeResult(JsonSerializationResult::Tasks::Merge);
if (rootKey.empty())
{
AZStd::scoped_lock lock(m_settingMutex);
mergeResult = JsonSerialization::ApplyPatch(m_settings, m_settings.GetAllocator(), jsonPatch, mergeApproach, m_applyPatchSettings);
}
else
@@ -1125,6 +1225,7 @@ namespace AZ
Pointer root(rootKey.data(), rootKey.length());
if (root.IsValid())
{
AZStd::scoped_lock lock(m_settingMutex);
Value& rootValue = root.Create(m_settings, m_settings.GetAllocator());
mergeResult = JsonSerialization::ApplyPatch(rootValue, m_settings.GetAllocator(), jsonPatch, mergeApproach, m_applyPatchSettings);
}
@@ -1132,6 +1233,7 @@ namespace AZ
{
AZ_Error("Settings Registry", false, R"(Failed to root path "%.*s" is invalid.)",
aznumeric_cast<int>(rootKey.length()), rootKey.data());
AZStd::scoped_lock lock(m_settingMutex);
pointer.Create(m_settings, m_settings.GetAllocator()).SetObject()
.AddMember(StringRef("Error"), StringRef("Invalid root key."), m_settings.GetAllocator())
.AddMember(StringRef("Path"), Value(path, m_settings.GetAllocator()), m_settings.GetAllocator());
@@ -1141,15 +1243,19 @@ namespace AZ
if (mergeResult.GetProcessing() != JsonSerializationResult::Processing::Completed)
{
AZ_Error("Settings Registry", false, R"(Failed to fully merge registry file "%s".)", path);
AZStd::scoped_lock lock(m_settingMutex);
pointer.Create(m_settings, m_settings.GetAllocator()).SetObject()
.AddMember(StringRef("Error"), StringRef("Failed to fully merge registry file."), m_settings.GetAllocator())
.AddMember(StringRef("Path"), Value(path, m_settings.GetAllocator()), m_settings.GetAllocator());
return false;
}
pointer.Create(m_settings, m_settings.GetAllocator()).SetString(path, m_settings.GetAllocator());
{
AZStd::scoped_lock lock(m_settingMutex);
pointer.Create(m_settings, m_settings.GetAllocator()).SetString(path, m_settings.GetAllocator());
}
m_notifiers.Signal("", Type::Object);
SignalNotifier("", Type::Object);
return true;
}
@@ -48,6 +48,12 @@ namespace AZ
[[nodiscard]] NotifyEventHandler RegisterNotifier(NotifyCallback&& callback) override;
void ClearNotifiers();
[[nodiscard]] PreMergeEventHandler RegisterPreMergeEvent(const PreMergeEventCallback& callback) override;
[[nodiscard]] PreMergeEventHandler RegisterPreMergeEvent(PreMergeEventCallback&& callback) override;
[[nodiscard]] PostMergeEventHandler RegisterPostMergeEvent(const PostMergeEventCallback& callback) override;
[[nodiscard]] PostMergeEventHandler RegisterPostMergeEvent(PostMergeEventCallback&& callback) override;
void ClearMergeEvents();
bool Get(bool& result, AZStd::string_view path) const override;
bool Get(s64& result, AZStd::string_view path) const override;
bool Get(u64& result, AZStd::string_view path) const override;
@@ -89,7 +95,7 @@ namespace AZ
using RegistryFileList = AZStd::fixed_vector<RegistryFile, MaxRegistryFolderEntries>;
template<typename T>
bool SetValueInternal(AZStd::string_view path, T value, SettingsRegistryInterface::Type type);
bool SetValueInternal(AZStd::string_view path, T value);
template<typename T>
bool GetValueInternal(T& result, AZStd::string_view path) const;
VisitResponse Visit(Visitor& visitor, StackedString& path, AZStd::string_view valueName,
@@ -100,9 +106,15 @@ namespace AZ
const rapidjson::Pointer& historyPointer, AZStd::string_view folderPath);
bool ExtractFileDescription(RegistryFile& output, const char* filename, const Specializations& specializations);
bool MergeSettingsFileInternal(const char* path, Format format, AZStd::string_view rootKey, AZStd::vector<char>& scratchBuffer);
void SignalNotifier(AZStd::string_view jsonPath, Type type);
mutable AZStd::recursive_mutex m_settingMutex;
mutable AZStd::recursive_mutex m_notifierMutex;
NotifyEvent m_notifiers;
PreMergeEvent m_preMergeEvent;
PostMergeEvent m_postMergeEvent;
rapidjson::Document m_settings;
JsonSerializerSettings m_serializationSettings;
JsonDeserializerSettings m_deserializationSettings;
@@ -25,6 +25,10 @@ namespace AZ
MOCK_CONST_METHOD2(Visit, bool(const VisitorCallback&, AZStd::string_view));
MOCK_METHOD1(RegisterNotifier, NotifyEventHandler(const NotifyCallback&));
MOCK_METHOD1(RegisterNotifier, NotifyEventHandler(NotifyCallback&&));
MOCK_METHOD1(RegisterPreMergeEvent, PreMergeEventHandler(const PreMergeEventCallback&));
MOCK_METHOD1(RegisterPreMergeEvent, PreMergeEventHandler(PreMergeEventCallback&&));
MOCK_METHOD1(RegisterPostMergeEvent, PostMergeEventHandler(const PostMergeEventCallback&));
MOCK_METHOD1(RegisterPostMergeEvent, PostMergeEventHandler(PostMergeEventCallback&&));
MOCK_CONST_METHOD2(Get, bool(bool&, AZStd::string_view));
MOCK_CONST_METHOD2(Get, bool(s64&, AZStd::string_view));
@@ -240,6 +240,37 @@ namespace UnitTest
static_assert(!AZStd::is_copy_assignable_v<AZ::Event<int32_t>>, "AZ Events should not be copy assignable");
}
TEST_F(EventTests, TestClaimHandlers_TakesAllSourceHandlers)
{
AZ::Event<> testEvent1;
AZ::Event<> testEvent2;
int32_t handlerInvokeCount{};
auto handlerCallback = [&handlerInvokeCount]()
{
++handlerInvokeCount;
};
AZ::Event<>::Handler testHandler1(handlerCallback);
AZ::Event<>::Handler testHandler2(handlerCallback);
testHandler1.Connect(testEvent1);
testHandler2.Connect(testEvent2);
EXPECT_TRUE(testEvent1.HasHandlerConnected());
EXPECT_TRUE(testEvent2.HasHandlerConnected());
testEvent1.ClaimHandlers(AZStd::move(testEvent2));
EXPECT_TRUE(testEvent1.HasHandlerConnected());
EXPECT_FALSE(testEvent2.HasHandlerConnected());
// testEvent1 should have both handlers
testEvent1.Signal();
EXPECT_EQ(2, handlerInvokeCount);
// testEvent2 should have neither of the handlers
testEvent2.Signal();
EXPECT_EQ(2, handlerInvokeCount);
}
TEST_F(EventTests, HandlerMoveAssignment_ProperlyDisconnectsFromOldEvent)
{
AZ::Event<> testEvent1;
@@ -34,7 +34,7 @@ namespace AzFramework
bool GetFullScreenState() const override;
void SetFullScreenState(bool fullScreenState) override;
bool CanToggleFullScreenState() const override { return true; }
uint32_t GetMainDisplayRefreshRate() const override;
uint32_t GetDisplayRefreshRate() const override;
private:
static NSWindowStyleMask ConvertToNSWindowStyleMask(const WindowStyleMasks& styleMasks);
@@ -142,7 +142,7 @@ namespace AzFramework
return nativeMask ? nativeMask : defaultMask;
}
uint32_t NativeWindowImpl_Darwin::GetMainDisplayRefreshRate() const
uint32_t NativeWindowImpl_Darwin::GetDisplayRefreshRate() const
{
return m_mainDisplayRefreshRate;
}
@@ -207,7 +207,10 @@ namespace AzFramework
// Handles Win32 Window Event callbacks
LRESULT CALLBACK NativeWindowImpl_Win32::WindowCallback(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
NativeWindowImpl_Win32* nativeWindowImpl = reinterpret_cast<NativeWindowImpl_Win32*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
NativeWindowImpl_Win32* nativeWindowImpl = reinterpret_cast<NativeWindowImpl_Win32*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
// If set to true, call DefWindowProc to ensure the default Windows behavior occurs
bool shouldBubbleEventUp = false;
switch (message)
{
@@ -276,14 +279,19 @@ namespace AzFramework
uint32_t refreshRate = DisplayConfig.dmDisplayFrequency;
WindowNotificationBus::Event(
nativeWindowImpl->GetWindowHandle(), &WindowNotificationBus::Events::OnRefreshRateChanged, refreshRate);
shouldBubbleEventUp = true;
break;
}
default:
return DefWindowProc(hWnd, message, wParam, lParam);
shouldBubbleEventUp = true;
break;
}
return 0;
if (!shouldBubbleEventUp)
{
return 0;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
void NativeWindowImpl_Win32::WindowSizeChanged(const uint32_t width, const uint32_t height)
@@ -27,7 +27,7 @@ namespace AzFramework
const WindowGeometry& geometry,
const WindowStyleMasks& styleMasks) override;
NativeWindowHandle GetWindowHandle() const override;
uint32_t GetMainDisplayRefreshRate() const override;
uint32_t GetDisplayRefreshRate() const override;
private:
UIWindow* m_nativeWindow;
@@ -66,7 +66,7 @@ namespace AzFramework
return m_nativeWindow;
}
uint32_t NativeWindowImpl_Ios::GetMainDisplayRefreshRate() const
uint32_t NativeWindowImpl_Ios::GetDisplayRefreshRate() const
{
return m_mainDisplayRefreshRate;
}
@@ -10,22 +10,9 @@
namespace AzNetworking
{
StringifySerializer::StringifySerializer(char delimeter, bool outputFieldNames, const AZStd::string& seperator)
: m_delimeter(delimeter)
, m_outputFieldNames(outputFieldNames)
, m_separator(seperator)
const StringifySerializer::ValueMap& StringifySerializer::GetValueMap() const
{
;
}
const AZStd::string& StringifySerializer::GetString() const
{
return m_string;
}
const StringifySerializer::StringMap& StringifySerializer::GetValueMap() const
{
return m_map;
return m_valueMap;
}
SerializerMode StringifySerializer::GetSerializerMode() const
@@ -137,22 +124,9 @@ namespace AzNetworking
template <typename T>
bool StringifySerializer::ProcessData(const char* name, const T& value)
{
// Only add delimeters after we have processed at least one element
if (!m_string.empty())
{
m_string += m_delimeter;
}
if (m_outputFieldNames)
{
m_string += m_prefix;
m_string += name;
m_string += m_separator;
}
AZ::CVarFixedString string = AZ::ConsoleTypeHelpers::ValueToString(value);
m_string += string.c_str();
m_map[m_prefix + name] = string.c_str();
const AZStd::string keyString = m_prefix + name;
AZ::CVarFixedString valueString = AZ::ConsoleTypeHelpers::ValueToString(value);
m_valueMap[keyString] = valueString.c_str();
return true;
}
}
@@ -20,17 +20,12 @@ namespace AzNetworking
{
public:
using StringMap = AZStd::map<AZStd::string, AZStd::string>;
using ValueMap = AZStd::map<AZStd::string, AZStd::string>;
StringifySerializer(char delimeter = ' ', bool outputFieldNames = true, const AZStd::string& seperator = "=");
StringifySerializer() = default;
// GetString
// After serializing objects, get the serialized values as a single string
const AZStd::string& GetString() const;
// GetValueMap
// After serializing objects, get the serialized values as key value pairs
const StringMap& GetValueMap() const;
//! After serializing objects, get the serialized values as a map of key/value pairs.
const ValueMap& GetValueMap() const;
// ISerializer interfaces
SerializerMode GetSerializerMode() const override;
@@ -62,15 +57,8 @@ namespace AzNetworking
template <typename T>
bool ProcessData(const char* name, const T& value);
private:
char m_delimeter;
bool m_outputFieldNames = true;
StringMap m_map;
AZStd::string m_string;
ValueMap m_valueMap;
AZStd::string m_prefix;
AZStd::string m_separator;
AZStd::deque<AZStd::size_t> m_prefixSizeStack;
};
}
@@ -1882,7 +1882,10 @@ namespace AzQtComponents
return;
}
QApplication::setOverrideCursor(m_dragCursor);
if (!QApplication::overrideCursor())
{
QApplication::setOverrideCursor(m_dragCursor);
}
QPoint relativePressPos = pressPos;
@@ -841,9 +841,6 @@ namespace AzToolsFramework
*/
virtual AZStd::string GetComponentIconPath(const AZ::Uuid& /*componentType*/, AZ::Crc32 /*componentIconAttrib*/, AZ::Component* /*component*/) { return AZStd::string(); }
/// Resource Selector hook, returns a path for a resource.
virtual AZStd::string SelectResource(const AZStd::string& /*resourceType*/, const AZStd::string& /*previousValue*/) { return AZStd::string(); }
/**
* Calculate the navigation 2D radius in units of an agent given its Navigation Type Name
* @param angentTypeName the name that identifies the agent navigation type
@@ -219,42 +219,10 @@ namespace AzToolsFramework
bool PrefabEditorEntityOwnershipService::SaveToStream(AZ::IO::GenericStream& stream, AZStd::string_view filename)
{
AZ::IO::Path relativePath = m_loaderInterface->GenerateRelativePath(filename);
AzToolsFramework::Prefab::TemplateId templateId = m_prefabSystemComponent->GetTemplateIdFromFilePath(relativePath);
m_rootInstance->SetTemplateSourcePath(relativePath);
if (templateId == AzToolsFramework::Prefab::InvalidTemplateId)
{
m_rootInstance->m_containerEntity->AddComponent(aznew Prefab::EditorPrefabComponent());
HandleEntitiesAdded({ m_rootInstance->m_containerEntity.get() });
AzToolsFramework::Prefab::PrefabDom dom;
bool success = AzToolsFramework::Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(*m_rootInstance, dom);
if (!success)
{
AZ_Error("Prefab", false, "Failed to convert current root instance into a DOM when saving file '%.*s'", AZ_STRING_ARG(filename));
return false;
}
templateId = m_prefabSystemComponent->AddTemplate(relativePath, AZStd::move(dom));
if (templateId == AzToolsFramework::Prefab::InvalidTemplateId)
{
AZ_Error("Prefab", false, "Couldn't add new template id '%i' when saving file '%.*s'", templateId, AZ_STRING_ARG(filename));
return false;
}
}
Prefab::TemplateId prevTemplateId = m_rootInstance->GetTemplateId();
m_rootInstance->SetTemplateId(templateId);
if (prevTemplateId != Prefab::InvalidTemplateId && templateId != prevTemplateId)
{
// Make sure we only have one level template loaded at a time
m_prefabSystemComponent->RemoveTemplate(prevTemplateId);
}
AZStd::string out;
if (!m_loaderInterface->SaveTemplateToString(m_rootInstance->GetTemplateId(), out))
{
return false;
@@ -266,7 +234,7 @@ namespace AzToolsFramework
{
return false;
}
m_prefabSystemComponent->SetTemplateDirtyFlag(templateId, false);
m_prefabSystemComponent->SetTemplateDirtyFlag(m_rootInstance->GetTemplateId(), false);
return true;
}
@@ -162,7 +162,6 @@ namespace AzToolsFramework
: QObject(sourceWidget)
, m_sourceWidget(sourceWidget)
, m_keyboardModifiers(AZStd::make_shared<AzFramework::ModifierKeyStates>())
, m_cursorPosition(AZStd::make_shared<AzFramework::InputChannel::PositionData2D>())
{
InitializeKeyMappings();
InitializeMouseButtonMappings();
@@ -230,24 +229,17 @@ namespace AzToolsFramework
return false;
}
// Because there's no "end" to mouse movement and wheel events, we reset mouse movement channels that have been opened
// during the next processed non-mouse event.
if (m_mouseChannelsNeedUpdate && event->type() != QEvent::Type::MouseMove && event->type() != QEvent::Type::Wheel)
{
m_cursorPosition->m_normalizedPositionDelta = AZ::Vector2::CreateZero();
ProcessPendingMouseEvents();
m_mouseChannelsNeedUpdate = false;
}
const auto eventType = event->type();
// Only accept mouse & key release events that originate from an object that is not our target widget,
// as we don't want to erroneously intercept user input meant for another component.
if (object != m_sourceWidget && event->type() != QEvent::Type::KeyRelease && event->type() != QEvent::Type::MouseButtonRelease)
if (object != m_sourceWidget && eventType != QEvent::Type::KeyRelease && eventType != QEvent::Type::MouseButtonRelease)
{
return false;
}
// If our focus changes, go ahead and reset all input devices.
if (event->type() == QEvent::FocusIn || event->type() == QEvent::FocusOut)
if (eventType == QEvent::FocusIn || eventType == QEvent::FocusOut)
{
HandleFocusChange(event);
}
@@ -255,27 +247,28 @@ namespace AzToolsFramework
// ShortcutOverride is used in lieu of KeyPress for high priority input channels like Alt
// that need to be accepted and stopped before they bubble up and cause unintended behavior.
else if (
event->type() == QEvent::Type::KeyPress || event->type() == QEvent::Type::KeyRelease ||
event->type() == QEvent::Type::ShortcutOverride)
eventType == QEvent::Type::KeyPress || eventType == QEvent::Type::KeyRelease || eventType == QEvent::Type::ShortcutOverride)
{
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
HandleKeyEvent(keyEvent);
}
// Map mouse events to input channels.
else if (event->type() == QEvent::Type::MouseButtonPress || event->type() == QEvent::Type::MouseButtonRelease || event->type() == QEvent::Type::MouseButtonDblClick)
else if (
eventType == QEvent::Type::MouseButtonPress || eventType == QEvent::Type::MouseButtonRelease ||
eventType == QEvent::Type::MouseButtonDblClick)
{
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
HandleMouseButtonEvent(mouseEvent);
}
// Map mouse movement to the movement input channels.
// This includes SystemCursorPosition alongside Movement::X and Movement::Y.
else if (event->type() == QEvent::Type::MouseMove)
else if (eventType == QEvent::Type::MouseMove)
{
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
HandleMouseMoveEvent(mouseEvent);
}
// Map wheel events to the mouse Z movement channel.
else if (event->type() == QEvent::Type::Wheel)
else if (eventType == QEvent::Type::Wheel)
{
QWheelEvent* wheelEvent = static_cast<QWheelEvent*>(event);
HandleWheelEvent(wheelEvent);
@@ -303,14 +296,16 @@ namespace AzToolsFramework
auto mouseWheelChannel =
GetInputChannel<AzFramework::InputChannelDeltaWithSharedPosition2D>(AzFramework::InputDeviceMouse::Movement::Z);
systemCursorChannel->ProcessRawInputEvent(m_cursorPosition->m_normalizedPositionDelta.GetLength());
systemCursorChannel->ProcessRawInputEvent(m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta.GetLength());
// Generate movement events based on the pixel delta divided by the DPI scaling factor, to calculate a rough approximation
// of cursor movement velocity.
movementXChannel->ProcessRawInputEvent(
m_cursorPosition->m_normalizedPositionDelta.GetX() * aznumeric_cast<float>(m_sourceWidget->width()) / m_sourceWidget->devicePixelRatioF());
m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta.GetX() * aznumeric_cast<float>(m_sourceWidget->width()) /
m_sourceWidget->devicePixelRatioF());
movementYChannel->ProcessRawInputEvent(
m_cursorPosition->m_normalizedPositionDelta.GetY() * aznumeric_cast<float>(m_sourceWidget->height()) / m_sourceWidget->devicePixelRatioF());
mouseWheelChannel->ProcessRawInputEvent(0.f);
m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta.GetY() * aznumeric_cast<float>(m_sourceWidget->height()) /
m_sourceWidget->devicePixelRatioF());
mouseWheelChannel->ProcessRawInputEvent(0.0f);
NotifyUpdateChannelIfNotIdle(systemCursorChannel, nullptr);
NotifyUpdateChannelIfNotIdle(movementXChannel, nullptr);
@@ -358,14 +353,13 @@ namespace AzToolsFramework
void QtEventToAzInputMapper::HandleMouseMoveEvent(QMouseEvent* mouseEvent)
{
AZ::Vector2 lastCursorPosition = m_cursorPosition->m_normalizedPosition;
AZ::Vector2 lastCursorPosition = m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition;
const QPoint mousePos = mouseEvent->pos();
const AZ::Vector2 normalizedPosition = WidgetPositionToNormalizedPosition(mousePos);
m_cursorPosition->m_normalizedPositionDelta = normalizedPosition - m_cursorPosition->m_normalizedPosition;
m_cursorPosition->m_normalizedPosition = normalizedPosition;
m_mouseDevice->m_cursorPositionData2D->m_normalizedPositionDelta = normalizedPosition - m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition;
m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition = normalizedPosition;
ProcessPendingMouseEvents();
m_mouseChannelsNeedUpdate = true;
if (m_capturingCursor)
{
@@ -376,7 +370,7 @@ namespace AzToolsFramework
// Even though we just set the cursor position, there are edge cases such as remote desktop that will leave
// the cursor position unchanged. For safety, we re-cache our last cursor position for delta generation.
QPoint actualWidgetPosition = m_sourceWidget->mapFromGlobal(QCursor::pos());
m_cursorPosition->m_normalizedPosition = WidgetPositionToNormalizedPosition(actualWidgetPosition);
m_mouseDevice->m_cursorPositionData2D->m_normalizedPosition = WidgetPositionToNormalizedPosition(actualWidgetPosition);
}
}
@@ -427,21 +421,18 @@ namespace AzToolsFramework
}
cursorZChannel->ProcessRawInputEvent(aznumeric_cast<float>(wheelAngle));
NotifyUpdateChannelIfNotIdle(cursorZChannel, wheelEvent);
m_mouseChannelsNeedUpdate = true;
}
void QtEventToAzInputMapper::HandleFocusChange(QEvent* event)
{
for (auto& channelData : m_channels)
{
// If resetting the input device changed the channel state, submit it to the mapped channel list
// for processing.
// If resetting the input device changed the channel state, submit it to the mapped channel list for processing.
if (channelData.second->IsActive())
{
channelData.second->UpdateState(false);
NotifyUpdateChannelIfNotIdle(channelData.second, event);
}
}
m_mouseChannelsNeedUpdate = false;
}
} // namespace AzToolsFramework
@@ -138,8 +138,6 @@ namespace AzToolsFramework
// The current keyboard modifier state used by our synthetic key input channels.
AZStd::shared_ptr<AzFramework::ModifierKeyStates> m_keyboardModifiers;
// The current normalized cursor position used by our synthetic system cursor event.
AZStd::shared_ptr<AzFramework::InputChannel::PositionData2D> m_cursorPosition;
// A lookup table for Qt key -> AZ input channel.
AZStd::unordered_map<Qt::Key, AzFramework::InputChannelId> m_keyMappings;
// A lookup table for Qt mouse button -> AZ input channel.
@@ -152,8 +150,6 @@ namespace AzToolsFramework
AZStd::unordered_map<AzFramework::InputChannelId, AzFramework::InputChannel*> m_channels;
// The source widget to map events from, used to calculate the relative mouse position within the widget bounds.
QWidget* m_sourceWidget;
// Flags when mouse movement channels have been opened and may need to be closed (as there are no movement ended events).
bool m_mouseChannelsNeedUpdate = false;
// Flags whether or not Qt events should currently be processed.
bool m_enabled = true;
// Flags whether or not the cursor is being constrained to the source widget (for invisible mouse movement).
@@ -5,11 +5,9 @@
*
*/
#include <AzToolsFramework/Logger/TraceLogger.h>
#include <AzCore/Settings/SettingsRegistryMergeUtils.h>
#include <AzFramework/StringFunc/StringFunc.h>
#include <AzToolsFramework/Logger/TraceLogger.h>
namespace AzToolsFramework
{
@@ -25,6 +23,22 @@ namespace AzToolsFramework
bool TraceLogger::OnOutput(const char* window, const char* message)
{
for (const auto& filter : m_windowFilters)
{
if (AZ::StringFunc::Contains(window, filter))
{
return true;
}
}
for (const auto& filter : m_messageFilters)
{
if (AZ::StringFunc::Contains(message, filter))
{
return true;
}
}
if (m_logFile)
{
m_logFile->AppendLog(AzFramework::LogFile::SEV_NORMAL, window, message);
@@ -36,10 +50,10 @@ namespace AzToolsFramework
return false;
}
void TraceLogger::WriteStartupLog(const AZStd::string& logFileName)
{
void TraceLogger::PrepareLogFile(const AZStd::string& logFileName)
{
using namespace AzFramework;
AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance();
AZ_Assert(fileIO != nullptr, "FileIO should be running at this point");
@@ -71,4 +85,34 @@ namespace AzToolsFramework
m_logFile->FlushLog();
}
}
void TraceLogger::AddWindowFilter(const AZStd::string& filter)
{
m_windowFilters.insert(filter);
}
void TraceLogger::RemoveWindowFilter(const AZStd::string& filter)
{
m_windowFilters.erase(filter);
}
void TraceLogger::ClearWindowFilter()
{
m_windowFilters.clear();
}
void TraceLogger::AddMessageFilter(const AZStd::string& filter)
{
m_messageFilters.insert(filter);
}
void TraceLogger::RemoveMessageFilter(const AZStd::string& filter)
{
m_messageFilters.erase(filter);
}
void TraceLogger::ClearMessageFilter()
{
m_messageFilters.clear();
}
} // namespace AzToolsFramework
@@ -22,8 +22,26 @@ namespace AzToolsFramework
TraceLogger();
~TraceLogger();
//! Intalize logging for O3DEToolsApplications
void WriteStartupLog(const AZStd::string& logFileName);
//! Open log file and dump log sink into it
void PrepareLogFile(const AZStd::string& logFileName);
//! Add filter to ignore messages for windows with matching names
void AddWindowFilter(const AZStd::string& filter);
//! Remove window filter
void RemoveWindowFilter(const AZStd::string& filter);
//! Clear window filters
void ClearWindowFilter();
//! Add filter to ignore messages with matching names
void AddMessageFilter(const AZStd::string& filter);
//! Remove message filter
void RemoveMessageFilter(const AZStd::string& filter);
//! Clear message filters
void ClearMessageFilter();
protected:
//////////////////////////////////////////////////////////////////////////
@@ -38,6 +56,8 @@ namespace AzToolsFramework
AZStd::string message;
};
AZStd::vector<LogMessage> m_startupLogSink;
AZStd::unordered_set<AZStd::string> m_windowFilters;
AZStd::unordered_set<AZStd::string> m_messageFilters;
AZStd::unique_ptr<AzFramework::LogFile> m_logFile;
};
} // namespace AzToolsFramework
@@ -15,6 +15,7 @@
#include <AzToolsFramework/Prefab/Instance/InstanceEntityMapperInterface.h>
#include <AzToolsFramework/Prefab/PrefabLoaderInterface.h>
#include <AzToolsFramework/Prefab/PrefabSystemComponentInterface.h>
#include <Prefab/PrefabDomUtils.h>
namespace AzToolsFramework
{
@@ -81,6 +82,15 @@ namespace AzToolsFramework
result.Combine(resultInstances);
}
PrefabDomUtils::LinkIdMetadata* subPathLinkId = context.GetMetadata().Find<PrefabDomUtils::LinkIdMetadata>();
if (subPathLinkId)
{
AZ::ScopedContextPath subPathSource(context, "m_linkId");
result = ContinueStoringToJsonObjectField(
outputValue, "LinkId", &(instance->m_linkId), &InvalidLinkId, azrtti_typeid<decltype(instance->m_linkId)>(), context);
}
return context.Report(result,
result.GetProcessing() == JSR::Processing::Completed ? "Successfully stored Instance information for Prefab." :
"Failed to store Instance information for Prefab.");
@@ -88,6 +88,11 @@ namespace AzToolsFramework
settings.m_keepDefaults = true;
}
if ((flags & StoreFlags::StoreLinkIds) != StoreFlags::None)
{
settings.m_metadata.Create<LinkIdMetadata>();
}
AZStd::string scratchBuffer;
auto issueReportingCallback = [&scratchBuffer]
(AZStd::string_view message, AZ::JsonSerializationResult::ResultCode result,
@@ -45,7 +45,11 @@ namespace AzToolsFramework
//! By default an instance will be stored with default values. In cases where we want to store less json without defaults
//! such as saving to disk, this flag will control that behavior.
StripDefaultValues = 1 << 0
StripDefaultValues = 1 << 0,
//! We do not save linkIds to file. However when loading a level we want to temporarily save
//! linkIds to instance dom so any nested prefabs will have linkIds correctly set.
StoreLinkIds = 1 << 1
};
AZ_DEFINE_ENUM_BITWISE_OPERATORS(StoreFlags);
@@ -150,6 +154,14 @@ namespace AzToolsFramework
[[maybe_unused]] const AZStd::string_view printMessage,
[[maybe_unused]] const AzToolsFramework::Prefab::PrefabDomValue& prefabDomValue);
//! An empty struct for passing to JsonSerializerSettings.m_metadata that is consumed by InstanceSerializer::Store.
//! If present in metadata, linkIds will be stored to instance dom.
struct LinkIdMetadata
{
AZ_RTTI(LinkIdMetadata, "{8FF7D299-14E3-41D4-90C5-393A240FAE7C}");
virtual ~LinkIdMetadata() {}
};
} // namespace PrefabDomUtils
} // namespace Prefab
} // namespace AzToolsFramework
@@ -300,7 +300,7 @@ namespace AzToolsFramework
}
PrefabDom storedPrefabDom(&loadedTemplateDom->get().GetAllocator());
if (!PrefabDomUtils::StoreInstanceInPrefabDom(loadedPrefabInstance, storedPrefabDom))
if (!PrefabDomUtils::StoreInstanceInPrefabDom(loadedPrefabInstance, storedPrefabDom, PrefabDomUtils::StoreFlags::StoreLinkIds))
{
return false;
}
@@ -6,7 +6,6 @@
*
*/
// Description : For listing available script commands with their descriptions
#include "ScriptHelpDialog.h"
@@ -23,6 +22,7 @@
// AzToolsFramework
#include <AzToolsFramework/API/EditorPythonConsoleBus.h> // for EditorPythonConsoleInterface
#include <AzToolsFramework/API/EditorWindowRequestBus.h>
AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING
#include <AzToolsFramework/PythonTerminal/ui_ScriptHelpDialog.h>
@@ -313,6 +313,45 @@ namespace AzToolsFramework
connect(ui->tableView, &ScriptTableView::doubleClicked, this, &CScriptHelpDialog::OnDoubleClick);
}
CScriptHelpDialog* CScriptHelpDialog::GetInstance()
{
static CScriptHelpDialog* pInstance = nullptr;
if (!pInstance)
{
QMainWindow* mainWindow = GetMainWindowOfCurrentApplication();
if (!mainWindow)
{
AZ_Assert(false, "Failed to find MainWindow.");
return nullptr;
}
QWidget* parentWidget = mainWindow->window()
? mainWindow->window()
: mainWindow; // MainWindow might have a WindowDecorationWrapper parent. Makes a difference on macOS.
pInstance = new CScriptHelpDialog(parentWidget);
}
return pInstance;
}
QMainWindow* CScriptHelpDialog::GetMainWindowOfCurrentApplication()
{
QWidget* mainWindowWidget = nullptr;
EditorWindowRequestBus::BroadcastResult(mainWindowWidget, &EditorWindowRequests::GetAppMainWindow);
if (QMainWindow* mainWindow = qobject_cast<QMainWindow*>(mainWindowWidget))
{
return mainWindow;
}
for (QWidget* topLevelWidget : qApp->topLevelWidgets())
{
if (QMainWindow* mainWindow = qobject_cast<QMainWindow*>(topLevelWidget))
{
return mainWindow;
}
}
return nullptr;
}
void CScriptHelpDialog::OnDoubleClick(const QModelIndex& index)
{
if (!index.isValid())
@@ -132,43 +132,13 @@ namespace AzToolsFramework
{
Q_OBJECT
public:
static CScriptHelpDialog* GetInstance()
{
static CScriptHelpDialog* pInstance = nullptr;
if (!pInstance)
{
QMainWindow* mainWindow = GetMainWindowOfCurrentApplication();
if (!mainWindow)
{
AZ_Assert(false, "Failed to find MainWindow.");
return nullptr;
}
QWidget* parentWidget = mainWindow->window() ? mainWindow->window() : mainWindow; // MainWindow might have a WindowDecorationWrapper parent. Makes a difference on macOS.
pInstance = new CScriptHelpDialog(parentWidget);
}
return pInstance;
}
static CScriptHelpDialog* GetInstance();
private Q_SLOTS:
void OnDoubleClick(const QModelIndex&);
private:
static QMainWindow* GetMainWindowOfCurrentApplication()
{
QMainWindow* mainWindow = nullptr;
for (QWidget* w : qApp->topLevelWidgets())
{
mainWindow = qobject_cast<QMainWindow*>(w);
if (mainWindow)
{
return mainWindow;
}
}
return nullptr;
}
explicit CScriptHelpDialog(QWidget* parent = nullptr);
static QMainWindow* GetMainWindowOfCurrentApplication();
QScopedPointer<Ui::ScriptDialog> ui;
};
} // namespace AzToolsFramework
@@ -19,6 +19,7 @@
#include <AzCore/Component/Component.h>
#include <AzCore/Component/ComponentBus.h>
#include <AzCore/Component/EntityBus.h>
#include <AzCore/Component/TickBus.h>
#include <AzCore/Asset/AssetCommon.h>
#include <AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h>
#include <AzToolsFramework/Undo/UndoSystem.h>
@@ -110,6 +111,7 @@ namespace AzToolsFramework
, public EditorInspectorComponentNotificationBus::MultiHandler
, private AzToolsFramework::ComponentModeFramework::EditorComponentModeNotificationBus::Handler
, public AZ::EntitySystemBus::Handler
, public AZ::TickBus::Handler
, private EditorWindowUIRequestBus::Handler
{
Q_OBJECT;
@@ -117,6 +119,23 @@ namespace AzToolsFramework
AZ_CLASS_ALLOCATOR(EntityPropertyEditor, AZ::SystemAllocator, 0)
enum class ReorderState
{
Inactive, // No row widget reordering operation is in progress.
DraggingComponent, // User is dragging a component editor.
DraggingRowWidget, // User is dragging a row widget around.
UsingMenu, // User has the context menu open and may hover over a move up/down operation.
MenuOperationInProgress, // User has selected a move/up down menu item.
WaitForRedraw, // Wait for rebuild of RPE.
HighlightMovedRow // User has moved a row, highlight the new position.
};
enum class DropArea
{
Above,
Below
};
EntityPropertyEditor(QWidget* pParent = NULL, Qt::WindowFlags flags = Qt::WindowFlags(), bool isLevelEntityEditor = false);
virtual ~EntityPropertyEditor();
@@ -151,6 +170,16 @@ namespace AzToolsFramework
bool IsLockedToSpecificEntities() const { return !m_overrideSelectedEntityIds.empty(); }
static bool AreComponentsCopyable(const AZ::Entity::ComponentArrayType& components, const ComponentFilter& filter);
ReorderState GetReorderState() const;
ComponentEditor* GetEditorForCurrentReorderRowWidget() const;
PropertyRowWidget* GetReorderRowWidget() const;
PropertyRowWidget* GetReorderDropTarget() const;
DropArea GetReorderDropArea() const;
QPixmap GetReorderRowWidgetImage() const;
float GetMoveIndicatorAlpha() const;
PropertyRowWidget* GetRowToHighlight();
Q_SIGNALS:
void SelectedEntityNameChanged(const AZ::EntityId& entityId, const AZStd::string& name);
@@ -211,6 +240,9 @@ namespace AzToolsFramework
void GetSelectedEntities(EntityIdList& selectedEntityIds) override;
void SetNewComponentId(AZ::ComponentId componentId) override;
// TickBus
void OnTick(float deltaTime, AZ::ScriptTimePoint time) override;
// EditorWindowRequestBus overrides
void SetEditorUiEnabled(bool enable) override;
@@ -253,6 +285,10 @@ namespace AzToolsFramework
void ContextMenuActionPullFieldData(AZ::Component* parentComponent, InstanceDataNode* fieldNode);
void ContextMenuActionSetDataFlag(InstanceDataNode* node, AZ::DataPatch::Flag flag, bool additive);
void GenerateRowWidgetIndexMapToChildIndex(PropertyRowWidget* parent, int destIndex);
void ContextMenuActionMoveItemUp(ComponentEditor* componentEditor, PropertyRowWidget* rowWidget);
void ContextMenuActionMoveItemDown(ComponentEditor* componentEditor, PropertyRowWidget* rowWidget);
/// Given an InstanceDataNode, calculate a DataPatch address relative to the entity.
/// @return true if successful.
bool GetEntityDataPatchAddress(const InstanceDataNode* componentFieldNode, AZ::DataPatch::AddressType& dataPatchAddressOut, AZ::EntityId* entityIdOut = nullptr) const;
@@ -341,8 +377,6 @@ namespace AzToolsFramework
QAction* m_actionToMoveComponentsBottom = nullptr;
QAction* m_resetToSliceAction = nullptr;
bool m_isShowingContextMenu = false;
void CreateActions();
void UpdateActions();
@@ -390,6 +424,10 @@ namespace AzToolsFramework
void ResetToSlice();
bool DoesOwnFocus() const;
AZ::u32 GetHeightOfRowAndVisibleChildren(const PropertyRowWidget* row) const;
QRect GetWidgetAndVisibleChildrenGlobalRect(const PropertyRowWidget* widget) const;
PropertyRowWidget* GetRowWidgetAtSameLevelAfter(PropertyRowWidget* widget) const;
PropertyRowWidget* GetRowWidgetAtSameLevelBefore(PropertyRowWidget* widget) const;
QRect GetWidgetGlobalRect(const QWidget* widget) const;
bool DoesIntersectWidget(const QRect& globalRect, const QWidget* widget) const;
bool DoesIntersectSelectedComponentEditor(const QRect& globalRect) const;
@@ -445,6 +483,8 @@ namespace AzToolsFramework
bool HandleSelectionEvents(QObject* object, QEvent* event);
bool m_selectionEventAccepted;
bool HandleMenuEvent(QObject* object, QEvent* event);
// drag and drop events
QRect GetInflatedRectFromPoint(const QPoint& point, int radius) const;
bool GetComponentsAtDropEventPosition(QDropEvent* event, AZ::Entity::ComponentArrayType& targetComponents);
@@ -458,8 +498,12 @@ namespace AzToolsFramework
ComponentEditor* GetReorderDropTarget(const QRect& globalRect) const;
bool ResetDrag(QMouseEvent* event);
bool FindAllowedRowWidgetReorderDropTarget(const QPoint& globalPos);
bool UpdateRowWidgetDrag(const QPoint& localPos, Qt::MouseButtons mouseButtons, const QMimeData* mimeData);
PropertyRowWidget* FindPropertyRowWidgetAt(QPoint globalPos);
bool UpdateDrag(const QPoint& localPos, Qt::MouseButtons mouseButtons, const QMimeData* mimeData);
bool StartDrag(QMouseEvent* event);
void EndRowWidgetReorder();
bool HandleDrop(QDropEvent* event);
bool HandleDropForComponentTypes(QDropEvent* event);
bool HandleDropForComponentAssets(QDropEvent* event);
@@ -468,6 +512,8 @@ namespace AzToolsFramework
bool CanDropForComponentTypes(const QMimeData* mimeData) const;
bool CanDropForComponentAssets(const QMimeData* mimeData) const;
bool CanDropForAssetBrowserEntries(const QMimeData* mimeData) const;
void SetRowWidgetHighlighted(PropertyRowWidget* rowWidget);
AZStd::vector<AZ::s32> ExtractComponentEditorIndicesFromMimeData(const QMimeData* mimeData) const;
ComponentEditorVector GetComponentEditorsFromIndices(const AZStd::vector<AZ::s32>& indices) const;
ComponentEditor* GetComponentEditorsFromIndex(const AZ::s32 index) const;
@@ -559,6 +605,8 @@ namespace AzToolsFramework
QIcon m_emptyIcon;
QIcon m_clearIcon;
QIcon m_dragIcon;
QCursor m_dragCursor;
QStandardItem* m_comboItems[StatusItems];
EntityIdSet m_overrideSelectedEntityIds;
@@ -566,6 +614,19 @@ namespace AzToolsFramework
Prefab::PrefabPublicInterface* m_prefabPublicInterface = nullptr;
bool m_prefabsAreEnabled = false;
// Reordering row widgets within the RPE.
static constexpr float MoveFadeSeconds = 0.5f;
ReorderState m_currentReorderState = ReorderState::Inactive;
ComponentEditor* m_reorderRowWidgetEditor = nullptr;
InstanceDataNode* m_nodeToMove = nullptr;
PropertyRowWidget* m_reorderRowWidget = nullptr;
PropertyRowWidget* m_reorderDropTarget = nullptr;
DropArea m_reorderDropArea = DropArea::Above;
QPixmap m_reorderRowImage;
float m_moveFadeSecondsRemaining;
AZStd::vector<int> m_indexMapOfMovedRow;
// When m_initiatingPropertyChangeNotification is set to true, it means this EntityPropertyEditor is
// broadcasting a change to all listeners about a property change for a given entity. This is needed
// so that we don't update the values twice for this inspector
@@ -573,6 +634,9 @@ namespace AzToolsFramework
void ConnectToEntityBuses(const AZ::EntityId& entityId);
void DisconnectFromEntityBuses(const AZ::EntityId& entityId);
void BeginMoveRowWidgetFade();
void HighlightMovedRowWidget();
//! Stores a component id to be focused on next time the UI updates.
AZStd::optional<AZ::ComponentId> m_newComponentId;
@@ -594,6 +658,8 @@ namespace AzToolsFramework
bool SelectedEntitiesAreFromSameSourceSliceEntity() const;
void DragStopped();
AZ::Entity* GetSelectedEntityById(AZ::EntityId& entityId) const;
};
@@ -7,8 +7,8 @@
*/
#include "PropertyAudioCtrl.h"
#include "PropertyQTConstants.h"
#include <UI/PropertyEditor/PropertyAudioCtrl.h>
#include <UI/PropertyEditor/PropertyQTConstants.h>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
@@ -34,7 +34,7 @@ namespace AzToolsFramework
: QWidget(parent)
, m_browseEdit(nullptr)
, m_mainLayout(nullptr)
, m_propertyType(AudioPropertyType::Invalid)
, m_propertyType(AudioPropertyType::NumTypes)
{
// create the gui
m_mainLayout = new QHBoxLayout();
@@ -96,7 +96,7 @@ namespace AzToolsFramework
return;
}
if (type != AudioPropertyType::Invalid)
if (type != AudioPropertyType::NumTypes)
{
m_propertyType = type;
}
@@ -136,10 +136,11 @@ namespace AzToolsFramework
void AudioControlSelectorWidget::OnOpenAudioControlSelector()
{
AZStd::string resourceResult;
AZStd::string resourceType(GetResourceSelectorNameFromType(m_propertyType));
AZStd::string currentValue(m_controlName.toStdString().c_str());
EditorRequests::Bus::BroadcastResult(resourceResult, &EditorRequests::Bus::Events::SelectResource, resourceType, currentValue);
AZStd::string resourceResult;
AudioControlSelectorRequestBus::EventResult(
resourceResult, m_propertyType,
&AudioControlSelectorRequestBus::Events::SelectResource, currentValue);
SetControlName(QString(resourceResult.c_str()));
}
@@ -167,12 +168,12 @@ namespace AzToolsFramework
{
case AudioPropertyType::Trigger:
return { "AudioTrigger" };
case AudioPropertyType::Rtpc:
return { "AudioRTPC" };
case AudioPropertyType::Switch:
return { "AudioSwitch" };
case AudioPropertyType::SwitchState:
return { "AudioSwitchState" };
case AudioPropertyType::Rtpc:
return { "AudioRTPC" };
case AudioPropertyType::Environment:
return { "AudioEnvironment" };
case AudioPropertyType::Preload:
@@ -29,6 +29,27 @@ class QMimeData;
namespace AzToolsFramework
{
//=============================================================================
// Audio Control Selector Request Bus
// For connecting UI proper
//=============================================================================
class AudioControlSelectorRequests
: public AZ::EBusTraits
{
public:
// EBusTraits
static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById;
static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single;
using BusIdType = AudioPropertyType;
virtual AZStd::string SelectResource(AZStd::string_view previousValue)
{
return previousValue;
}
};
using AudioControlSelectorRequestBus = AZ::EBus<AudioControlSelectorRequests>;
//=============================================================================
// Audio Control Selector Widget
//=============================================================================
@@ -18,15 +18,15 @@
namespace AzToolsFramework
{
//=========================================================================
enum class AudioPropertyType
enum class AudioPropertyType : AZ::u32
{
Invalid = 0,
Trigger,
Trigger = 0,
Rtpc,
Switch,
SwitchState,
Rtpc,
Environment,
Preload,
NumTypes,
};
//=========================================================================
@@ -40,7 +40,7 @@ namespace AzToolsFramework
virtual ~CReflectedVarAudioControl() = default;
AZStd::string m_controlName;
AudioPropertyType m_propertyType = AudioPropertyType::Invalid;
AudioPropertyType m_propertyType = AudioPropertyType::NumTypes;
static void Reflect(AZ::ReflectContext* context)
{
@@ -368,10 +368,15 @@ namespace AzToolsFramework
delete m_containerAddButton;
}
this->unsetCursor();
if ((m_parentRow) && (m_parentRow->IsContainerEditable()))
{
if (!m_elementRemoveButton)
{
QIcon icon = QIcon(QStringLiteral(":/Cursors/Grab_release.svg"));
this->setCursor(QCursor(icon.pixmap(16), 5, 2));
static QIcon s_iconRemove(QStringLiteral(":/stylesheet/img/UI20/delete-16.svg"));
m_elementRemoveButton = new QToolButton(this);
m_elementRemoveButton->setAutoRaise(true);
@@ -570,7 +575,12 @@ namespace AzToolsFramework
AZ_Assert(m_selectionEnabled, "Property is not selectable");
m_isSelected = selected;
m_nameLabel->setProperty("selected", selected);
}
}
bool PropertyRowWidget::GetSelected()
{
return m_isSelected;
}
void PropertyRowWidget::SetSelectionEnabled(bool selectionEnabled)
{
@@ -1395,6 +1405,21 @@ namespace AzToolsFramework
return !m_childrenRows.empty();
}
AZ::u32 PropertyRowWidget::GetChildRowCount() const
{
return static_cast<AZ::u32>(m_childrenRows.size());
}
PropertyRowWidget* PropertyRowWidget::GetChildRowByIndex(AZ::u32 index) const
{
if (index >= m_childrenRows.size())
{
return nullptr;
}
return m_childrenRows[index];
}
bool PropertyRowWidget::ShouldPreValidatePropertyChange() const
{
return (m_changeValidators.size() > 0);
@@ -1722,6 +1747,162 @@ namespace AzToolsFramework
return m_parentRow->CanChildrenBeReordered();
}
int PropertyRowWidget::GetIndexInParent() const
{
if (!GetParentRow())
{
return -1;
}
for (AZ::u32 index = 0; index < GetParentRow()->GetChildRowCount(); index++)
{
if (GetParentRow()->GetChildrenRows()[index] == this)
{
return index;
}
}
return -1;
}
bool PropertyRowWidget::CanMoveUp() const
{
if (!CanBeReordered())
{
return false;
}
return this != m_parentRow->GetChildRowByIndex(0);
}
bool PropertyRowWidget::CanMoveDown() const
{
if (!CanBeReordered())
{
return false;
}
AZ::u32 numChildrenOfParent = m_parentRow->GetChildRowCount();
return this != m_parentRow->GetChildRowByIndex(numChildrenOfParent - 1);
}
int PropertyRowWidget::GetContainingEditorFrameWidth()
{
QWidget* parent = parentWidget();
// Find the first ancestor that can be cast to a QFrame, this will be the RPE.
while (!qobject_cast<QFrame*>(parent))
{
parent = parent->parentWidget();
}
if (!parent)
{
return 0;
}
// The parent of the RPE is the size we want.
parent = parent->parentWidget();
return parent->rect().width();
}
int PropertyRowWidget::GetHeightOfRowAndVisibleChildren()
{
int height = rect().height();
if (!GetChildRowCount() || !IsExpanded())
{
return height;
}
for (auto childRow : GetChildrenRows())
{
height += childRow->GetHeightOfRowAndVisibleChildren();
}
return height;
}
int PropertyRowWidget::DrawDragImageAndVisibleChildrenInto(QPainter& painter, int xpos, int ypos)
{
// Render our image into the given painter.
int ystart = ypos;
render(&painter, QPoint(xpos, ypos));
if (!GetChildRowCount() || !IsExpanded())
{
return rect().height();
}
ypos += rect().height();
// Recursively draw any children.
for (auto childRow : GetChildrenRows())
{
ypos += childRow->DrawDragImageAndVisibleChildrenInto(painter, xpos, ypos);
}
return ypos - ystart;
}
QPixmap PropertyRowWidget::createDragImage(
const QColor backgroundColor, const QColor borderColor, const float alpha, DragImageType imageType)
{
// Make the drag box as wide as the containing editor minus a gap each side for the border.
static constexpr int ParentEditorBorderSize = 2;
int width = GetContainingEditorFrameWidth() - ParentEditorBorderSize * 2;
int height = 0;
if (imageType == DragImageType::IncludeVisibleChildren)
{
height = GetHeightOfRowAndVisibleChildren();
}
else
{
height = rect().height();
}
const auto dpr = devicePixelRatioF();
QPixmap dragImage(width * dpr, height * dpr);
dragImage.setDevicePixelRatio(dpr);
dragImage.fill(Qt::transparent);
QRect imageRect = QRect(0, 0, width, height);
QPainter dragPainter(&dragImage);
dragPainter.setCompositionMode(QPainter::CompositionMode_Source);
dragPainter.fillRect(imageRect, Qt::transparent);
dragPainter.setCompositionMode(QPainter::CompositionMode_SourceOver);
dragPainter.setOpacity(alpha);
dragPainter.fillRect(imageRect, backgroundColor);
dragPainter.setOpacity(1.0f);
int marginWidth = (imageRect.width() - rect().width()) / 2 + ParentEditorBorderSize - 1;
if (imageType == DragImageType::IncludeVisibleChildren)
{
DrawDragImageAndVisibleChildrenInto(dragPainter, marginWidth, 0);
}
else
{
render(&dragPainter, QPoint(marginWidth, 0));
}
QPen pen;
pen.setColor(QColor(borderColor));
pen.setWidth(1);
dragPainter.setPen(pen);
dragPainter.drawRect(0, 0, imageRect.width() - 1, imageRect.height() - 1);
dragPainter.end();
return dragImage;
}
}
#include "UI/PropertyEditor/moc_PropertyRowWidget.cpp"
@@ -45,6 +45,13 @@ namespace AzToolsFramework
Q_PROPERTY(bool appendDefaultLabelToName READ GetAppendDefaultLabelToName WRITE AppendDefaultLabelToName)
public:
AZ_CLASS_ALLOCATOR(PropertyRowWidget, AZ::SystemAllocator, 0)
enum class DragImageType
{
SingleRow,
IncludeVisibleChildren
};
PropertyRowWidget(QWidget* pParent);
virtual ~PropertyRowWidget();
@@ -86,6 +93,9 @@ namespace AzToolsFramework
bool GetAppendDefaultLabelToName();
void AppendDefaultLabelToName(bool doAppend);
AZ::u32 GetChildRowCount() const;
PropertyRowWidget* GetChildRowByIndex(AZ::u32 index) const;
AZStd::vector<PropertyRowWidget*>& GetChildrenRows() { return m_childrenRows; }
bool HasChildRows() const;
@@ -124,6 +134,7 @@ namespace AzToolsFramework
void SetSelectionEnabled(bool selectionEnabled);
void SetSelected(bool selected);
bool GetSelected();
bool eventFilter(QObject *watched, QEvent *event) override;
void paintEvent(QPaintEvent*) override;
@@ -152,9 +163,18 @@ namespace AzToolsFramework
bool CanChildrenBeReordered() const;
bool CanBeReordered() const;
int GetIndexInParent() const;
bool CanMoveUp() const;
bool CanMoveDown() const;
int GetContainingEditorFrameWidth();
QPixmap createDragImage(const QColor backgroundColor, const QColor borderColor, const float alpha, DragImageType imageType);
protected:
int CalculateLabelWidth() const;
int GetHeightOfRowAndVisibleChildren();
int DrawDragImageAndVisibleChildrenInto(QPainter& painter, int xpos, int ypos);
bool IsHidden(InstanceDataNode* node) const;
struct ChangeNotification;
@@ -216,6 +236,7 @@ namespace AzToolsFramework
bool m_isMultiSizeContainer = false;
bool m_isFixedSizeOrSmartPtrContainer = false;
bool m_custom = false;
bool m_canChildrenBeReordered = false;
bool m_isSelected = false;
bool m_selectionEnabled = false;
@@ -19,6 +19,7 @@
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QScrollArea>
#include <QtWidgets/QApplication>
#include <QPainter>
AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // 'QTextFormat::d': class 'QSharedDataPointer<QTextFormatPrivate>' needs to have dll-interface to be used by clients of class 'QTextFormat'
#include <QtWidgets/QInputDialog>
AZ_POP_DISABLE_WARNING
@@ -1343,7 +1344,7 @@ namespace AzToolsFramework
// calculate the index/offset of the instance data node in the container
// (useful for notifying which element in a vector was modified/removed)
static size_t CalculateElementIndexInContainer(
static int CalculateElementIndexInContainer(
InstanceDataNode* node, void* parentInstanceNode,
AZ::SerializeContext::IDataContainer* container, AZStd::vector<void*>& nodeInstancesOut)
{
@@ -1358,7 +1359,7 @@ namespace AzToolsFramework
}
}
size_t elementIndex = 0;
int elementIndex = 0;
void* elementPtr = nodeInstancesOut.empty() ? nullptr : nodeInstancesOut.front();
// find the index of the element we are about to remove
@@ -1429,7 +1430,7 @@ namespace AzToolsFramework
// if the element being modified exists in a container, calculate
// the index to be passed through to PropertyNotify
const auto calculateElementIndex = [](InstanceDataNode* node) -> size_t {
const auto calculateElementIndex = [](InstanceDataNode* node) -> int {
if (InstanceDataNode* parent = node->GetParent())
{
if (AZ::SerializeContext::IDataContainer* container = parent->GetClassMetadata()->m_container)
@@ -1656,6 +1657,221 @@ namespace AzToolsFramework
AzToolsFramework::Refresh_EntireTree);
}
InstanceDataNode* ReflectedPropertyEditor::FindContainerNodeForNode(InstanceDataNode* node) const
{
// Locate the owning container. There may be a level of indirection due to wrappers, such as DynamicSerializableField.
InstanceDataNode* pContainerNode = node->GetParent();
if (!pContainerNode)
{
return nullptr;
}
while (pContainerNode && !pContainerNode->GetClassMetadata()->m_container)
{
pContainerNode = pContainerNode->GetParent();
node = node->GetParent();
}
// Check for pContainerNode again, can happen if a node is deleted during operation.
if (!pContainerNode)
{
return nullptr;
}
if (IsParentAssociativeContainer(pContainerNode) && IsPairContainer(pContainerNode))
{
// Go up one more level to the associative container, we'll remove the pair from that container
pContainerNode = pContainerNode->GetParent();
node = node->GetParent();
}
AZ_Assert(
pContainerNode, "Failed to locate parent container for element \"%s\" of type %s.",
node->GetElementMetadata() ? node->GetElementMetadata()->m_name : node->GetClassMetadata()->m_name,
node->GetClassMetadata()->m_typeId.ToString<AZStd::string>().c_str());
return pContainerNode;
}
InstanceDataNode* ReflectedPropertyEditor::GetNodeAtIndex(int index)
{
if (index >= m_impl->m_widgetsInDisplayOrder.size())
{
return nullptr;
}
return GetNodeFromWidget(m_impl->m_widgetsInDisplayOrder[index]);
}
QSet<PropertyRowWidget*> ReflectedPropertyEditor::GetTopLevelWidgets()
{
return m_impl->getTopLevelWidgets();
}
void ReflectedPropertyEditor::ChangeNodeIndex(InstanceDataNode* containerNode, InstanceDataNode* node, int fromIndex, int toIndex)
{
auto container = containerNode->GetElementMetadata()
? containerNode->GetElementMetadata()->m_genericClassInfo->GetClassData()->m_container
: nullptr;
if (fromIndex == toIndex)
{
return;
}
if (!container || container->GetAssociativeContainerInterface())
{
return;
}
AZ::Uuid typeId = node->GetClassMetadata()->m_typeId;
if (m_impl->m_ptrNotify)
{
m_impl->m_ptrNotify->BeforePropertyModified(containerNode);
}
const AZ::SerializeContext::ClassElement* containerClassElement = container->GetElement(container->GetDefaultElementNameCrc());
AZ::SerializeContext* serializeContext = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
// Backup the item we're moving.
void* srcElement = nullptr;
void* destElement = nullptr;
int destIndex = -1;
int srcIndex = fromIndex;
srcElement = container->GetElementByIndex(containerNode->GetInstance(0), containerClassElement, srcIndex);
void* tmpBuffer = serializeContext->CloneObject(srcElement, typeId);
// Shuffle all intervening items up (or down).
int indexOffset = (toIndex < fromIndex) ? -1 : 1;
while (destIndex != toIndex - indexOffset)
{
destIndex = srcIndex;
srcIndex += indexOffset;
destElement = srcElement;
srcElement = container->GetElementByIndex(containerNode->GetInstance(0), containerClassElement, srcIndex);
serializeContext->CloneObjectInplace(destElement, srcElement, typeId);
}
// Now replace the final element with the one backed up previously.
destElement = srcElement;
serializeContext->CloneObjectInplace(destElement, tmpBuffer, typeId);
if (m_impl->m_ptrNotify)
{
m_impl->m_ptrNotify->AfterPropertyModified(containerNode);
m_impl->m_ptrNotify->SealUndoStack();
}
// Need to refresh any pinned inspectors as well to keep the container state in sync
QueueInvalidation(Refresh_Values);
AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast(
&AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_Values);
}
void ReflectedPropertyEditor::MoveNodeToIndex(InstanceDataNode* node, int index)
{
InstanceDataNode* pContainerNode = FindContainerNodeForNode(node);
if (!pContainerNode)
{
return;
}
AZ::SerializeContext::IDataContainer* container = pContainerNode->GetClassMetadata()->m_container;
AZStd::vector<void*> nodeInstancesOut;
const int elementIndex = CalculateElementIndexInContainer(node, pContainerNode->GetInstance(0), container, nodeInstancesOut);
ChangeNodeIndex(pContainerNode, node, elementIndex, index);
}
void ReflectedPropertyEditor::MoveNodeBefore(InstanceDataNode* nodeToMove, InstanceDataNode* nodeToMoveBefore)
{
InstanceDataNode* pContainerNode = FindContainerNodeForNode(nodeToMove);
InstanceDataNode* pContainerNodeTarget = FindContainerNodeForNode(nodeToMoveBefore);
if (nodeToMove == nodeToMoveBefore)
{
return;
}
// Can only move nodes within the same parent.
if (pContainerNode != pContainerNodeTarget)
{
return;
}
AZ::SerializeContext::IDataContainer* container = pContainerNode->GetClassMetadata()->m_container;
AZStd::vector<void*> nodeInstancesOut;
int elementIndex = CalculateElementIndexInContainer(nodeToMove, pContainerNode->GetInstance(0), container, nodeInstancesOut);
nodeInstancesOut.clear();
int elementIndexTarget =
CalculateElementIndexInContainer(nodeToMoveBefore, pContainerNode->GetInstance(0), container, nodeInstancesOut);
if (elementIndex < elementIndexTarget)
{
elementIndexTarget -= 1;
}
ChangeNodeIndex(pContainerNode, nodeToMove, elementIndex, elementIndexTarget);
}
void ReflectedPropertyEditor::MoveNodeAfter(InstanceDataNode* nodeToMove, InstanceDataNode* nodeToMoveBefore)
{
InstanceDataNode* pContainerNode = FindContainerNodeForNode(nodeToMove);
InstanceDataNode* pContainerNodeTarget = FindContainerNodeForNode(nodeToMoveBefore);
if (nodeToMove == nodeToMoveBefore)
{
return;
}
// Can only move nodes within the same parent.
if (pContainerNode != pContainerNodeTarget)
{
return;
}
AZ::SerializeContext::IDataContainer* container = pContainerNode->GetClassMetadata()->m_container;
AZStd::vector<void*> nodeInstancesOut;
int elementIndex = CalculateElementIndexInContainer(nodeToMove, pContainerNode->GetInstance(0), container, nodeInstancesOut);
nodeInstancesOut.clear();
int elementIndexTarget =
CalculateElementIndexInContainer(nodeToMoveBefore, pContainerNode->GetInstance(0), container, nodeInstancesOut);
if (elementIndex > elementIndexTarget)
{
elementIndexTarget += 1;
}
ChangeNodeIndex(pContainerNode, nodeToMove, elementIndex, elementIndexTarget);
}
int ReflectedPropertyEditor::GetNodeIndexInContainer(InstanceDataNode* node)
{
InstanceDataNode* pContainerNode = FindContainerNodeForNode(node);
AZ::SerializeContext::IDataContainer* container = pContainerNode->GetClassMetadata()->m_container;
AZStd::vector<void*> nodeInstancesOut;
int elementIndex = CalculateElementIndexInContainer(node, pContainerNode->GetInstance(0), container, nodeInstancesOut);
return elementIndex;
}
void ReflectedPropertyEditor::OnPropertyRowRequestContainerRemoveItem(PropertyRowWidget* widget, InstanceDataNode* node)
{
// Locate the owning container. There may be a level of indirection due to wrappers, such as DynamicSerializableField.
@@ -1690,7 +1906,7 @@ namespace AzToolsFramework
// the index of the element being removed
AZStd::vector<void*> nodeInstancesOut;
const size_t elementIndex = CalculateElementIndexInContainer(
const int elementIndex = CalculateElementIndexInContainer(
node, pContainerNode->GetInstance(0), container, nodeInstancesOut);
// pass the context as the last parameter to actually delete the related data.
@@ -155,9 +155,19 @@ namespace AzToolsFramework
using VisibilityCallback = AZStd::function<void(InstanceDataNode* node, NodeDisplayVisibility& visibility, bool& checkChildVisibility)>;
void SetVisibilityCallback(VisibilityCallback callback);
void MoveNodeToIndex(InstanceDataNode* node, int index);
void MoveNodeBefore(InstanceDataNode* nodeToMove, InstanceDataNode* nodeToMoveBefore);
void MoveNodeAfter(InstanceDataNode* nodeToMove, InstanceDataNode* nodeToMoveBefore);
int GetNodeIndexInContainer(InstanceDataNode* node);
InstanceDataNode* GetNodeAtIndex(int index);
QSet<PropertyRowWidget*> GetTopLevelWidgets();
signals:
void OnExpansionContractionDone();
private:
InstanceDataNode* FindContainerNodeForNode(InstanceDataNode* node) const;
void ChangeNodeIndex(InstanceDataNode* containerNode, InstanceDataNode* node, int oldIndex, int newIndex);
class Impl;
std::unique_ptr<Impl> m_impl;
@@ -27,6 +27,35 @@ using namespace AzToolsFramework;
namespace UnitTest
{
void MousePressAndMove(
QWidget* widget, const QPoint& initialPositionWidget, const QPoint& mouseDelta, const Qt::MouseButton mouseButton)
{
QPoint position = widget->mapToGlobal(initialPositionWidget);
QTest::mousePress(widget, mouseButton, Qt::NoModifier, position);
MouseMove(widget, initialPositionWidget, mouseDelta, mouseButton);
}
// Note: There are a series of bugs in Qt that appear to be preventing mouseMove events
// firing when sent through the QTest framework. This is a work around for our version
// of Qt. In future this can hopefully be simplified. See ^1 for workaround.
// More info: Issues with mouse move in Qt
// - https://bugreports.qt.io/browse/QTBUG-5232
// - https://bugreports.qt.io/browse/QTBUG-69414
// - https://lists.qt-project.org/pipermail/development/2019-July/036873.html
void MouseMove(QWidget* widget, const QPoint& initialPositionWidget, const QPoint& mouseDelta, const Qt::MouseButton mouseButton)
{
QPoint nextPosition = widget->mapToGlobal(initialPositionWidget + mouseDelta);
// ^1 To ensure a mouse move event is fired we must call the test mouse move function
// and also send a mouse move event that matches. Each on their own do not appear to
// work - please see the links above for more context.
QTest::mouseMove(widget, nextPosition);
QMouseEvent mouseMoveEvent(
QEvent::MouseMove, QPointF(nextPosition), QPointF(nextPosition), Qt::NoButton, mouseButton, Qt::NoModifier);
QApplication::sendEvent(widget, &mouseMoveEvent);
}
bool TestWidget::eventFilter(QObject* watched, QEvent* event)
{
AZ_UNUSED(watched);
@@ -59,6 +59,21 @@ namespace UnitTest
{
constexpr AZStd::string_view prefabSystemSetting = "/Amazon/Preferences/EnablePrefabSystem";
/// Performs a mouse press and move event on the provided widget.
/// @param widget The widget to perform the mouse press and move on.
/// @param initialPositionWidget The position of the mouse relative to the widget (will be remapped to a global position internally).
/// @param mouseDelta How far to move the mouse.
/// @param mouseButton The button to be used during the press and move.
void MousePressAndMove(
QWidget* widget, const QPoint& initialPositionWidget, const QPoint& mouseDelta, Qt::MouseButton mouseButton = Qt::LeftButton);
/// Performs a mouse move event on the provided widget.
/// @param widget The widget to perform the mouse move on.
/// @param initialPositionWidget The position of the mouse relative to the widget (will be remapped to a global position internally).
/// @param mouseDelta How far to move the mouse (note: mouseDelta may be zero and the mouse will only be moved to initialPosition).
/// @param mouseButton The button to be held during the move.
void MouseMove(QWidget* widget, const QPoint& initialPosition, const QPoint& mouseDelta, Qt::MouseButton mouseButton = Qt::NoButton);
/// Test widget to store QActions generated by EditorTransformComponentSelection.
class TestWidget : public QWidget
{
@@ -313,7 +313,7 @@ namespace AzToolsFramework
//! Utility function to return EntityContextId.
inline AzFramework::EntityContextId GetEntityContextId()
{
AzFramework::EntityContextId entityContextId;
auto entityContextId = AzFramework::EntityContextId::CreateNull();
EditorEntityContextRequestBus::BroadcastResult(entityContextId, &EditorEntityContextRequests::GetEditorEntityContextId);
return entityContextId;
@@ -60,6 +60,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED)
PUBLIC
AZ::AzTestShared
PRIVATE
3rdParty::Qt::Test
3rdParty::googletest::GMock
3rdParty::GoogleBenchmark
AZ::AzToolsFramework
@@ -76,8 +77,9 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED)
PRIVATE
Tests
BUILD_DEPENDENCIES
PRIVATE
PUBLIC
AZ::AzTestShared
PRIVATE
3rdParty::Qt::Test
AZ::AzFrameworkTestShared
AZ::AzToolsFramework
@@ -107,31 +107,6 @@ namespace UnitTest
EXPECT_THAT(m_doubleSpinBoxWithLineEdit, Ne(nullptr));
}
// Note: There are a series of bugs in Qt that appear to be preventing mouseMove events
// firing when sent through the QTest framework. This is a work around for our version
// of Qt. In future this can hopefully be simplified. See ^1 for workaround.
// More info: Issues with mouse move in Qt
// - https://bugreports.qt.io/browse/QTBUG-5232
// - https://bugreports.qt.io/browse/QTBUG-69414
// - https://lists.qt-project.org/pipermail/development/2019-July/036873.html
void MousePressAndMove(
QWidget* widget, const QPoint& widgetScreenPosition, const QPoint& mouseDelta)
{
QPoint position = widget->mapToGlobal(widgetScreenPosition);
QPoint nextPosition = widget->mapToGlobal(widgetScreenPosition + mouseDelta);
QTest::mousePress(widget, Qt::LeftButton, Qt::NoModifier, position);
// ^1 To ensure a mouse move event is fired we must call the test mouse move function
// and also send a mouse move event that matches. Each on their own do not appear to
// work - please see the links above for more context.
QTest::mouseMove(widget, nextPosition);
QMouseEvent mouseMoveEvent(
QEvent::MouseMove, QPointF(nextPosition), QPointF(nextPosition),
Qt::NoButton, Qt::LeftButton, Qt::NoModifier);
QApplication::sendEvent(widget, &mouseMoveEvent);
}
TEST_F(SpinBoxFixture, SpinBoxMousePressAndMoveRightScrollsValue)
{
m_doubleSpinBox->setValue(10.0);
@@ -7,6 +7,7 @@
*/
#include <unistd.h>
#include <AzCore/std/string/string.h>
namespace GridMate
{
@@ -7,6 +7,7 @@
*/
#include <unistd.h>
#include <AzCore/std/string/string.h>
namespace GridMate
{