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. AZ::SettingsRegistryImpl settingsRegistry;
  210. AZ::CommandLine commandLine;
  211. commandLine.Parse(argc, argv);
  212. ParseCommandLine(commandLine);
  213. StoreCommandLineToRegistry(settingsRegistry, commandLine);
  214. MergeSettingsToRegistry_CommandLine(settingsRegistry, commandLine, {});
  215. MergeSettingsToRegistry_AddRuntimeFilePaths(settingsRegistry);
  216. settingsRegistry.Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder);
  217. }
  218. m_stylesheet->initialize(this, engineRootPath);
  219. }
  220. void EditorQtApplication::Initialize()
  221. {
  222. GetIEditor()->RegisterNotifyListener(this);
  223. // install QTranslator
  224. InstallEditorTranslators();
  225. // install hooks and filters last and revoke them first
  226. InstallFilters();
  227. // install this filter. It will be a parent of the application and cleaned up when it is cleaned up automically
  228. auto globalEventFilter = new EditorGlobalEventFilter(this);
  229. installEventFilter(globalEventFilter);
  230. }
  231. void EditorQtApplication::LoadSettings()
  232. {
  233. AZ::SerializeContext* context;
  234. AZ::ComponentApplicationBus::BroadcastResult(context, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
  235. AZ_Assert(context, "No serialize context");
  236. char resolvedPath[AZ_MAX_PATH_LEN];
  237. AZ::IO::FileIOBase::GetInstance()->ResolvePath("@user@/EditorUserSettings.xml", resolvedPath, AZ_MAX_PATH_LEN);
  238. m_localUserSettings.Load(resolvedPath, context);
  239. m_localUserSettings.Activate(AZ::UserSettings::CT_LOCAL);
  240. AZ::UserSettingsOwnerRequestBus::Handler::BusConnect(AZ::UserSettings::CT_LOCAL);
  241. m_activatedLocalUserSettings = true;
  242. }
  243. void EditorQtApplication::UnloadSettings()
  244. {
  245. if (m_activatedLocalUserSettings)
  246. {
  247. SaveSettings();
  248. m_localUserSettings.Deactivate();
  249. AZ::UserSettingsOwnerRequestBus::Handler::BusDisconnect();
  250. m_activatedLocalUserSettings = false;
  251. }
  252. }
  253. void EditorQtApplication::SaveSettings()
  254. {
  255. if (m_activatedLocalUserSettings)
  256. {
  257. AZ::SerializeContext* context;
  258. AZ::ComponentApplicationBus::BroadcastResult(context, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
  259. AZ_Assert(context, "No serialize context");
  260. char resolvedPath[AZ_MAX_PATH_LEN];
  261. AZ::IO::FileIOBase::GetInstance()->ResolvePath("@user@/EditorUserSettings.xml", resolvedPath, AZ_ARRAY_SIZE(resolvedPath));
  262. m_localUserSettings.Save(resolvedPath, context);
  263. }
  264. }
  265. void EditorQtApplication::maybeProcessIdle()
  266. {
  267. if (!m_isMovingOrResizing)
  268. {
  269. if (auto winapp = CCryEditApp::instance())
  270. {
  271. winapp->OnIdle(0);
  272. }
  273. }
  274. if (m_applicationActive)
  275. {
  276. QTimer::singleShot(1, this, &EditorQtApplication::maybeProcessIdle);
  277. }
  278. }
  279. void EditorQtApplication::InstallQtLogHandler()
  280. {
  281. qInstallMessageHandler(LogToDebug);
  282. }
  283. void EditorQtApplication::InstallFilters()
  284. {
  285. if (auto dispatcher = QAbstractEventDispatcher::instance())
  286. {
  287. dispatcher->installNativeEventFilter(this);
  288. }
  289. }
  290. void EditorQtApplication::UninstallFilters()
  291. {
  292. if (auto dispatcher = QAbstractEventDispatcher::instance())
  293. {
  294. dispatcher->removeNativeEventFilter(this);
  295. }
  296. }
  297. EditorQtApplication::~EditorQtApplication()
  298. {
  299. if (GetIEditor())
  300. {
  301. GetIEditor()->UnregisterNotifyListener(this);
  302. }
  303. UninstallFilters();
  304. UninstallEditorTranslators();
  305. }
  306. EditorQtApplication* EditorQtApplication::instance()
  307. {
  308. return static_cast<EditorQtApplication*>(QApplication::instance());
  309. }
  310. void EditorQtApplication::OnEditorNotifyEvent(EEditorNotifyEvent event)
  311. {
  312. switch (event)
  313. {
  314. case eNotify_OnStyleChanged:
  315. RefreshStyleSheet();
  316. emit skinChanged();
  317. break;
  318. case eNotify_OnQuit:
  319. GetIEditor()->UnregisterNotifyListener(this);
  320. break;
  321. }
  322. }
  323. QColor EditorQtApplication::InterpolateColors(QColor a, QColor b, float factor)
  324. {
  325. return QColor(int(a.red() * (1.0f - factor) + b.red() * factor),
  326. int(a.green() * (1.0f - factor) + b.green() * factor),
  327. int(a.blue() * (1.0f - factor) + b.blue() * factor),
  328. int(a.alpha() * (1.0f - factor) + b.alpha() * factor));
  329. }
  330. void EditorQtApplication::RefreshStyleSheet()
  331. {
  332. m_stylesheet->Refresh();
  333. }
  334. void EditorQtApplication::setIsMovingOrResizing(bool isMovingOrResizing)
  335. {
  336. if (m_isMovingOrResizing == isMovingOrResizing)
  337. {
  338. return;
  339. }
  340. m_isMovingOrResizing = isMovingOrResizing;
  341. }
  342. bool EditorQtApplication::isMovingOrResizing() const
  343. {
  344. return m_isMovingOrResizing;
  345. }
  346. const QColor& EditorQtApplication::GetColorByName(const QString& name)
  347. {
  348. return m_stylesheet->GetColorByName(name);
  349. }
  350. bool EditorQtApplication::IsActive()
  351. {
  352. return applicationState() == Qt::ApplicationActive;
  353. }
  354. QTranslator* EditorQtApplication::CreateAndInitializeTranslator(const QString& filename, const QString& directory)
  355. {
  356. Q_ASSERT(QFile::exists(directory + "/" + filename));
  357. QTranslator* translator = new QTranslator();
  358. translator->load(filename, directory);
  359. installTranslator(translator);
  360. return translator;
  361. }
  362. void EditorQtApplication::InstallEditorTranslators()
  363. {
  364. m_editorTranslator = CreateAndInitializeTranslator("editor_en-us.qm", ":/Translations");
  365. m_assetBrowserTranslator = CreateAndInitializeTranslator("assetbrowser_en-us.qm", ":/Translations");
  366. }
  367. void EditorQtApplication::DeleteTranslator(QTranslator*& translator)
  368. {
  369. removeTranslator(translator);
  370. delete translator;
  371. translator = nullptr;
  372. }
  373. void EditorQtApplication::UninstallEditorTranslators()
  374. {
  375. DeleteTranslator(m_editorTranslator);
  376. DeleteTranslator(m_assetBrowserTranslator);
  377. }
  378. void EditorQtApplication::EnableOnIdle(bool enable)
  379. {
  380. m_applicationActive = enable;
  381. if (enable)
  382. {
  383. QTimer::singleShot(0, this, &EditorQtApplication::maybeProcessIdle);
  384. }
  385. }
  386. bool EditorQtApplication::OnIdleEnabled() const
  387. {
  388. return m_applicationActive;
  389. }
  390. bool EditorQtApplication::eventFilter(QObject* object, QEvent* event)
  391. {
  392. switch (event->type())
  393. {
  394. case QEvent::MouseButtonPress:
  395. m_pressedButtons |= reinterpret_cast<QMouseEvent*>(event)->button();
  396. break;
  397. case QEvent::MouseButtonRelease:
  398. m_pressedButtons &= ~(reinterpret_cast<QMouseEvent*>(event)->button());
  399. break;
  400. case QEvent::KeyPress:
  401. m_pressedKeys.insert(reinterpret_cast<QKeyEvent*>(event)->key());
  402. break;
  403. case QEvent::KeyRelease:
  404. m_pressedKeys.remove(reinterpret_cast<QKeyEvent*>(event)->key());
  405. break;
  406. default:
  407. break;
  408. }
  409. return QApplication::eventFilter(object, event);
  410. }
  411. } // end namespace Editor
  412. #include <Core/moc_QtEditorApplication.cpp>