QtEditorApplication.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "EditorDefs.h"
  9. #include "QtEditorApplication.h"
  10. // Qt
  11. #include <QAbstractEventDispatcher>
  12. #include <QScopedValueRollback>
  13. #include <QToolBar>
  14. #include <QLoggingCategory>
  15. #include <AzCore/Component/ComponentApplication.h>
  16. #include <AzCore/IO/Path/Path.h>
  17. #include <AzCore/Settings/SettingsRegistryMergeUtils.h>
  18. // AzQtComponents
  19. #include <AzQtComponents/Components/GlobalEventFilter.h>
  20. #include <AzQtComponents/Components/O3DEStylesheet.h>
  21. #include <AzQtComponents/Components/Titlebar.h>
  22. #include <AzQtComponents/Components/WindowDecorationWrapper.h>
  23. // Editor
  24. #include "Settings.h"
  25. #include "CryEdit.h"
  26. Q_LOGGING_CATEGORY(InputDebugging, "o3de.editor.input")
  27. // internal, private namespace:
  28. namespace
  29. {
  30. class EditorGlobalEventFilter
  31. : public AzQtComponents::GlobalEventFilter
  32. {
  33. public:
  34. explicit EditorGlobalEventFilter(QObject* watch)
  35. : AzQtComponents::GlobalEventFilter(watch) {}
  36. bool eventFilter(QObject* obj, QEvent* e) override
  37. {
  38. static bool isRecursing = false;
  39. if (isRecursing)
  40. {
  41. return false;
  42. }
  43. QScopedValueRollback<bool> guard(isRecursing, true);
  44. // Detect Widget move
  45. // We're doing this before the events are actually consumed to avoid confusion
  46. if (IsDragGuardedWidget(obj))
  47. {
  48. switch (e->type())
  49. {
  50. case QEvent::MouseButtonPress:
  51. {
  52. m_widgetDraggedState = WidgetDraggedState::Clicked;
  53. break;
  54. }
  55. case QEvent::Move:
  56. case QEvent::MouseMove:
  57. {
  58. if (m_widgetDraggedState == WidgetDraggedState::Clicked)
  59. {
  60. m_widgetDraggedState = WidgetDraggedState::Dragged;
  61. }
  62. break;
  63. }
  64. }
  65. }
  66. if (e->type() == QEvent::MouseButtonRelease)
  67. {
  68. m_widgetDraggedState = WidgetDraggedState::None;
  69. }
  70. switch (e->type())
  71. {
  72. case QEvent::KeyPress:
  73. case QEvent::KeyRelease:
  74. {
  75. if (GetIEditor()->IsInGameMode())
  76. {
  77. // don't let certain keys fall through to the game when it's running
  78. QKeyEvent* keyEvent = static_cast<QKeyEvent*>(e);
  79. auto key = keyEvent->key();
  80. if ((key == Qt::Key_Alt) || (key == Qt::Key_AltGr) || ((key >= Qt::Key_F1) && (key <= Qt::Key_F35)))
  81. {
  82. return true;
  83. }
  84. }
  85. }
  86. break;
  87. case QEvent::Shortcut:
  88. {
  89. // Eat shortcuts in game mode or when a guarded widget is being dragged
  90. if (GetIEditor()->IsInGameMode() || m_widgetDraggedState == WidgetDraggedState::Dragged)
  91. {
  92. return true;
  93. }
  94. }
  95. break;
  96. case QEvent::MouseButtonPress:
  97. case QEvent::MouseButtonRelease:
  98. case QEvent::MouseButtonDblClick:
  99. case QEvent::MouseMove:
  100. {
  101. #if AZ_TRAIT_OS_PLATFORM_APPLE
  102. auto widget = qobject_cast<QWidget*>(obj);
  103. if (widget && widget->graphicsProxyWidget() != nullptr)
  104. {
  105. QMouseEvent* me = static_cast<QMouseEvent*>(e);
  106. QWidget* target = qApp->widgetAt(QCursor::pos());
  107. if (target)
  108. {
  109. QMouseEvent ev(me->type(), target->mapFromGlobal(QCursor::pos()), me->button(), me->buttons(), me->modifiers());
  110. qApp->notify(target, &ev);
  111. return true;
  112. }
  113. }
  114. #endif
  115. GuardMouseEventSelectionChangeMetrics(e);
  116. }
  117. break;
  118. }
  119. return GlobalEventFilter::eventFilter(obj, e);
  120. }
  121. private:
  122. bool m_mouseButtonWasDown = false;
  123. void GuardMouseEventSelectionChangeMetrics(QEvent* e)
  124. {
  125. // Force the metrics collector to queue up any selection changed metrics until mouse release, so that we don't
  126. // get flooded with multiple selection changed events when one, sent on mouse release, is enough.
  127. if (e->type() == QEvent::MouseButtonPress)
  128. {
  129. if (!m_mouseButtonWasDown)
  130. {
  131. m_mouseButtonWasDown = true;
  132. }
  133. }
  134. else if (e->type() == QEvent::MouseButtonRelease)
  135. {
  136. // This is a tricky case. We don't want to send the end selection change event too early
  137. // because there might be other things responding to the mouse release after this, and we want to
  138. // block handling of the selection change events until we're entirely finished with the mouse press.
  139. // So, queue the handling with a single shot timer, but then check the state of the mouse buttons
  140. // to ensure that they haven't been pressed in between the release and the timer firing off.
  141. QTimer::singleShot(0, this, [this]() {
  142. if (!QApplication::mouseButtons() && m_mouseButtonWasDown)
  143. {
  144. m_mouseButtonWasDown = false;
  145. }
  146. });
  147. }
  148. }
  149. //! Detect if the event's target is a Widget we want to guard from shortcuts while it's being dragged.
  150. //! This function can be easily expanded to handle exceptions.
  151. bool IsDragGuardedWidget(const QObject* obj)
  152. {
  153. return qobject_cast<const QWidget*>(obj) != nullptr;
  154. }
  155. //! Enum to keep track of Widget dragged state
  156. enum class WidgetDraggedState
  157. {
  158. None, //!< No widget is being clicked nor dragged
  159. Clicked, //!< A widget has been clicked on but has not been dragged
  160. Dragged, //!< A widget is being dragged
  161. };
  162. WidgetDraggedState m_widgetDraggedState = WidgetDraggedState::None;
  163. };
  164. static void LogToDebug([[maybe_unused]] QtMsgType Type, [[maybe_unused]] const QMessageLogContext& Context, const QString& message)
  165. {
  166. AZ::Debug::Platform::OutputToDebugger("Qt", message.toUtf8().data());
  167. AZ::Debug::Platform::OutputToDebugger("", "\n");
  168. }
  169. }
  170. namespace Editor
  171. {
  172. void ScanDirectories(QFileInfoList& directoryList, const QStringList& filters, QFileInfoList& files, ScanDirectoriesUpdateCallBack updateCallback)
  173. {
  174. while (!directoryList.isEmpty())
  175. {
  176. QDir directory(directoryList.front().absoluteFilePath(), "*", QDir::Name | QDir::IgnoreCase, QDir::AllEntries);
  177. directoryList.pop_front();
  178. if (directory.exists())
  179. {
  180. // Append each file from this directory that matches one of the filters to files
  181. directory.setNameFilters(filters);
  182. directory.setFilter(QDir::Files);
  183. files.append(directory.entryInfoList());
  184. // Add all of the subdirectories from this directory to the queue to be searched
  185. directory.setNameFilters(QStringList("*"));
  186. directory.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
  187. directoryList.append(directory.entryInfoList());
  188. if (updateCallback)
  189. {
  190. updateCallback();
  191. }
  192. }
  193. }
  194. }
  195. EditorQtApplication::EditorQtApplication(int& argc, char** argv)
  196. : AzQtApplication(argc, argv)
  197. , m_stylesheet(new AzQtComponents::O3DEStylesheet(this))
  198. {
  199. setWindowIcon(QIcon(":/Application/res/o3de_editor.ico"));
  200. // set the default key store for our preferences:
  201. setApplicationName("O3DE Editor");
  202. installEventFilter(this);
  203. // Disable our debugging input helpers by default
  204. QLoggingCategory::setFilterRules(QStringLiteral("o3de.editor.input.*=false"));
  205. // Initialize our stylesheet here to allow Gems to register stylesheets when their system components activate.
  206. AZ::IO::FixedMaxPath engineRootPath;
  207. {
  208. using namespace AZ::SettingsRegistryMergeUtils;
  209. constexpr bool executeRegDumpCommands = false;
  210. AZ::SettingsRegistryImpl settingsRegistry;
  211. AZ::CommandLine commandLine;
  212. commandLine.Parse(argc, argv);
  213. ParseCommandLine(commandLine);
  214. StoreCommandLineToRegistry(settingsRegistry, commandLine);
  215. MergeSettingsToRegistry_CommandLine(settingsRegistry, commandLine, executeRegDumpCommands);
  216. MergeSettingsToRegistry_AddRuntimeFilePaths(settingsRegistry);
  217. settingsRegistry.Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder);
  218. }
  219. m_stylesheet->initialize(this, engineRootPath);
  220. }
  221. void EditorQtApplication::Initialize()
  222. {
  223. GetIEditor()->RegisterNotifyListener(this);
  224. // install QTranslator
  225. InstallEditorTranslators();
  226. // install hooks and filters last and revoke them first
  227. InstallFilters();
  228. // install this filter. It will be a parent of the application and cleaned up when it is cleaned up automically
  229. auto globalEventFilter = new EditorGlobalEventFilter(this);
  230. installEventFilter(globalEventFilter);
  231. }
  232. void EditorQtApplication::LoadSettings()
  233. {
  234. AZ::SerializeContext* context;
  235. AZ::ComponentApplicationBus::BroadcastResult(context, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
  236. AZ_Assert(context, "No serialize context");
  237. char resolvedPath[AZ_MAX_PATH_LEN];
  238. AZ::IO::FileIOBase::GetInstance()->ResolvePath("@user@/EditorUserSettings.xml", resolvedPath, AZ_MAX_PATH_LEN);
  239. m_localUserSettings.Load(resolvedPath, context);
  240. m_localUserSettings.Activate(AZ::UserSettings::CT_LOCAL);
  241. AZ::UserSettingsOwnerRequestBus::Handler::BusConnect(AZ::UserSettings::CT_LOCAL);
  242. m_activatedLocalUserSettings = true;
  243. }
  244. void EditorQtApplication::UnloadSettings()
  245. {
  246. if (m_activatedLocalUserSettings)
  247. {
  248. SaveSettings();
  249. m_localUserSettings.Deactivate();
  250. AZ::UserSettingsOwnerRequestBus::Handler::BusDisconnect();
  251. m_activatedLocalUserSettings = false;
  252. }
  253. }
  254. void EditorQtApplication::SaveSettings()
  255. {
  256. if (m_activatedLocalUserSettings)
  257. {
  258. AZ::SerializeContext* context;
  259. AZ::ComponentApplicationBus::BroadcastResult(context, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
  260. AZ_Assert(context, "No serialize context");
  261. char resolvedPath[AZ_MAX_PATH_LEN];
  262. AZ::IO::FileIOBase::GetInstance()->ResolvePath("@user@/EditorUserSettings.xml", resolvedPath, AZ_ARRAY_SIZE(resolvedPath));
  263. m_localUserSettings.Save(resolvedPath, context);
  264. }
  265. }
  266. void EditorQtApplication::maybeProcessIdle()
  267. {
  268. if (!m_isMovingOrResizing)
  269. {
  270. if (auto winapp = CCryEditApp::instance())
  271. {
  272. winapp->OnIdle(0);
  273. }
  274. }
  275. if (m_applicationActive)
  276. {
  277. QTimer::singleShot(1, this, &EditorQtApplication::maybeProcessIdle);
  278. }
  279. }
  280. void EditorQtApplication::InstallQtLogHandler()
  281. {
  282. qInstallMessageHandler(LogToDebug);
  283. }
  284. void EditorQtApplication::InstallFilters()
  285. {
  286. if (auto dispatcher = QAbstractEventDispatcher::instance())
  287. {
  288. dispatcher->installNativeEventFilter(this);
  289. }
  290. }
  291. void EditorQtApplication::UninstallFilters()
  292. {
  293. if (auto dispatcher = QAbstractEventDispatcher::instance())
  294. {
  295. dispatcher->removeNativeEventFilter(this);
  296. }
  297. }
  298. EditorQtApplication::~EditorQtApplication()
  299. {
  300. if (GetIEditor())
  301. {
  302. GetIEditor()->UnregisterNotifyListener(this);
  303. }
  304. UninstallFilters();
  305. UninstallEditorTranslators();
  306. }
  307. EditorQtApplication* EditorQtApplication::instance()
  308. {
  309. return static_cast<EditorQtApplication*>(QApplication::instance());
  310. }
  311. void EditorQtApplication::OnEditorNotifyEvent(EEditorNotifyEvent event)
  312. {
  313. switch (event)
  314. {
  315. case eNotify_OnStyleChanged:
  316. RefreshStyleSheet();
  317. emit skinChanged();
  318. break;
  319. case eNotify_OnQuit:
  320. GetIEditor()->UnregisterNotifyListener(this);
  321. break;
  322. }
  323. }
  324. QColor EditorQtApplication::InterpolateColors(QColor a, QColor b, float factor)
  325. {
  326. return QColor(int(a.red() * (1.0f - factor) + b.red() * factor),
  327. int(a.green() * (1.0f - factor) + b.green() * factor),
  328. int(a.blue() * (1.0f - factor) + b.blue() * factor),
  329. int(a.alpha() * (1.0f - factor) + b.alpha() * factor));
  330. }
  331. void EditorQtApplication::RefreshStyleSheet()
  332. {
  333. m_stylesheet->Refresh();
  334. }
  335. void EditorQtApplication::setIsMovingOrResizing(bool isMovingOrResizing)
  336. {
  337. if (m_isMovingOrResizing == isMovingOrResizing)
  338. {
  339. return;
  340. }
  341. m_isMovingOrResizing = isMovingOrResizing;
  342. }
  343. bool EditorQtApplication::isMovingOrResizing() const
  344. {
  345. return m_isMovingOrResizing;
  346. }
  347. const QColor& EditorQtApplication::GetColorByName(const QString& name)
  348. {
  349. return m_stylesheet->GetColorByName(name);
  350. }
  351. bool EditorQtApplication::IsActive()
  352. {
  353. return applicationState() == Qt::ApplicationActive;
  354. }
  355. QTranslator* EditorQtApplication::CreateAndInitializeTranslator(const QString& filename, const QString& directory)
  356. {
  357. Q_ASSERT(QFile::exists(directory + "/" + filename));
  358. QTranslator* translator = new QTranslator();
  359. translator->load(filename, directory);
  360. installTranslator(translator);
  361. return translator;
  362. }
  363. void EditorQtApplication::InstallEditorTranslators()
  364. {
  365. m_editorTranslator = CreateAndInitializeTranslator("editor_en-us.qm", ":/Translations");
  366. m_assetBrowserTranslator = CreateAndInitializeTranslator("assetbrowser_en-us.qm", ":/Translations");
  367. }
  368. void EditorQtApplication::DeleteTranslator(QTranslator*& translator)
  369. {
  370. removeTranslator(translator);
  371. delete translator;
  372. translator = nullptr;
  373. }
  374. void EditorQtApplication::UninstallEditorTranslators()
  375. {
  376. DeleteTranslator(m_editorTranslator);
  377. DeleteTranslator(m_assetBrowserTranslator);
  378. }
  379. void EditorQtApplication::EnableOnIdle(bool enable)
  380. {
  381. m_applicationActive = enable;
  382. if (enable)
  383. {
  384. QTimer::singleShot(0, this, &EditorQtApplication::maybeProcessIdle);
  385. }
  386. }
  387. bool EditorQtApplication::OnIdleEnabled() const
  388. {
  389. return m_applicationActive;
  390. }
  391. bool EditorQtApplication::eventFilter(QObject* object, QEvent* event)
  392. {
  393. switch (event->type())
  394. {
  395. case QEvent::MouseButtonPress:
  396. m_pressedButtons |= reinterpret_cast<QMouseEvent*>(event)->button();
  397. break;
  398. case QEvent::MouseButtonRelease:
  399. m_pressedButtons &= ~(reinterpret_cast<QMouseEvent*>(event)->button());
  400. break;
  401. case QEvent::KeyPress:
  402. m_pressedKeys.insert(reinterpret_cast<QKeyEvent*>(event)->key());
  403. break;
  404. case QEvent::KeyRelease:
  405. m_pressedKeys.remove(reinterpret_cast<QKeyEvent*>(event)->key());
  406. break;
  407. default:
  408. break;
  409. }
  410. return QApplication::eventFilter(object, event);
  411. }
  412. } // end namespace Editor
  413. #include <Core/moc_QtEditorApplication.cpp>