2
0

CryEdit.cpp 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411
  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. #ifdef WIN32
  10. AZ_PUSH_DISABLE_WARNING(4458, "-Wunknown-warning-option")
  11. #include <Propidl.h>
  12. #include <gdiplus.h>
  13. AZ_POP_DISABLE_WARNING
  14. #pragma comment (lib, "Gdiplus.lib")
  15. #include <WinUser.h> // needed for MessageBoxW in the assert handler
  16. #endif
  17. #include <array>
  18. #include <string>
  19. #include <iostream>
  20. #include <fstream>
  21. #include "CryEdit.h"
  22. // Qt
  23. #include <QCommandLineParser>
  24. #include <QSharedMemory>
  25. #include <QSystemSemaphore>
  26. #include <QDesktopServices>
  27. #include <QElapsedTimer>
  28. #include <QProcess>
  29. #include <QScopedValueRollback>
  30. #include <QClipboard>
  31. #include <QMenuBar>
  32. #include <QMessageBox>
  33. #include <QDialogButtonBox>
  34. #include <QUrlQuery>
  35. // AzCore
  36. #include <AzCore/Casting/numeric_cast.h>
  37. #include <AzCore/Component/ComponentApplicationBus.h>
  38. #include <AzCore/Component/ComponentApplicationLifecycle.h>
  39. #include <AzCore/Module/Environment.h>
  40. #include <AzCore/RTTI/BehaviorContext.h>
  41. #include <AzCore/std/smart_ptr/make_shared.h>
  42. #include <AzCore/Settings/SettingsRegistryMergeUtils.h>
  43. #include <AzCore/StringFunc/StringFunc.h>
  44. #include <AzCore/Utils/Utils.h>
  45. #include <AzCore/Console/IConsole.h>
  46. #include <AzCore/EBus/IEventScheduler.h>
  47. #include <AzCore/Name/Name.h>
  48. #include <AzCore/IO/SystemFile.h>
  49. // AzFramework
  50. #include <AzFramework/Components/CameraBus.h>
  51. #include <AzFramework/Process/ProcessWatcher.h>
  52. #include <AzFramework/ProjectManager/ProjectManager.h>
  53. #include <AzFramework/Spawnable/RootSpawnableInterface.h>
  54. // AzToolsFramework
  55. #include <AzToolsFramework/ActionManager/ActionManagerSystemComponent.h>
  56. #include <AzToolsFramework/Component/EditorComponentAPIBus.h>
  57. #include <AzToolsFramework/Component/EditorLevelComponentAPIBus.h>
  58. #include <AzToolsFramework/Editor/ActionManagerUtils.h>
  59. #include <AzToolsFramework/UI/UICore/ProgressShield.hxx>
  60. #include <AzToolsFramework/UI/UICore/WidgetHelpers.h>
  61. #include <AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.h>
  62. #include <AzToolsFramework/API/EditorPythonConsoleBus.h>
  63. #include <AzToolsFramework/API/EditorPythonRunnerRequestsBus.h>
  64. #include <AzToolsFramework/API/ToolsApplicationAPI.h>
  65. #include <AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h>
  66. #include <AzToolsFramework/PythonTerminal/ScriptHelpDialog.h>
  67. #include <AzToolsFramework/Viewport/LocalViewBookmarkLoader.h>
  68. // AzQtComponents
  69. #include <AzQtComponents/Components/StyleManager.h>
  70. #include <AzQtComponents/Utilities/HandleDpiAwareness.h>
  71. #include <AzQtComponents/Components/WindowDecorationWrapper.h>
  72. #include <AzQtComponents/Utilities/QtPluginPaths.h>
  73. // CryCommon
  74. #include <CryCommon/ILevelSystem.h>
  75. // Editor
  76. #include "Settings.h"
  77. #include "MainWindow.h"
  78. #include "Core/QtEditorApplication.h"
  79. #include "NewLevelDialog.h"
  80. #include "LayoutConfigDialog.h"
  81. #include "ViewManager.h"
  82. #include "FileTypeUtils.h"
  83. #include "PluginManager.h"
  84. #include "IEditorImpl.h"
  85. #include "StartupLogoDialog.h"
  86. #include "DisplaySettings.h"
  87. #include "GameEngine.h"
  88. #include "StartupTraceHandler.h"
  89. #include "ToolsConfigPage.h"
  90. #include "WaitProgress.h"
  91. #include "ToolBox.h"
  92. #include "EditorPreferencesDialog.h"
  93. #include "AnimationContext.h"
  94. #include "GotoPositionDlg.h"
  95. #include "ConsoleDialog.h"
  96. #include "Controls/ConsoleSCB.h"
  97. #include "ScopedVariableSetter.h"
  98. #include "Util/3DConnexionDriver.h"
  99. #include "Util/AutoDirectoryRestoreFileDialog.h"
  100. #include "Util/EditorAutoLevelLoadTest.h"
  101. #include <AzToolsFramework/PythonTerminal/ScriptHelpDialog.h>
  102. #include "LevelFileDialog.h"
  103. #include "LevelIndependentFileMan.h"
  104. #include "WelcomeScreen/WelcomeScreenDialog.h"
  105. #include "Controls/ReflectedPropertyControl/PropertyCtrl.h"
  106. #include "Controls/ReflectedPropertyControl/ReflectedVar.h"
  107. #include "EditorToolsApplication.h"
  108. #include <AzToolsFramework/Undo/UndoSystem.h>
  109. #if defined(AZ_PLATFORM_WINDOWS)
  110. #include <AzFramework/API/ApplicationAPI_Platform.h>
  111. #endif
  112. #if AZ_TRAIT_OS_PLATFORM_APPLE
  113. #include "WindowObserver_mac.h"
  114. #endif
  115. #include <AzCore/RTTI/BehaviorContext.h>
  116. #include <AzFramework/Render/Intersector.h>
  117. #include <AzCore/std/smart_ptr/make_shared.h>
  118. static const char O3DEEditorClassName[] = "O3DEEditorClass";
  119. static const char O3DEApplicationName[] = "O3DEApplication";
  120. static AZ::EnvironmentVariable<bool> inEditorBatchMode = nullptr;
  121. namespace Platform
  122. {
  123. bool OpenUri(const QUrl& uri);
  124. }
  125. RecentFileList::RecentFileList()
  126. {
  127. m_settings.beginGroup(QStringLiteral("Application"));
  128. m_settings.beginGroup(QStringLiteral("Recent File List"));
  129. ReadList();
  130. }
  131. void RecentFileList::Remove(int index)
  132. {
  133. m_arrNames.removeAt(index);
  134. }
  135. void RecentFileList::Add(const QString& f)
  136. {
  137. QString filename = QDir::toNativeSeparators(f);
  138. m_arrNames.removeAll(filename);
  139. m_arrNames.push_front(filename);
  140. while (m_arrNames.count() > Max)
  141. {
  142. m_arrNames.removeAt(Max);
  143. }
  144. }
  145. int RecentFileList::GetSize()
  146. {
  147. return m_arrNames.count();
  148. }
  149. void RecentFileList::GetDisplayName(QString& name, int index, const QString& curDir)
  150. {
  151. name = m_arrNames[index];
  152. const QDir cur(curDir);
  153. QDir fileDir(name); // actually pointing at file, first cdUp() gets us the parent dir
  154. while (fileDir.cdUp())
  155. {
  156. if (fileDir == cur)
  157. {
  158. name = cur.relativeFilePath(name);
  159. break;
  160. }
  161. }
  162. name = QDir::toNativeSeparators(name);
  163. }
  164. QString& RecentFileList::operator[](int index)
  165. {
  166. return m_arrNames[index];
  167. }
  168. void RecentFileList::ReadList()
  169. {
  170. m_arrNames.clear();
  171. for (int i = 1; i <= Max; ++i)
  172. {
  173. QString f = m_settings.value(QStringLiteral("File%1").arg(i)).toString();
  174. if (!f.isEmpty())
  175. {
  176. m_arrNames.push_back(f);
  177. }
  178. }
  179. }
  180. void RecentFileList::WriteList()
  181. {
  182. m_settings.remove(QString());
  183. int i = 1;
  184. for (auto f : m_arrNames)
  185. {
  186. m_settings.setValue(QStringLiteral("File%1").arg(i++), f);
  187. }
  188. }
  189. #define ERROR_LEN 256
  190. CCryDocManager::CCryDocManager()
  191. {
  192. }
  193. CCrySingleDocTemplate* CCryDocManager::SetDefaultTemplate(CCrySingleDocTemplate* pNew)
  194. {
  195. CCrySingleDocTemplate* pOld = m_pDefTemplate;
  196. m_pDefTemplate = pNew;
  197. m_templateList.clear();
  198. m_templateList.push_back(m_pDefTemplate);
  199. return pOld;
  200. }
  201. // Copied from MFC to get rid of the silly ugly unoverridable doc-type pick dialog
  202. void CCryDocManager::OnFileNew()
  203. {
  204. assert(m_pDefTemplate != nullptr);
  205. m_pDefTemplate->OpenDocumentFile(nullptr);
  206. // if returns NULL, the user has already been alerted
  207. }
  208. bool CCryDocManager::DoPromptFileName(QString& fileName, [[maybe_unused]] UINT nIDSTitle,
  209. [[maybe_unused]] DWORD lFlags, bool bOpenFileDialog, [[maybe_unused]] CDocTemplate* pTemplate)
  210. {
  211. CLevelFileDialog levelFileDialog(bOpenFileDialog);
  212. levelFileDialog.show();
  213. levelFileDialog.adjustSize();
  214. if (levelFileDialog.exec() == QDialog::Accepted)
  215. {
  216. fileName = levelFileDialog.GetFileName();
  217. return true;
  218. }
  219. return false;
  220. }
  221. CCryEditDoc* CCryDocManager::OpenDocumentFile(const char* filename, bool addToMostRecentFileList, COpenSameLevelOptions openSameLevelOptions)
  222. {
  223. assert(filename != nullptr);
  224. const bool reopenIfSame = openSameLevelOptions == COpenSameLevelOptions::ReopenLevelIfSame;
  225. // find the highest confidence
  226. auto pos = m_templateList.begin();
  227. CCrySingleDocTemplate::Confidence bestMatch = CCrySingleDocTemplate::noAttempt;
  228. CCrySingleDocTemplate* pBestTemplate = nullptr;
  229. CCryEditDoc* pOpenDocument = nullptr;
  230. if (filename[0] == '\"')
  231. {
  232. ++filename;
  233. }
  234. QString szPath = QString::fromUtf8(filename);
  235. if (szPath.endsWith('"'))
  236. {
  237. szPath.remove(szPath.length() - 1, 1);
  238. }
  239. while (pos != m_templateList.end())
  240. {
  241. auto pTemplate = *(pos++);
  242. CCrySingleDocTemplate::Confidence match;
  243. assert(pOpenDocument == nullptr);
  244. match = pTemplate->MatchDocType(szPath.toUtf8().data(), pOpenDocument);
  245. if (match > bestMatch)
  246. {
  247. bestMatch = match;
  248. pBestTemplate = pTemplate;
  249. }
  250. if (match == CCrySingleDocTemplate::yesAlreadyOpen)
  251. {
  252. break; // stop here
  253. }
  254. }
  255. if (!reopenIfSame && pOpenDocument != nullptr)
  256. {
  257. return pOpenDocument;
  258. }
  259. if (pBestTemplate == nullptr)
  260. {
  261. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Failed to open document."));
  262. return nullptr;
  263. }
  264. return pBestTemplate->OpenDocumentFile(szPath.toUtf8().data(), addToMostRecentFileList, false);
  265. }
  266. //////////////////////////////////////////////////////////////////////////////
  267. // CCryEditApp
  268. #undef ON_COMMAND
  269. #define ON_COMMAND(id, method) \
  270. MainWindow::instance()->GetActionManager()->RegisterActionHandler(id, this, &CCryEditApp::method);
  271. #undef ON_COMMAND_RANGE
  272. #define ON_COMMAND_RANGE(idStart, idEnd, method) \
  273. for (int i = idStart; i <= idEnd; ++i) \
  274. ON_COMMAND(i, method);
  275. AZ_CVAR_EXTERNED(bool, ed_previewGameInFullscreen_once);
  276. CCryEditApp* CCryEditApp::s_currentInstance = nullptr;
  277. /////////////////////////////////////////////////////////////////////////////
  278. // CCryEditApp construction
  279. CCryEditApp::CCryEditApp()
  280. {
  281. s_currentInstance = this;
  282. m_sPreviewFile[0] = 0;
  283. AzFramework::AssetSystemInfoBus::Handler::BusConnect();
  284. AzFramework::AssetSystemStatusBus::Handler::BusConnect();
  285. m_disableIdleProcessingCounter = 0;
  286. EditorIdleProcessingBus::Handler::BusConnect();
  287. }
  288. //////////////////////////////////////////////////////////////////////////
  289. CCryEditApp::~CCryEditApp()
  290. {
  291. EditorIdleProcessingBus::Handler::BusDisconnect();
  292. AzFramework::AssetSystemStatusBus::Handler::BusDisconnect();
  293. AzFramework::AssetSystemInfoBus::Handler::BusDisconnect();
  294. s_currentInstance = nullptr;
  295. }
  296. CCryEditApp* CCryEditApp::instance()
  297. {
  298. return s_currentInstance;
  299. }
  300. class CEditCommandLineInfo
  301. {
  302. public:
  303. bool m_bTest = false;
  304. bool m_bAutoLoadLevel = false;
  305. bool m_bConsoleMode = false;
  306. bool m_bNullRenderer = false;
  307. bool m_bDeveloperMode = false;
  308. bool m_bRunPythonScript = false;
  309. bool m_bRunPythonTestScript = false;
  310. bool m_bShowVersionInfo = false;
  311. QString m_strFileName;
  312. QString m_appRoot;
  313. QString m_logFile;
  314. QString m_pythonArgs;
  315. QString m_pythonTestCase;
  316. QString m_execFile;
  317. QString m_execLineCmd;
  318. bool m_bSkipWelcomeScreenDialog = false;
  319. bool m_bAutotestMode = false;
  320. struct CommandLineStringOption
  321. {
  322. QString name;
  323. QString description;
  324. QString valueName;
  325. };
  326. CEditCommandLineInfo()
  327. {
  328. bool dummy;
  329. QCommandLineParser parser;
  330. parser.addHelpOption();
  331. parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
  332. parser.setApplicationDescription(QObject::tr("O3DE Editor"));
  333. // nsDocumentRevisionDebugMode is an argument that the macOS system passed into an App bundle that is being debugged.
  334. // Need to include it here so that Qt argument parser does not error out.
  335. bool nsDocumentRevisionsDebugMode = false;
  336. const std::vector<std::pair<QString, bool&> > options = {
  337. { "test", m_bTest },
  338. { "auto_level_load", m_bAutoLoadLevel },
  339. { "BatchMode", m_bConsoleMode },
  340. { "NullRenderer", m_bNullRenderer },
  341. { "devmode", m_bDeveloperMode },
  342. { "runpython", m_bRunPythonScript },
  343. { "runpythontest", m_bRunPythonTestScript },
  344. { "version", m_bShowVersionInfo },
  345. { "NSDocumentRevisionsDebugMode", nsDocumentRevisionsDebugMode},
  346. { "skipWelcomeScreenDialog", m_bSkipWelcomeScreenDialog},
  347. { "autotest_mode", m_bAutotestMode},
  348. { "regdumpall", dummy },
  349. { "attach-debugger", dummy }, // Attaches a debugger for the current application
  350. { "wait-for-debugger", dummy }, // Waits until a debugger is attached to the current application
  351. };
  352. QString dummyString;
  353. const std::vector<std::pair<CommandLineStringOption, QString&> > stringOptions = {
  354. {{"logfile", "File name of the log file to write out to.", "logfile"}, m_logFile},
  355. {{"runpythonargs", "Command-line argument string to pass to the python script if --runpython or --runpythontest was used.", "runpythonargs"}, m_pythonArgs},
  356. {{"pythontestcase", "Test case name of python test script if --runpythontest was used.", "pythontestcase"}, m_pythonTestCase},
  357. {{"exec", "cfg file to run on startup, used for systems like automation", "exec"}, m_execFile},
  358. {{"rhi", "Command-line argument to force which rhi to use", "rhi"}, dummyString },
  359. {{"rhi-device-validation", "Command-line argument to configure rhi validation", "rhi-device-validation"}, dummyString },
  360. {{"exec_line", "command to run on startup, used for systems like automation", "exec_line"}, m_execLineCmd},
  361. {{"regset", "Command-line argument to override settings registry values", "regset"}, dummyString},
  362. {{"regremove", "Deletes a value within the global settings registry at the JSON pointer path @key", "regremove"}, dummyString},
  363. {{"regdump", "Sets a value within the global settings registry at the JSON pointer path @key with value of @value", "regdump"}, dummyString},
  364. {{"project-path", "Supplies the path to the project that the Editor should use", "project-path"}, dummyString},
  365. {{"engine-path", "Supplies the path to the engine", "engine-path"}, dummyString},
  366. {{"project-cache-path", "Path to the project cache", "project-cache-path"}, dummyString},
  367. {{"project-user-path", "Path to the project user path", "project-user-path"}, dummyString},
  368. {{"project-log-path", "Path to the project log path", "project-log-path"}, dummyString}
  369. // add dummy entries here to prevent QCommandLineParser error-ing out on cmd line args that will be parsed later
  370. };
  371. parser.addPositionalArgument("file", QCoreApplication::translate("main", "file to open"));
  372. for (const auto& option : options)
  373. {
  374. parser.addOption(QCommandLineOption(option.first));
  375. }
  376. for (const auto& option : stringOptions)
  377. {
  378. parser.addOption(QCommandLineOption(option.first.name, option.first.description, option.first.valueName));
  379. }
  380. QStringList args = qApp->arguments();
  381. #ifdef Q_OS_WIN32
  382. for (QString& arg : args)
  383. {
  384. if (!arg.isEmpty() && arg[0] == '/')
  385. {
  386. arg[0] = '-'; // QCommandLineParser only supports - and -- prefixes
  387. }
  388. }
  389. #endif
  390. if (!parser.parse(args))
  391. {
  392. AZ_TracePrintf("QT CommandLine Parser", "QT command line parsing warned with message %s."
  393. " Has the QCommandLineParser had these options added to it", parser.errorText().toUtf8().constData());
  394. }
  395. // Get boolean options
  396. const int numOptions = static_cast<int>(options.size());
  397. for (int i = 0; i < numOptions; ++i)
  398. {
  399. options[i].second = parser.isSet(options[i].first);
  400. }
  401. // Get string options
  402. for (auto& option : stringOptions)
  403. {
  404. option.second = parser.value(option.first.valueName);
  405. }
  406. const QStringList positionalArgs = parser.positionalArguments();
  407. if (!positionalArgs.isEmpty())
  408. {
  409. m_strFileName = positionalArgs.first();
  410. }
  411. }
  412. };
  413. struct SharedData
  414. {
  415. bool raise = false;
  416. char text[_MAX_PATH];
  417. };
  418. /////////////////////////////////////////////////////////////////////////////
  419. // CTheApp::FirstInstance
  420. // FirstInstance checks for an existing instance of the application.
  421. // If one is found, it is activated.
  422. //
  423. // This function uses a technique similar to that described in KB
  424. // article Q141752 to locate the previous instance of the application. .
  425. bool CCryEditApp::FirstInstance(bool bForceNewInstance)
  426. {
  427. QSystemSemaphore sem(QString(O3DEApplicationName) + "_sem", 1);
  428. sem.acquire();
  429. {
  430. FixDanglingSharedMemory(O3DEEditorClassName);
  431. }
  432. sem.release();
  433. m_mutexApplication = new QSharedMemory(O3DEEditorClassName);
  434. if (!m_mutexApplication->create(sizeof(SharedData)) && !bForceNewInstance)
  435. {
  436. m_mutexApplication->attach();
  437. // another instance is already running - activate it
  438. sem.acquire();
  439. SharedData* data = reinterpret_cast<SharedData*>(m_mutexApplication->data());
  440. data->raise = true;
  441. if (m_bPreviewMode)
  442. {
  443. // IF in preview mode send this window copy data message to load new preview file.
  444. azstrcpy(data->text, MAX_PATH, m_sPreviewFile);
  445. }
  446. return false;
  447. }
  448. else
  449. {
  450. m_mutexApplication->attach();
  451. // this is the first instance
  452. sem.acquire();
  453. ::memset(m_mutexApplication->data(), 0, m_mutexApplication->size());
  454. sem.release();
  455. QTimer* t = new QTimer(this);
  456. connect(t, &QTimer::timeout, this, [this]() {
  457. QSystemSemaphore sem(QString(O3DEApplicationName) + "_sem", 1);
  458. sem.acquire();
  459. SharedData* data = reinterpret_cast<SharedData*>(m_mutexApplication->data());
  460. QString preview = QString::fromLatin1(data->text);
  461. if (data->raise)
  462. {
  463. QWidget* w = MainWindow::instance();
  464. w->setWindowState((w->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
  465. w->raise();
  466. w->activateWindow();
  467. data->raise = false;
  468. }
  469. if (!preview.isEmpty())
  470. {
  471. // Load this file
  472. LoadFile(preview);
  473. data->text[0] = 0;
  474. }
  475. sem.release();
  476. });
  477. t->start(1000);
  478. return true;
  479. }
  480. return true;
  481. }
  482. //////////////////////////////////////////////////////////////////////////
  483. void CCryEditApp::OnFileSave()
  484. {
  485. if (m_savingLevel)
  486. {
  487. return;
  488. }
  489. const QScopedValueRollback<bool> rollback(m_savingLevel, true);
  490. auto* prefabIntegrationInterface = AZ::Interface<AzToolsFramework::Prefab::PrefabIntegrationInterface>::Get();
  491. AZ_Assert(prefabIntegrationInterface != nullptr, "PrefabIntegrationInterface is not found.");
  492. prefabIntegrationInterface->SaveCurrentPrefab();
  493. // when attempting to save, update the last known location using the active camera transform
  494. AzToolsFramework::StoreViewBookmarkLastKnownLocationFromActiveCamera();
  495. }
  496. //////////////////////////////////////////////////////////////////////////
  497. void CCryEditApp::OnUpdateDocumentReady(QAction* action)
  498. {
  499. action->setEnabled(GetIEditor()
  500. && GetIEditor()->GetDocument()
  501. && GetIEditor()->GetDocument()->IsDocumentReady()
  502. && !m_creatingNewLevel
  503. && !m_openingLevel
  504. && !m_savingLevel);
  505. }
  506. //////////////////////////////////////////////////////////////////////////
  507. void CCryEditApp::OnUpdateFileOpen(QAction* action)
  508. {
  509. action->setEnabled(!m_creatingNewLevel && !m_openingLevel && !m_savingLevel);
  510. }
  511. bool CCryEditApp::ShowEnableDisableGemDialog(const QString& title, const QString& message)
  512. {
  513. const QString informativeMessage = QObject::tr("Please follow the instructions <a href=\"https://www.o3de.org/docs/user-guide/project-config/add-remove-gems/\">here</a>, after which the Editor will be re-launched automatically.");
  514. QMessageBox box(AzToolsFramework::GetActiveWindow());
  515. box.addButton(QObject::tr("Continue"), QMessageBox::AcceptRole);
  516. box.addButton(QObject::tr("Back"), QMessageBox::RejectRole);
  517. box.setWindowTitle(title);
  518. box.setText(message);
  519. box.setInformativeText(informativeMessage);
  520. box.setWindowFlags(box.windowFlags() & ~Qt::WindowContextHelpButtonHint);
  521. if (box.exec() == QMessageBox::AcceptRole)
  522. {
  523. // Called from a modal dialog with the main window as its parent. Best not to close the main window while the dialog is still active.
  524. QTimer::singleShot(0, MainWindow::instance(), &MainWindow::close);
  525. return true;
  526. }
  527. return false;
  528. }
  529. QString CCryEditApp::ShowWelcomeDialog()
  530. {
  531. WelcomeScreenDialog wsDlg(MainWindow::instance());
  532. wsDlg.SetRecentFileList(GetRecentFileList());
  533. wsDlg.exec();
  534. QString levelName = wsDlg.GetLevelPath();
  535. return levelName;
  536. }
  537. //////////////////////////////////////////////////////////////////////////
  538. // Needed to work with custom memory manager.
  539. //////////////////////////////////////////////////////////////////////////
  540. CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(const char* lpszPathName, bool bMakeVisible /*= true*/)
  541. {
  542. return OpenDocumentFile(lpszPathName, true, bMakeVisible);
  543. }
  544. CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(const char* lpszPathName, bool addToMostRecentFileList, [[maybe_unused]] bool bMakeVisible)
  545. {
  546. CCryEditDoc* pCurDoc = GetIEditor()->GetDocument();
  547. if (pCurDoc)
  548. {
  549. if (!pCurDoc->SaveModified())
  550. {
  551. return nullptr;
  552. }
  553. }
  554. if (!pCurDoc)
  555. {
  556. pCurDoc = qobject_cast<CCryEditDoc*>(m_documentClass->newInstance());
  557. if (pCurDoc == nullptr)
  558. return nullptr;
  559. pCurDoc->setParent(this);
  560. }
  561. pCurDoc->SetModifiedFlag(false);
  562. if (lpszPathName == nullptr)
  563. {
  564. pCurDoc->SetTitle(tr("Untitled"));
  565. pCurDoc->OnNewDocument();
  566. }
  567. else
  568. {
  569. pCurDoc->OnOpenDocument(lpszPathName);
  570. pCurDoc->SetPathName(lpszPathName);
  571. if (addToMostRecentFileList)
  572. {
  573. CCryEditApp::instance()->AddToRecentFileList(lpszPathName);
  574. }
  575. }
  576. return pCurDoc;
  577. }
  578. CCrySingleDocTemplate::Confidence CCrySingleDocTemplate::MatchDocType(const char* lpszPathName, CCryEditDoc*& rpDocMatch)
  579. {
  580. assert(lpszPathName != nullptr);
  581. rpDocMatch = nullptr;
  582. // go through all documents
  583. CCryEditDoc* pDoc = GetIEditor()->GetDocument();
  584. if (pDoc)
  585. {
  586. QString prevPathName = pDoc->GetLevelPathName();
  587. // all we need to know here is whether it is the same file as before.
  588. if (!prevPathName.isEmpty())
  589. {
  590. // QFileInfo is guaranteed to return true iff the two paths refer to the same path.
  591. if (QFileInfo(prevPathName) == QFileInfo(QString::fromUtf8(lpszPathName)))
  592. {
  593. // already open
  594. rpDocMatch = pDoc;
  595. return yesAlreadyOpen;
  596. }
  597. }
  598. }
  599. // see if it matches our default suffix
  600. const QString strFilterExt = EditorUtils::LevelFile::GetDefaultFileExtension();
  601. const QString strOldFilterExt = EditorUtils::LevelFile::GetOldCryFileExtension();
  602. // see if extension matches
  603. assert(strFilterExt[0] == '.');
  604. QString strDot = "." + Path::GetExt(lpszPathName);
  605. if (!strDot.isEmpty())
  606. {
  607. if(strDot == strFilterExt || strDot == strOldFilterExt)
  608. {
  609. return yesAttemptNative; // extension matches, looks like ours
  610. }
  611. }
  612. // otherwise we will guess it may work
  613. return yesAttemptForeign;
  614. }
  615. /////////////////////////////////////////////////////////////////////////////
  616. namespace
  617. {
  618. AZStd::mutex g_splashScreenStateLock;
  619. enum ESplashScreenState
  620. {
  621. eSplashScreenState_Init, eSplashScreenState_Started, eSplashScreenState_Destroy
  622. };
  623. ESplashScreenState g_splashScreenState = eSplashScreenState_Init;
  624. IInitializeUIInfo* g_pInitializeUIInfo = nullptr;
  625. QWidget* g_splashScreen = nullptr;
  626. }
  627. QString FormatVersion([[maybe_unused]] const SFileVersion& v)
  628. {
  629. if (QObject::tr("%1").arg(O3DE_BUILD_VERSION) == "0")
  630. {
  631. return QObject::tr("Development Build");
  632. }
  633. return QObject::tr("Version %1").arg(O3DE_BUILD_VERSION);
  634. }
  635. QString FormatRichTextCopyrightNotice()
  636. {
  637. // copyright symbol is HTML Entity = &#xA9;
  638. QString copyrightHtmlSymbol = "&#xA9;";
  639. QString copyrightString = QObject::tr("Copyright %1 Contributors to the Open 3D Engine Project");
  640. return copyrightString.arg(copyrightHtmlSymbol);
  641. }
  642. void CCryEditApp::AssetSystemWaiting()
  643. {
  644. QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  645. }
  646. /////////////////////////////////////////////////////////////////////////////
  647. void CCryEditApp::ShowSplashScreen(CCryEditApp* app)
  648. {
  649. g_splashScreenStateLock.lock();
  650. CStartupLogoDialog* splashScreen = new CStartupLogoDialog(CStartupLogoDialog::Loading, FormatVersion(app->m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice());
  651. g_pInitializeUIInfo = splashScreen;
  652. g_splashScreen = splashScreen;
  653. g_splashScreenState = eSplashScreenState_Started;
  654. g_splashScreenStateLock.unlock();
  655. splashScreen->show();
  656. QObject::connect(splashScreen, &QObject::destroyed, splashScreen, [=]
  657. {
  658. AZStd::scoped_lock lock(g_splashScreenStateLock);
  659. g_pInitializeUIInfo = nullptr;
  660. g_splashScreen = nullptr;
  661. });
  662. }
  663. /////////////////////////////////////////////////////////////////////////////
  664. void CCryEditApp::CreateSplashScreen()
  665. {
  666. if (!m_bConsoleMode && !IsInAutotestMode())
  667. {
  668. // Create startup output splash
  669. ShowSplashScreen(this);
  670. GetIEditor()->Notify(eNotify_OnSplashScreenCreated);
  671. }
  672. else
  673. {
  674. // Create console
  675. m_pConsoleDialog = new CConsoleDialog();
  676. m_pConsoleDialog->show();
  677. g_pInitializeUIInfo = m_pConsoleDialog;
  678. }
  679. }
  680. /////////////////////////////////////////////////////////////////////////////
  681. void CCryEditApp::CloseSplashScreen()
  682. {
  683. if (CStartupLogoDialog::instance())
  684. {
  685. delete CStartupLogoDialog::instance();
  686. g_splashScreenStateLock.lock();
  687. g_splashScreenState = eSplashScreenState_Destroy;
  688. g_splashScreenStateLock.unlock();
  689. }
  690. GetIEditor()->Notify(eNotify_OnSplashScreenDestroyed);
  691. }
  692. /////////////////////////////////////////////////////////////////////////////
  693. void CCryEditApp::OutputStartupMessage(QString str)
  694. {
  695. g_splashScreenStateLock.lock();
  696. if (g_pInitializeUIInfo)
  697. {
  698. g_pInitializeUIInfo->SetInfoText(str.toUtf8().data());
  699. }
  700. g_splashScreenStateLock.unlock();
  701. }
  702. //////////////////////////////////////////////////////////////////////////
  703. void CCryEditApp::InitFromCommandLine(CEditCommandLineInfo& cmdInfo)
  704. {
  705. m_bConsoleMode |= cmdInfo.m_bConsoleMode;
  706. inEditorBatchMode = AZ::Environment::CreateVariable<bool>("InEditorBatchMode", m_bConsoleMode);
  707. m_bTestMode |= cmdInfo.m_bTest;
  708. m_bSkipWelcomeScreenDialog = cmdInfo.m_bSkipWelcomeScreenDialog || !cmdInfo.m_execFile.isEmpty() || !cmdInfo.m_execLineCmd.isEmpty() || cmdInfo.m_bAutotestMode;
  709. m_bRunPythonTestScript = cmdInfo.m_bRunPythonTestScript;
  710. m_bRunPythonScript = cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript;
  711. m_execFile = cmdInfo.m_execFile;
  712. m_execLineCmd = cmdInfo.m_execLineCmd;
  713. m_bAutotestMode = cmdInfo.m_bAutotestMode || cmdInfo.m_bConsoleMode;
  714. // Do we have a passed filename ?
  715. if (!cmdInfo.m_strFileName.isEmpty())
  716. {
  717. if (!m_bRunPythonScript && IsPreviewableFileType(cmdInfo.m_strFileName.toUtf8().constData()))
  718. {
  719. m_bPreviewMode = true;
  720. azstrncpy(m_sPreviewFile, _MAX_PATH, cmdInfo.m_strFileName.toUtf8().constData(), _MAX_PATH);
  721. }
  722. }
  723. if (cmdInfo.m_bAutoLoadLevel)
  724. {
  725. m_bLevelLoadTestMode = true;
  726. gEnv->bNoAssertDialog = true;
  727. CEditorAutoLevelLoadTest::Instance();
  728. }
  729. }
  730. /////////////////////////////////////////////////////////////////////////////
  731. AZ::Outcome<void, AZStd::string> CCryEditApp::InitGameSystem(HWND hwndForInputSystem)
  732. {
  733. CGameEngine* pGameEngine = new CGameEngine;
  734. AZ::Outcome<void, AZStd::string> initOutcome = pGameEngine->Init(m_bPreviewMode, m_bTestMode, qApp->arguments().join(" ").toUtf8().data(), g_pInitializeUIInfo, hwndForInputSystem);
  735. if (!initOutcome.IsSuccess())
  736. {
  737. return initOutcome;
  738. }
  739. AZ_Assert(pGameEngine, "Game engine initialization failed, but initOutcome returned success.");
  740. m_pEditor->SetGameEngine(pGameEngine);
  741. // needs to be called after CrySystem has been loaded.
  742. gSettings.LoadDefaultGamePaths();
  743. return AZ::Success();
  744. }
  745. /////////////////////////////////////////////////////////////////////////////
  746. bool CCryEditApp::CheckIfAlreadyRunning()
  747. {
  748. bool bForceNewInstance = false;
  749. if (!m_bPreviewMode)
  750. {
  751. FixDanglingSharedMemory(O3DEApplicationName);
  752. m_mutexApplication = new QSharedMemory(O3DEApplicationName);
  753. if (!m_mutexApplication->create(16))
  754. {
  755. // Don't prompt the user in non-interactive export mode. Instead, default to allowing multiple instances to
  756. // run simultaneously, so that multiple level exports can be run in parallel on the same machine.
  757. // NOTE: If you choose to do this, be sure to export *different* levels, since nothing prevents multiple runs
  758. // from trying to write to the same level at the same time.
  759. // If we're running interactively, let's ask and make sure the user actually intended to do this.
  760. if (QMessageBox::question(AzToolsFramework::GetActiveWindow(), QObject::tr("Too many apps"), QObject::tr("There is already an Open 3D Engine application running\nDo you want to start another one?")) != QMessageBox::Yes)
  761. {
  762. return false;
  763. }
  764. bForceNewInstance = true;
  765. }
  766. }
  767. if (!FirstInstance(bForceNewInstance))
  768. {
  769. return false;
  770. }
  771. return true;
  772. }
  773. /////////////////////////////////////////////////////////////////////////////
  774. bool CCryEditApp::InitGame()
  775. {
  776. if (!m_bPreviewMode)
  777. {
  778. AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath();
  779. Log((QString("project_path = %1").arg(!projectPath.empty() ? projectPath.c_str() : "<not set>")).toUtf8().data());
  780. ICVar* pVar = gEnv->pConsole->GetCVar("sys_localization_folder");
  781. const char* sLocalizationFolder = pVar ? pVar->GetString() : nullptr;
  782. Log((QString("sys_localization_folder = ") + (sLocalizationFolder && sLocalizationFolder[0] ? sLocalizationFolder : "<not set>")).toUtf8().data());
  783. OutputStartupMessage("Starting Game...");
  784. if (!GetIEditor()->GetGameEngine()->InitGame(nullptr))
  785. {
  786. return false;
  787. }
  788. }
  789. //////////////////////////////////////////////////////////////////////////
  790. // Apply settings post engine initialization.
  791. GetIEditor()->GetDisplaySettings()->PostInitApply();
  792. gSettings.PostInitApply();
  793. return true;
  794. }
  795. /////////////////////////////////////////////////////////////////////////////
  796. void CCryEditApp::InitPlugins()
  797. {
  798. OutputStartupMessage("Loading Plugins...");
  799. // Load the plugins
  800. {
  801. GetIEditor()->LoadPlugins();
  802. #if defined(AZ_PLATFORM_WINDOWS)
  803. C3DConnexionDriver* p3DConnexionDriver = new C3DConnexionDriver;
  804. GetIEditor()->GetPluginManager()->RegisterPlugin(0, p3DConnexionDriver);
  805. #endif
  806. }
  807. }
  808. ////////////////////////////////////////////////////////////////////////////
  809. // Be careful when calling this function: it should be called after
  810. // everything else has finished initializing, otherwise, certain things
  811. // aren't set up yet. If in doubt, wrap it in a QTimer::singleShot(0ms);
  812. void CCryEditApp::InitLevel(const CEditCommandLineInfo& cmdInfo)
  813. {
  814. const char* defaultExtension = EditorUtils::LevelFile::GetDefaultFileExtension();
  815. const char* oldExtension = EditorUtils::LevelFile::GetOldCryFileExtension();
  816. if (m_bPreviewMode)
  817. {
  818. // Load geometry object.
  819. if (!cmdInfo.m_strFileName.isEmpty())
  820. {
  821. LoadFile(cmdInfo.m_strFileName);
  822. }
  823. }
  824. else if ((cmdInfo.m_strFileName.endsWith(defaultExtension, Qt::CaseInsensitive))
  825. || (cmdInfo.m_strFileName.endsWith(oldExtension, Qt::CaseInsensitive)))
  826. {
  827. auto pDocument = OpenDocumentFile(cmdInfo.m_strFileName.toUtf8().constData());
  828. if (pDocument)
  829. {
  830. GetIEditor()->SetModifiedFlag(false);
  831. GetIEditor()->SetModifiedModule(eModifiedNothing);
  832. }
  833. }
  834. else
  835. {
  836. //////////////////////////////////////////////////////////////////////////
  837. //It can happen that if you are switching between projects and you have auto load set that
  838. //you could inadvertently load the wrong project and not know it, you would think you are editing
  839. //one level when in fact you are editing the old one. This can happen if both projects have the same
  840. //relative path... which is often the case when branching.
  841. // Ex. D:\cryengine\dev\ gets branched to D:\cryengine\branch\dev
  842. // Now you have gamesdk in both roots and therefore GameSDK\Levels\Singleplayer\Forest in both
  843. // If you execute the branch the m_pRecentFileList will be an absolute path to the old gamesdk,
  844. // then if auto load is set simply takes the old level and loads it in the new branch...
  845. //I would question ever trying to load a level not in our gamesdk, what happens when there are things that
  846. //an not exist in the level when built in a different gamesdk.. does it erase them, most likely, then you
  847. //just screwed up the level for everyone in the other gamesdk...
  848. //So if we are auto loading a level outside our current gamesdk we should act as though the flag
  849. //was unset and pop the dialog which should be in the correct location. This is not fool proof, but at
  850. //least this its a compromise that doesn't automatically do something you probably shouldn't.
  851. bool autoloadLastLevel = gSettings.bAutoloadLastLevelAtStartup;
  852. if (autoloadLastLevel
  853. && GetRecentFileList()
  854. && GetRecentFileList()->GetSize())
  855. {
  856. QString gamePath = Path::GetEditingGameDataFolder().c_str();
  857. Path::ConvertSlashToBackSlash(gamePath);
  858. gamePath = Path::ToUnixPath(gamePath.toLower());
  859. gamePath = Path::AddSlash(gamePath);
  860. QString fullPath = GetRecentFileList()->m_arrNames[0];
  861. Path::ConvertSlashToBackSlash(fullPath);
  862. fullPath = Path::ToUnixPath(fullPath.toLower());
  863. fullPath = Path::AddSlash(fullPath);
  864. if (fullPath.indexOf(gamePath, 0) != 0)
  865. {
  866. autoloadLastLevel = false;
  867. }
  868. }
  869. //////////////////////////////////////////////////////////////////////////
  870. QString levelName;
  871. bool isLevelNameValid = false;
  872. bool doLevelNeedLoading = true;
  873. const bool runningPythonScript = cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript;
  874. AZ::EBusLogicalResult<bool, AZStd::logical_or<bool> > skipStartupUIProcess(false);
  875. AzToolsFramework::EditorEvents::Bus::BroadcastResult(
  876. skipStartupUIProcess, &AzToolsFramework::EditorEvents::Bus::Events::SkipEditorStartupUI);
  877. if (!skipStartupUIProcess.value)
  878. {
  879. do
  880. {
  881. isLevelNameValid = false;
  882. doLevelNeedLoading = true;
  883. if (gSettings.bShowDashboardAtStartup
  884. && !runningPythonScript
  885. && !m_bConsoleMode
  886. && !m_bSkipWelcomeScreenDialog
  887. && !m_bPreviewMode
  888. && !autoloadLastLevel)
  889. {
  890. levelName = ShowWelcomeDialog();
  891. }
  892. else if (autoloadLastLevel
  893. && GetRecentFileList()
  894. && GetRecentFileList()->GetSize())
  895. {
  896. levelName = GetRecentFileList()->m_arrNames[0];
  897. }
  898. if (levelName.isEmpty())
  899. {
  900. break;
  901. }
  902. if (levelName == "new")
  903. {
  904. //implies that the user has clicked the create new level option
  905. bool wasCreateLevelOperationCancelled = false;
  906. bool isNewLevelCreationSuccess = false;
  907. // This will show the new level dialog until a valid input has been entered by the user or until the user click cancel
  908. while (!isNewLevelCreationSuccess && !wasCreateLevelOperationCancelled)
  909. {
  910. isNewLevelCreationSuccess = CreateLevel(wasCreateLevelOperationCancelled);
  911. if (isNewLevelCreationSuccess == true)
  912. {
  913. doLevelNeedLoading = false;
  914. isLevelNameValid = true;
  915. }
  916. }
  917. ;
  918. }
  919. else
  920. {
  921. //implies that the user wants to open an existing level
  922. doLevelNeedLoading = true;
  923. isLevelNameValid = true;
  924. }
  925. } while (!isLevelNameValid);// if we reach here and levelName is not valid ,it implies that the user has clicked cancel on the create new level dialog
  926. // load level
  927. if (doLevelNeedLoading && !levelName.isEmpty())
  928. {
  929. if (!CFileUtil::Exists(levelName, false))
  930. {
  931. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Missing level"), QObject::tr("Failed to auto-load last opened level. Level file does not exist:\n\n%1").arg(levelName));
  932. return;
  933. }
  934. QString str;
  935. str = tr("Loading level %1 ...").arg(levelName);
  936. OutputStartupMessage(str);
  937. OpenDocumentFile(levelName.toUtf8().data());
  938. }
  939. }
  940. }
  941. }
  942. /////////////////////////////////////////////////////////////////////////////
  943. bool CCryEditApp::InitConsole()
  944. {
  945. // Execute command from cmdline -exec_line if applicable
  946. if (!m_execLineCmd.isEmpty())
  947. {
  948. gEnv->pConsole->ExecuteString(QString("%1").arg(m_execLineCmd).toLocal8Bit());
  949. }
  950. // Execute cfg from cmdline -exec if applicable
  951. if (!m_execFile.isEmpty())
  952. {
  953. gEnv->pConsole->ExecuteString(QString("exec %1").arg(m_execFile).toLocal8Bit());
  954. }
  955. // Execute special configs.
  956. gEnv->pConsole->ExecuteString("exec editor_autoexec.cfg");
  957. gEnv->pConsole->ExecuteString("exec editor.cfg");
  958. gEnv->pConsole->ExecuteString("exec user.cfg");
  959. GetISystem()->ExecuteCommandLine();
  960. return true;
  961. }
  962. /////////////////////////////////////////////////////////////////////////////
  963. void CCryEditApp::CompileCriticalAssets() const
  964. {
  965. // regardless of what is set in the bootstrap wait for AP to be ready
  966. // wait a maximum of 100 milliseconds and pump the system event loop until empty
  967. struct AssetsInQueueNotification
  968. : public AzFramework::AssetSystemInfoBus::Handler
  969. {
  970. void CountOfAssetsInQueue(const int& count) override
  971. {
  972. CCryEditApp::OutputStartupMessage(QString("Asset Processor working... %1 jobs remaining.").arg(count));
  973. }
  974. };
  975. AssetsInQueueNotification assetsInQueueNotifcation;
  976. assetsInQueueNotifcation.BusConnect();
  977. bool ready{};
  978. while (!ready)
  979. {
  980. AzFramework::AssetSystemRequestBus::BroadcastResult(ready, &AzFramework::AssetSystemRequestBus::Events::WaitUntilAssetProcessorReady, AZStd::chrono::milliseconds(100));
  981. if (!ready)
  982. {
  983. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::PumpSystemEventLoopUntilEmpty);
  984. }
  985. }
  986. assetsInQueueNotifcation.BusDisconnect();
  987. AZ_TracePrintf("Editor", "CriticalAssetsCompiled\n");
  988. // Signal the "CriticalAssetsCompiled" lifecycle event
  989. // Also reload the "assetcatalog.xml" if it exists
  990. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  991. {
  992. // Reload the assetcatalog.xml at this point again
  993. // Start Monitoring Asset changes over the network and load the AssetCatalog
  994. auto LoadCatalog = [settingsRegistry](AZ::Data::AssetCatalogRequests* assetCatalogRequests)
  995. {
  996. if (AZ::IO::FixedMaxPath assetCatalogPath;
  997. settingsRegistry->Get(assetCatalogPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_CacheRootFolder))
  998. {
  999. assetCatalogPath /= "assetcatalog.xml";
  1000. assetCatalogRequests->LoadCatalog(assetCatalogPath.c_str());
  1001. }
  1002. };
  1003. CCryEditApp::OutputStartupMessage(QString("Loading Asset Catalog..."));
  1004. AZ::Data::AssetCatalogRequestBus::Broadcast(AZStd::move(LoadCatalog));
  1005. // Only signal the event *after* the asset catalog has been loaded.
  1006. AZ::ComponentApplicationLifecycle::SignalEvent(*settingsRegistry, "CriticalAssetsCompiled", R"({})");
  1007. }
  1008. CCryEditApp::OutputStartupMessage(QString("Asset Processor is now ready."));
  1009. }
  1010. bool CCryEditApp::ConnectToAssetProcessor() const
  1011. {
  1012. bool connectedToAssetProcessor = false;
  1013. // When the AssetProcessor is already launched it should take less than a second to perform a connection
  1014. // but when the AssetProcessor needs to be launch it could take up to 15 seconds to have the AssetProcessor initialize
  1015. // and able to negotiate a connection when running a debug build
  1016. // and to negotiate a connection
  1017. // Setting the connectTimeout to 3 seconds if not set within the settings registry
  1018. AZStd::chrono::seconds connectTimeout(3);
  1019. // Initialize the launchAssetProcessorTimeout to 15 seconds by default and check the settings registry for an override
  1020. AZStd::chrono::seconds launchAssetProcessorTimeout(15);
  1021. AZ::SettingsRegistryInterface* settingsRegistry = AZ::SettingsRegistry::Get();
  1022. if (settingsRegistry)
  1023. {
  1024. AZ::s64 timeoutValue{};
  1025. if (AZ::SettingsRegistryMergeUtils::PlatformGet(*settingsRegistry, timeoutValue,
  1026. AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, "connect_ap_timeout"))
  1027. {
  1028. connectTimeout = AZStd::chrono::seconds(timeoutValue);
  1029. }
  1030. // Reset timeout integer
  1031. timeoutValue = {};
  1032. if (AZ::SettingsRegistryMergeUtils::PlatformGet(*settingsRegistry, timeoutValue,
  1033. AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, "launch_ap_timeout"))
  1034. {
  1035. launchAssetProcessorTimeout = AZStd::chrono::seconds(timeoutValue);
  1036. }
  1037. }
  1038. CCryEditApp::OutputStartupMessage(QString("Connecting to Asset Processor... "));
  1039. AzFramework::AssetSystem::ConnectionSettings connectionSettings;
  1040. AzFramework::AssetSystem::ReadConnectionSettingsFromSettingsRegistry(connectionSettings);
  1041. connectionSettings.m_launchAssetProcessorOnFailedConnection = true;
  1042. connectionSettings.m_connectionDirection = AzFramework::AssetSystem::ConnectionSettings::ConnectionDirection::ConnectToAssetProcessor;
  1043. connectionSettings.m_connectionIdentifier = AzFramework::AssetSystem::ConnectionIdentifiers::Editor;
  1044. connectionSettings.m_loggingCallback = [](AZStd::string_view logData)
  1045. {
  1046. CCryEditApp::OutputStartupMessage(QString::fromUtf8(logData.data(), aznumeric_cast<int>(logData.size())));
  1047. };
  1048. AzFramework::AssetSystemRequestBus::BroadcastResult(connectedToAssetProcessor, &AzFramework::AssetSystemRequestBus::Events::EstablishAssetProcessorConnection, connectionSettings);
  1049. if (connectedToAssetProcessor)
  1050. {
  1051. AZ_TracePrintf("Editor", "Connected to Asset Processor\n");
  1052. CCryEditApp::OutputStartupMessage(QString("Connected to Asset Processor"));
  1053. CompileCriticalAssets();
  1054. return true;
  1055. }
  1056. AZ_TracePrintf("Editor", "Failed to connect to Asset Processor\n");
  1057. CCryEditApp::OutputStartupMessage(QString("Failed to connect to Asset Processor"));
  1058. return false;
  1059. }
  1060. //! This handles the normal logging of Python output in the Editor by outputting
  1061. //! the data to both the Editor Console and the Editor.log file
  1062. struct CCryEditApp::PythonOutputHandler
  1063. : public AzToolsFramework::EditorPythonConsoleNotificationBus::Handler
  1064. {
  1065. PythonOutputHandler()
  1066. {
  1067. AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusConnect();
  1068. }
  1069. ~PythonOutputHandler() override
  1070. {
  1071. AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect();
  1072. }
  1073. int GetOrder() override
  1074. {
  1075. return 0;
  1076. }
  1077. void OnTraceMessage([[maybe_unused]] AZStd::string_view message) override
  1078. {
  1079. AZ_TracePrintf("python_test", "%.*s", static_cast<int>(message.size()), message.data());
  1080. }
  1081. void OnErrorMessage([[maybe_unused]] AZStd::string_view message) override
  1082. {
  1083. AZ_Error("python_test", false, "%.*s", static_cast<int>(message.size()), message.data());
  1084. }
  1085. void OnExceptionMessage([[maybe_unused]] AZStd::string_view message) override
  1086. {
  1087. AZ_Error("python_test", false, "EXCEPTION: %.*s", static_cast<int>(message.size()), message.data());
  1088. }
  1089. };
  1090. //! Outputs Python test script print() to stdout
  1091. //! If an exception happens in a Python test script, the process terminates
  1092. struct PythonTestOutputHandler final
  1093. : public CCryEditApp::PythonOutputHandler
  1094. {
  1095. PythonTestOutputHandler() = default;
  1096. ~PythonTestOutputHandler() override = default;
  1097. void OnTraceMessage(AZStd::string_view message) override
  1098. {
  1099. PythonOutputHandler::OnTraceMessage(message);
  1100. printf("%.*s\n", static_cast<int>(message.size()), message.data());
  1101. }
  1102. void OnErrorMessage(AZStd::string_view message) override
  1103. {
  1104. PythonOutputHandler::OnErrorMessage(message);
  1105. printf("ERROR: %.*s\n", static_cast<int>(message.size()), message.data());
  1106. }
  1107. void OnExceptionMessage(AZStd::string_view message) override
  1108. {
  1109. PythonOutputHandler::OnExceptionMessage(message);
  1110. printf("EXCEPTION: %.*s\n", static_cast<int>(message.size()), message.data());
  1111. }
  1112. };
  1113. void CCryEditApp::RunInitPythonScript(CEditCommandLineInfo& cmdInfo)
  1114. {
  1115. if (cmdInfo.m_bRunPythonTestScript)
  1116. {
  1117. m_pythonOutputHandler = AZStd::make_shared<PythonTestOutputHandler>();
  1118. }
  1119. else
  1120. {
  1121. m_pythonOutputHandler = AZStd::make_shared<PythonOutputHandler>();
  1122. }
  1123. using namespace AzToolsFramework;
  1124. if (cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript)
  1125. {
  1126. // Separates the compound string of semicolon separated values into a vector of values
  1127. const auto extractSeparatedValues = [](const AZStd::string& compoundValues)
  1128. {
  1129. AZStd::vector<AZStd::string_view> values;
  1130. AZ::StringFunc::TokenizeVisitor(
  1131. compoundValues.c_str(),
  1132. [&values](AZStd::string_view elem)
  1133. {
  1134. values.push_back(elem);
  1135. },
  1136. ';',
  1137. false /* keepEmptyStrings */
  1138. );
  1139. return values;
  1140. };
  1141. // Reads the contents of the specified file and returns a string of said contents
  1142. const auto readFileContents = [](const AZStd::string& path) -> AZStd::string
  1143. {
  1144. const auto fileSize = AZ::IO::SystemFile::Length(path.c_str());
  1145. if (fileSize == 0)
  1146. {
  1147. return "";
  1148. }
  1149. AZStd::vector<char> buffer(fileSize + 1);
  1150. buffer[fileSize] = '\0';
  1151. if (!AZ::IO::SystemFile::Read(path.c_str(), buffer.data()))
  1152. {
  1153. return "";
  1154. }
  1155. return AZStd::string(buffer.begin(), buffer.end());
  1156. };
  1157. // We support specifying multiple files in the cmdline by separating them with ';'
  1158. // If a semicolon list of .py files is provided we look at the arg string
  1159. AZStd::string scriptFileStr;
  1160. if (cmdInfo.m_strFileName.endsWith(".py"))
  1161. {
  1162. // cmdInfo data is only available on startup, copy it
  1163. scriptFileStr = cmdInfo.m_strFileName.toUtf8().constData();
  1164. }
  1165. else if (cmdInfo.m_strFileName.endsWith(".txt"))
  1166. {
  1167. // Otherwise, we look to see if we can read the file for test modules
  1168. // The file is expected to contain a single semicolon separated string of Editor pytest modules
  1169. if (scriptFileStr = readFileContents(cmdInfo.m_strFileName.toUtf8().data()); scriptFileStr.empty())
  1170. {
  1171. AZ_Error(
  1172. "RunInitPythonScript",
  1173. false, "Failed to read the file containing a semi colon separated list of python modules");
  1174. return;
  1175. }
  1176. }
  1177. else
  1178. {
  1179. AZ_Error("RunInitPythonScript", false, "Failed to read Python files from --runpythontest arg. "
  1180. "Expects a semi colon separated list of python modules or a file containing a semi colon separated list of python modules");
  1181. return;
  1182. }
  1183. // Extract the discrete python script files
  1184. const auto fileList = extractSeparatedValues(scriptFileStr);
  1185. if (cmdInfo.m_pythonArgs.length() > 0 || cmdInfo.m_bRunPythonTestScript)
  1186. {
  1187. QByteArray pythonArgsStr = cmdInfo.m_pythonArgs.toUtf8();
  1188. AZStd::vector<AZStd::string_view> pythonArgs;
  1189. AZ::StringFunc::TokenizeVisitor(pythonArgsStr.constData(),
  1190. [&pythonArgs](AZStd::string_view elem)
  1191. {
  1192. pythonArgs.push_back(elem);
  1193. }, ' '
  1194. );
  1195. if (cmdInfo.m_bRunPythonTestScript)
  1196. {
  1197. // We support specifying multiple test case names in the cmdline by separating them
  1198. // with ';', either in a text file or as a string
  1199. AZStd::string testCaseStr;
  1200. if (cmdInfo.m_pythonTestCase.endsWith(".txt"))
  1201. {
  1202. // A path to the file containing the test case names has been provided as the argument
  1203. if (testCaseStr = readFileContents(cmdInfo.m_pythonTestCase.toUtf8().data()); testCaseStr.empty())
  1204. {
  1205. AZ_Error(
  1206. "RunInitPythonScript",
  1207. false,
  1208. "Failed to read Python files from --pythontestcase arg. "
  1209. "Expects a semi colon separated list of python test case names or a file containing a semi colon separated list of "
  1210. "python test case names");
  1211. return;
  1212. }
  1213. }
  1214. else
  1215. {
  1216. // Test case names have been passed as the argument
  1217. testCaseStr = cmdInfo.m_pythonTestCase.toUtf8().data();
  1218. }
  1219. // Extract the discrete python test case names
  1220. const auto testCaseList = extractSeparatedValues(testCaseStr);
  1221. // The number of python script files must match the number of test case names for the test case names
  1222. // to properly correlate with their invoking scripts
  1223. if (fileList.size() != testCaseList.size())
  1224. {
  1225. AZ_Error(
  1226. "RunInitPythonScript",
  1227. false,
  1228. "The number of supplied test scripts (%zu) did not match the number of supplied test case names (%zu)",
  1229. fileList.size(), testCaseList.size());
  1230. return;
  1231. }
  1232. bool success = true;
  1233. auto ExecuteByFilenamesTests = [&pythonArgs, &fileList, &testCaseList, &success](EditorPythonRunnerRequests* pythonRunnerRequests)
  1234. {
  1235. for (int i = 0; i < fileList.size(); ++i)
  1236. {
  1237. bool cur_success = pythonRunnerRequests->ExecuteByFilenameAsTest(fileList[i], testCaseList[i], pythonArgs);
  1238. success = success && cur_success;
  1239. }
  1240. };
  1241. EditorPythonRunnerRequestBus::Broadcast(ExecuteByFilenamesTests);
  1242. if (success)
  1243. {
  1244. // Close the editor gracefully as the test has completed
  1245. GetIEditor()->GetDocument()->SetModifiedFlag(false);
  1246. QTimer::singleShot(0, qApp, &QApplication::closeAllWindows);
  1247. }
  1248. else
  1249. {
  1250. // Close down the application with 0xF exit code indicating failure of the test
  1251. AZ::Debug::Trace::Terminate(0xF);
  1252. }
  1253. }
  1254. else
  1255. {
  1256. auto ExecuteByFilenamesWithArgs = [&pythonArgs, &fileList](EditorPythonRunnerRequests* pythonRunnerRequests)
  1257. {
  1258. for (AZStd::string_view filename : fileList)
  1259. {
  1260. pythonRunnerRequests->ExecuteByFilenameWithArgs(filename, pythonArgs);
  1261. }
  1262. };
  1263. EditorPythonRunnerRequestBus::Broadcast(ExecuteByFilenamesWithArgs);
  1264. }
  1265. }
  1266. else
  1267. {
  1268. auto ExecuteByFilenames = [&fileList](EditorPythonRunnerRequests* pythonRunnerRequests)
  1269. {
  1270. for (AZStd::string_view filename : fileList)
  1271. {
  1272. pythonRunnerRequests->ExecuteByFilename(filename);
  1273. }
  1274. };
  1275. EditorPythonRunnerRequestBus::Broadcast(ExecuteByFilenames);
  1276. }
  1277. }
  1278. }
  1279. /////////////////////////////////////////////////////////////////////////////
  1280. // CCryEditApp initialization
  1281. bool CCryEditApp::InitInstance()
  1282. {
  1283. QElapsedTimer startupTimer;
  1284. startupTimer.start();
  1285. m_pEditor = new CEditorImpl();
  1286. // parameters must be parsed early to capture arguments for test bootstrap
  1287. CEditCommandLineInfo cmdInfo;
  1288. InitFromCommandLine(cmdInfo);
  1289. qobject_cast<Editor::EditorQtApplication*>(qApp)->Initialize(); // Must be done after CEditorImpl() is created
  1290. m_pEditor->Initialize();
  1291. // let anything listening know that they can use the IEditor now
  1292. AzToolsFramework::EditorEvents::Bus::Broadcast(&AzToolsFramework::EditorEvents::NotifyIEditorAvailable, m_pEditor);
  1293. if (cmdInfo.m_bShowVersionInfo)
  1294. {
  1295. CStartupLogoDialog startupDlg(CStartupLogoDialog::About, FormatVersion(m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice());
  1296. startupDlg.exec();
  1297. return false;
  1298. }
  1299. RegisterReflectedVarHandlers();
  1300. CreateSplashScreen();
  1301. // Register the application's document templates. Document templates
  1302. // serve as the connection between documents, frame windows and views
  1303. CCrySingleDocTemplate* pDocTemplate = CCrySingleDocTemplate::create<CCryEditDoc>();
  1304. m_pDocManager = new CCryDocManager;
  1305. ((CCryDocManager*)m_pDocManager)->SetDefaultTemplate(pDocTemplate);
  1306. auto mainWindow = new MainWindow();
  1307. #ifdef Q_OS_MACOS
  1308. auto mainWindowWrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionDisabled);
  1309. #else
  1310. auto mainWindowWrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionAutoTitleBarButtons);
  1311. #endif
  1312. mainWindowWrapper->setGuest(mainWindow);
  1313. HWND mainWindowWrapperHwnd = (HWND)mainWindowWrapper->winId();
  1314. AZ::IO::FixedMaxPath engineRootPath;
  1315. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  1316. {
  1317. settingsRegistry->Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder);
  1318. }
  1319. QDir engineRoot = QString::fromUtf8(engineRootPath.c_str(), aznumeric_cast<int>(engineRootPath.Native().size()));
  1320. AzQtComponents::StyleManager::addSearchPaths(
  1321. QStringLiteral("style"),
  1322. engineRoot.filePath(QStringLiteral("Code/Editor/Style")),
  1323. QStringLiteral(":/Assets/Editor/Style"),
  1324. engineRootPath);
  1325. AzQtComponents::StyleManager::setStyleSheet(mainWindow, QStringLiteral("style:Editor.qss"));
  1326. // Note: we should use getNativeHandle to get the HWND from the widget, but
  1327. // it returns an invalid handle unless the widget has been shown and polished and even then
  1328. // it sometimes returns an invalid handle.
  1329. // So instead, we use winId(), which does consistently work
  1330. //mainWindowWrapperHwnd = QtUtil::getNativeHandle(mainWindowWrapper);
  1331. // Connect to the AssetProcessor at this point
  1332. // It will be launched if not running
  1333. ConnectToAssetProcessor();
  1334. CCryEditApp::OutputStartupMessage(QString("Initializing Game System..."));
  1335. auto initGameSystemOutcome = InitGameSystem(mainWindowWrapperHwnd);
  1336. if (!initGameSystemOutcome.IsSuccess())
  1337. {
  1338. return false;
  1339. }
  1340. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  1341. {
  1342. AZ::ComponentApplicationLifecycle::SignalEvent(*settingsRegistry, "LegacySystemInterfaceCreated", R"({})");
  1343. }
  1344. // Process some queued events come from system init
  1345. // Such as asset catalog loaded notification.
  1346. // There are some systems need to load configurations from assets for post initialization but before loading level
  1347. AZ::TickBus::ExecuteQueuedEvents();
  1348. qobject_cast<Editor::EditorQtApplication*>(qApp)->LoadSettings();
  1349. // Create Sandbox user folder if necessary
  1350. AZ::IO::FileIOBase::GetDirectInstance()->CreatePath(Path::GetUserSandboxFolder().toUtf8().data());
  1351. if (!InitGame())
  1352. {
  1353. if (gEnv && gEnv->pLog)
  1354. {
  1355. gEnv->pLog->LogError("Game can not be initialized, InitGame() failed.");
  1356. }
  1357. return false;
  1358. }
  1359. // Meant to be called before MainWindow::Initialize
  1360. InitPlugins();
  1361. CCryEditApp::OutputStartupMessage(QString("Initializing Main Window..."));
  1362. mainWindow->Initialize();
  1363. GetIEditor()->GetCommandManager()->RegisterAutoCommands();
  1364. mainWindowWrapper->enableSaveRestoreGeometry("O3DE", "O3DE", "mainWindowGeometry");
  1365. m_pDocManager->OnFileNew();
  1366. if (MainWindow::instance())
  1367. {
  1368. if (m_bConsoleMode || IsInAutotestMode())
  1369. {
  1370. AZ::Environment::FindVariable<int>("assertVerbosityLevel").Set(1);
  1371. m_pConsoleDialog->raise();
  1372. }
  1373. else
  1374. {
  1375. MainWindow::instance()->show();
  1376. MainWindow::instance()->raise();
  1377. MainWindow::instance()->update();
  1378. MainWindow::instance()->setFocus();
  1379. #if AZ_TRAIT_OS_PLATFORM_APPLE
  1380. QWindow* window = mainWindowWrapper->windowHandle();
  1381. if (window)
  1382. {
  1383. Editor::WindowObserver* observer = new Editor::WindowObserver(window, this);
  1384. connect(observer, &Editor::WindowObserver::windowIsMovingOrResizingChanged, Editor::EditorQtApplication::instance(), &Editor::EditorQtApplication::setIsMovingOrResizing);
  1385. }
  1386. #endif
  1387. }
  1388. }
  1389. if (m_bAutotestMode)
  1390. {
  1391. ICVar* const noErrorReportWindowCVar = gEnv && gEnv->pConsole ? gEnv->pConsole->GetCVar("sys_no_error_report_window") : nullptr;
  1392. if (noErrorReportWindowCVar)
  1393. {
  1394. noErrorReportWindowCVar->Set(true);
  1395. }
  1396. ICVar* const showErrorDialogOnLoadCVar = gEnv && gEnv->pConsole ? gEnv->pConsole->GetCVar("ed_showErrorDialogOnLoad") : nullptr;
  1397. if (showErrorDialogOnLoadCVar)
  1398. {
  1399. showErrorDialogOnLoadCVar->Set(false);
  1400. }
  1401. }
  1402. SetEditorWindowTitle(nullptr, AZ::Utils::GetProjectDisplayName().c_str(), nullptr);
  1403. m_pEditor->InitFinished();
  1404. CCryEditApp::OutputStartupMessage(QString("Activating Python..."));
  1405. // Make sure Python is started before we attempt to restore the Editor layout, since the user
  1406. // might have custom view panes in the saved layout that will need to be registered.
  1407. auto editorPythonEventsInterface = AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Get();
  1408. if (editorPythonEventsInterface)
  1409. {
  1410. editorPythonEventsInterface->StartPython();
  1411. }
  1412. CCryEditApp::OutputStartupMessage(QString("")); // add a blank line so that python is not blamed for anything that happens here
  1413. if (!GetIEditor()->IsInConsolewMode())
  1414. {
  1415. bool restoreDefaults = !mainWindowWrapper->restoreGeometryFromSettings();
  1416. QtViewPaneManager::instance()->RestoreLayout(restoreDefaults);
  1417. }
  1418. // Trigger the Action Manager registration hooks once all systems and Gems are initialized and listening.
  1419. AzToolsFramework::ActionManagerSystemComponent::TriggerRegistrationNotifications();
  1420. CloseSplashScreen();
  1421. // DON'T CHANGE ME!
  1422. // Test scripts listen for this line, so please don't touch this without updating them.
  1423. // We consider ourselves "initialized enough" at this stage because all further initialization may be blocked by the modal welcome screen.
  1424. CLogFile::WriteLine(QString("Engine initialized, took %1s.").arg(startupTimer.elapsed() / 1000.0, 0, 'f', 2));
  1425. // Init the level after everything else is finished initializing, otherwise, certain things aren't set up yet
  1426. QTimer::singleShot(0, this, [this, cmdInfo] {
  1427. InitLevel(cmdInfo);
  1428. });
  1429. if (!m_bConsoleMode && !m_bPreviewMode)
  1430. {
  1431. GetIEditor()->UpdateViews();
  1432. if (MainWindow::instance())
  1433. {
  1434. MainWindow::instance()->setFocus();
  1435. }
  1436. }
  1437. if (!InitConsole())
  1438. {
  1439. return true;
  1440. }
  1441. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  1442. {
  1443. AZ::ComponentApplicationLifecycle::SignalEvent(*settingsRegistry, "LegacyCommandLineProcessed", R"({})");
  1444. }
  1445. if (IsInRegularEditorMode())
  1446. {
  1447. int startUpMacroIndex = GetIEditor()->GetToolBoxManager()->GetMacroIndex("startup", true);
  1448. if (startUpMacroIndex >= 0)
  1449. {
  1450. CryLogAlways("Executing the startup macro");
  1451. GetIEditor()->GetToolBoxManager()->ExecuteMacro(startUpMacroIndex, true);
  1452. }
  1453. }
  1454. if (GetIEditor()->GetCommandManager()->IsRegistered("editor.open_lnm_editor"))
  1455. {
  1456. CCommand0::SUIInfo uiInfo;
  1457. [[maybe_unused]] bool ok = GetIEditor()->GetCommandManager()->GetUIInfo("editor.open_lnm_editor", uiInfo);
  1458. assert(ok);
  1459. }
  1460. RunInitPythonScript(cmdInfo);
  1461. return true;
  1462. }
  1463. //////////////////////////////////////////////////////////////////////////
  1464. void CCryEditApp::LoadFile([[maybe_unused]] QString fileName)
  1465. {
  1466. if (GetIEditor()->GetViewManager()->GetViewCount() == 0)
  1467. {
  1468. return;
  1469. }
  1470. if (MainWindow::instance() || m_pConsoleDialog)
  1471. {
  1472. SetEditorWindowTitle(nullptr, AZ::Utils::GetProjectDisplayName().c_str(), GetIEditor()->GetGameEngine()->GetLevelName());
  1473. }
  1474. GetIEditor()->SetModifiedFlag(false);
  1475. GetIEditor()->SetModifiedModule(eModifiedNothing);
  1476. }
  1477. //////////////////////////////////////////////////////////////////////////
  1478. inline void ExtractMenuName(QString& str)
  1479. {
  1480. // eliminate &
  1481. int pos = str.indexOf('&');
  1482. if (pos >= 0)
  1483. {
  1484. str = str.left(pos) + str.right(str.length() - pos - 1);
  1485. }
  1486. // cut the string
  1487. for (int i = 0; i < str.length(); i++)
  1488. {
  1489. if (str[i] == 9)
  1490. {
  1491. str = str.left(i);
  1492. }
  1493. }
  1494. }
  1495. //////////////////////////////////////////////////////////////////////////
  1496. void CCryEditApp::EnableAccelerator([[maybe_unused]] bool bEnable)
  1497. {
  1498. /*
  1499. if (bEnable)
  1500. {
  1501. //LoadAccelTable( MAKEINTRESOURCE(IDR_MAINFRAME) );
  1502. m_AccelManager.UpdateWndTable();
  1503. CLogFile::WriteLine( "Enable Accelerators" );
  1504. }
  1505. else
  1506. {
  1507. CMainFrame *mainFrame = (CMainFrame*)m_pMainWnd;
  1508. if (mainFrame->m_hAccelTable)
  1509. DestroyAcceleratorTable( mainFrame->m_hAccelTable );
  1510. mainFrame->m_hAccelTable = nullptr;
  1511. mainFrame->LoadAccelTable( MAKEINTRESOURCE(IDR_GAMEACCELERATOR) );
  1512. CLogFile::WriteLine( "Disable Accelerators" );
  1513. }
  1514. */
  1515. }
  1516. //////////////////////////////////////////////////////////////////////////
  1517. void CCryEditApp::SaveAutoRemind()
  1518. {
  1519. // Added a static variable here to avoid multiple messageboxes to
  1520. // remind the user of saving the file. Many message boxes would appear as this
  1521. // is triggered by a timer even which does not stop when the message box is called.
  1522. // Used a static variable instead of a member variable because this value is not
  1523. // Needed anywhere else.
  1524. static bool boIsShowingWarning(false);
  1525. // Ingore in game mode, or if no level created, or level not modified
  1526. if (GetIEditor()->IsInGameMode() || !GetIEditor()->GetGameEngine()->IsLevelLoaded() || !GetIEditor()->GetDocument()->IsModified())
  1527. {
  1528. return;
  1529. }
  1530. if (boIsShowingWarning)
  1531. {
  1532. return;
  1533. }
  1534. boIsShowingWarning = true;
  1535. if (QMessageBox::question(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Auto Reminder: You did not save level for at least %1 minute(s)\r\nDo you want to save it now?").arg(gSettings.autoRemindTime), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
  1536. {
  1537. // Save now.
  1538. GetIEditor()->SaveDocument();
  1539. }
  1540. boIsShowingWarning = false;
  1541. }
  1542. //////////////////////////////////////////////////////////////////////////
  1543. void CCryEditApp::WriteConfig()
  1544. {
  1545. IEditor* pEditor = GetIEditor();
  1546. if (pEditor && pEditor->GetDisplaySettings())
  1547. {
  1548. pEditor->GetDisplaySettings()->SaveRegistry();
  1549. }
  1550. }
  1551. // App command to run the dialog
  1552. void CCryEditApp::OnAppAbout()
  1553. {
  1554. auto* dialog = new CStartupLogoDialog(
  1555. CStartupLogoDialog::About, FormatVersion(m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice());
  1556. auto mainWindow = MainWindow::instance();
  1557. auto geometry = dialog->geometry();
  1558. geometry.moveCenter(mainWindow->mapToGlobal(mainWindow->geometry().center()));
  1559. dialog->setGeometry(geometry);
  1560. dialog->setAttribute(Qt::WA_DeleteOnClose);
  1561. dialog->show();
  1562. }
  1563. // App command to run the Welcome to Open 3D Engine dialog
  1564. void CCryEditApp::OnAppShowWelcomeScreen()
  1565. {
  1566. // This logic is a simplified version of the startup
  1567. // flow that also shows the Welcome dialog
  1568. if (m_creatingNewLevel
  1569. || m_openingLevel
  1570. || m_savingLevel)
  1571. {
  1572. QMessageBox::warning(AzToolsFramework::GetActiveWindow(), QString(), "The Welcome screen cannot be displayed because a level load/save is in progress.");
  1573. return;
  1574. }
  1575. QString levelName;
  1576. bool showWelcomeDialog = true;
  1577. while (showWelcomeDialog)
  1578. {
  1579. // Keep showing the Welcome dialog as long as the user cancels
  1580. // a level creation/load triggered from the Welcome dialog
  1581. levelName = ShowWelcomeDialog();
  1582. if (levelName == "new")
  1583. {
  1584. // The user has clicked on the create new level option
  1585. bool wasCreateLevelOperationCancelled = false;
  1586. bool isNewLevelCreationSuccess = false;
  1587. // This will show the new level dialog until a valid input has been entered by the user or until the user click cancel
  1588. while (!isNewLevelCreationSuccess && !wasCreateLevelOperationCancelled)
  1589. {
  1590. isNewLevelCreationSuccess = CreateLevel(wasCreateLevelOperationCancelled);
  1591. }
  1592. if (isNewLevelCreationSuccess)
  1593. {
  1594. showWelcomeDialog = false;
  1595. levelName.clear();
  1596. }
  1597. }
  1598. else
  1599. {
  1600. // The user has selected an existing level to open
  1601. showWelcomeDialog = false;
  1602. }
  1603. }
  1604. if (!levelName.isEmpty())
  1605. {
  1606. // load level
  1607. if (!CFileUtil::Exists(levelName, false))
  1608. {
  1609. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Missing level"), QObject::tr("Failed to auto-load last opened level. Level file does not exist:\n\n%1").arg(levelName));
  1610. }
  1611. else
  1612. {
  1613. OpenDocumentFile(levelName.toUtf8().data());
  1614. }
  1615. }
  1616. }
  1617. void CCryEditApp::OnUpdateShowWelcomeScreen(QAction* action)
  1618. {
  1619. action->setEnabled(!m_creatingNewLevel
  1620. && !m_openingLevel
  1621. && !m_savingLevel);
  1622. }
  1623. void CCryEditApp::OnDocumentationTutorials()
  1624. {
  1625. QString webLink = tr("https://o3de.org/docs/learning-guide/");
  1626. QDesktopServices::openUrl(QUrl(webLink));
  1627. }
  1628. void CCryEditApp::OnDocumentationGlossary()
  1629. {
  1630. QString webLink = tr("https://o3de.org/docs/user-guide/appendix/glossary/");
  1631. QDesktopServices::openUrl(QUrl(webLink));
  1632. }
  1633. void CCryEditApp::OnDocumentationO3DE()
  1634. {
  1635. QString webLink = tr("https://o3de.org/docs/");
  1636. QDesktopServices::openUrl(QUrl(webLink));
  1637. }
  1638. void CCryEditApp::OnDocumentationReleaseNotes()
  1639. {
  1640. QString webLink = tr("https://o3de.org/docs/release-notes/");
  1641. QDesktopServices::openUrl(QUrl(webLink));
  1642. }
  1643. void CCryEditApp::OnDocumentationGameDevBlog()
  1644. {
  1645. QString webLink = tr("https://o3de.org/news-blogs/");
  1646. QDesktopServices::openUrl(QUrl(webLink));
  1647. }
  1648. void CCryEditApp::OnDocumentationForums()
  1649. {
  1650. QString webLink = tr("https://discord.com/invite/o3de");
  1651. QDesktopServices::openUrl(QUrl(webLink));
  1652. }
  1653. bool CCryEditApp::FixDanglingSharedMemory(const QString& sharedMemName) const
  1654. {
  1655. QSystemSemaphore sem(sharedMemName + "_sem", 1);
  1656. sem.acquire();
  1657. {
  1658. QSharedMemory fix(sharedMemName);
  1659. if (!fix.attach())
  1660. {
  1661. if (fix.error() != QSharedMemory::NotFound)
  1662. {
  1663. sem.release();
  1664. return false;
  1665. }
  1666. }
  1667. // fix.detach() when destructed, taking out any dangling shared memory
  1668. // on unix
  1669. }
  1670. sem.release();
  1671. return true;
  1672. }
  1673. /////////////////////////////////////////////////////////////////////////////
  1674. // CCryEditApp message handlers
  1675. int CCryEditApp::ExitInstance(int exitCode)
  1676. {
  1677. if (m_pEditor)
  1678. {
  1679. m_pEditor->OnBeginShutdownSequence();
  1680. }
  1681. qobject_cast<Editor::EditorQtApplication*>(qApp)->UnloadSettings();
  1682. if (IsInRegularEditorMode())
  1683. {
  1684. if (GetIEditor())
  1685. {
  1686. int shutDownMacroIndex = GetIEditor()->GetToolBoxManager()->GetMacroIndex("shutdown", true);
  1687. if (shutDownMacroIndex >= 0)
  1688. {
  1689. CryLogAlways("Executing the shutdown macro");
  1690. GetIEditor()->GetToolBoxManager()->ExecuteMacro(shutDownMacroIndex, true);
  1691. }
  1692. }
  1693. }
  1694. if (GetIEditor())
  1695. {
  1696. //Nobody seems to know in what case that kind of exit can happen so instrumented to see if it happens at all
  1697. if (m_pEditor)
  1698. {
  1699. m_pEditor->OnEarlyExitShutdownSequence();
  1700. }
  1701. gEnv->pLog->Flush();
  1702. // note: the intention here is to quit immediately without processing anything further
  1703. // on linux and mac, _exit has that effect
  1704. // however, on windows, _exit() still invokes CRT functions, unloads, and destructors
  1705. // so on windows, we need to use TerminateProcess
  1706. #if defined(AZ_PLATFORM_WINDOWS)
  1707. TerminateProcess(GetCurrentProcess(), exitCode);
  1708. #else
  1709. _exit(exitCode);
  1710. #endif
  1711. }
  1712. SAFE_DELETE(m_pConsoleDialog);
  1713. if (GetIEditor())
  1714. {
  1715. GetIEditor()->Notify(eNotify_OnQuit);
  1716. }
  1717. // if we're aborting due to an unexpected shutdown then don't call into objects that don't exist yet.
  1718. if ((gEnv) && (gEnv->pSystem) && (gEnv->pSystem->GetILevelSystem()))
  1719. {
  1720. gEnv->pSystem->GetILevelSystem()->UnloadLevel();
  1721. }
  1722. if (GetIEditor())
  1723. {
  1724. GetIEditor()->GetDocument()->DeleteTemporaryLevel();
  1725. }
  1726. m_bExiting = true;
  1727. HEAP_CHECK
  1728. ////////////////////////////////////////////////////////////////////////
  1729. // Executed directly before termination of the editor, just write a
  1730. // quick note to the log so that we can later see that the editor
  1731. // terminated flawlessly. Also delete temporary files.
  1732. ////////////////////////////////////////////////////////////////////////
  1733. WriteConfig();
  1734. if (m_pEditor)
  1735. {
  1736. // Ensure component entities are wiped prior to unloading plugins,
  1737. // since components may be implemented in those plugins.
  1738. AzToolsFramework::EditorEntityContextRequestBus::Broadcast(
  1739. &AzToolsFramework::EditorEntityContextRequestBus::Events::ResetEditorContext);
  1740. // vital, so that the Qt integration can unhook itself!
  1741. m_pEditor->UnloadPlugins();
  1742. m_pEditor->Uninitialize();
  1743. }
  1744. //////////////////////////////////////////////////////////////////////////
  1745. // Quick end for editor.
  1746. if (gEnv && gEnv->pSystem)
  1747. {
  1748. gEnv->pSystem->Quit();
  1749. SAFE_RELEASE(gEnv->pSystem);
  1750. }
  1751. //////////////////////////////////////////////////////////////////////////
  1752. if (m_pEditor)
  1753. {
  1754. m_pEditor->DeleteThis();
  1755. m_pEditor = nullptr;
  1756. }
  1757. // save accelerator manager configuration.
  1758. //m_AccelManager.SaveOnExit();
  1759. #ifdef WIN32
  1760. Gdiplus::GdiplusShutdown(m_gdiplusToken);
  1761. #endif
  1762. if (m_mutexApplication)
  1763. {
  1764. delete m_mutexApplication;
  1765. }
  1766. return 0;
  1767. }
  1768. bool CCryEditApp::IsWindowInForeground()
  1769. {
  1770. return Editor::EditorQtApplication::instance()->IsActive();
  1771. }
  1772. void CCryEditApp::DisableIdleProcessing()
  1773. {
  1774. m_disableIdleProcessingCounter++;
  1775. }
  1776. void CCryEditApp::EnableIdleProcessing()
  1777. {
  1778. m_disableIdleProcessingCounter--;
  1779. AZ_Assert(m_disableIdleProcessingCounter >= 0, "m_disableIdleProcessingCounter must be nonnegative");
  1780. }
  1781. bool CCryEditApp::OnIdle([[maybe_unused]] LONG lCount)
  1782. {
  1783. if (0 == m_disableIdleProcessingCounter)
  1784. {
  1785. return IdleProcessing(gSettings.backgroundUpdatePeriod == -1);
  1786. }
  1787. else
  1788. {
  1789. return false;
  1790. }
  1791. }
  1792. int CCryEditApp::IdleProcessing(bool bBackgroundUpdate)
  1793. {
  1794. AZ_Assert(m_disableIdleProcessingCounter == 0, "We should not be in IdleProcessing()");
  1795. //HEAP_CHECK
  1796. if (!MainWindow::instance())
  1797. {
  1798. return 0;
  1799. }
  1800. if (!GetIEditor()->GetSystem())
  1801. {
  1802. return 0;
  1803. }
  1804. // Ensure we don't get called re-entrantly
  1805. // This can occur when a nested Qt event loop fires (e.g. by way of a modal dialog calling exec)
  1806. if (m_idleProcessingRunning)
  1807. {
  1808. return 0;
  1809. }
  1810. QScopedValueRollback<bool> guard(m_idleProcessingRunning, true);
  1811. ////////////////////////////////////////////////////////////////////////
  1812. // Call the update function of the engine
  1813. ////////////////////////////////////////////////////////////////////////
  1814. if (m_bTestMode && !bBackgroundUpdate)
  1815. {
  1816. // Terminate process.
  1817. CLogFile::WriteLine("Editor: Terminate Process");
  1818. exit(0);
  1819. }
  1820. bool bIsAppWindow = IsWindowInForeground();
  1821. bool bActive = false;
  1822. int res = 0;
  1823. if (bIsAppWindow || m_bForceProcessIdle || m_bKeepEditorActive
  1824. // Automated tests must always keep the editor active, or they can get stuck
  1825. || m_bAutotestMode || m_bRunPythonTestScript)
  1826. {
  1827. res = 1;
  1828. bActive = true;
  1829. }
  1830. if (m_bForceProcessIdle && bIsAppWindow)
  1831. {
  1832. m_bForceProcessIdle = false;
  1833. }
  1834. // focus changed
  1835. if (m_bPrevActive != bActive)
  1836. {
  1837. GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_CHANGE_FOCUS, bActive, 0);
  1838. #if defined(AZ_PLATFORM_WINDOWS)
  1839. // This is required for the audio system to be notified of focus changes in the editor. After discussing it
  1840. // with the macOS team, they are working on unifying the system events between the editor and standalone
  1841. // launcher so this is only needed on windows.
  1842. if (bActive)
  1843. {
  1844. AzFramework::WindowsLifecycleEvents::Bus::Broadcast(&AzFramework::WindowsLifecycleEvents::Bus::Events::OnSetFocus);
  1845. }
  1846. else
  1847. {
  1848. AzFramework::WindowsLifecycleEvents::Bus::Broadcast(&AzFramework::WindowsLifecycleEvents::Bus::Events::OnKillFocus);
  1849. }
  1850. #endif
  1851. }
  1852. m_bPrevActive = bActive;
  1853. // Tick System Events, even in the background
  1854. AZ::ComponentApplicationRequests* componentApplicationRequests = AZ::Interface<AZ::ComponentApplicationRequests>::Get();
  1855. if (componentApplicationRequests)
  1856. {
  1857. AZ::ComponentApplication* componentApplication = componentApplicationRequests->GetApplication();
  1858. if (componentApplication)
  1859. {
  1860. componentApplication->TickSystem();
  1861. }
  1862. }
  1863. // Don't tick application if we're doing idle processing during an assert.
  1864. const bool isErrorWindowVisible = (gEnv && gEnv->pSystem->IsAssertDialogVisible());
  1865. if (isErrorWindowVisible)
  1866. {
  1867. if (m_pEditor)
  1868. {
  1869. m_pEditor->Update();
  1870. }
  1871. }
  1872. else if (bActive || (bBackgroundUpdate && !bIsAppWindow))
  1873. {
  1874. // Update Game
  1875. GetIEditor()->GetGameEngine()->Update();
  1876. if (!GetIEditor()->IsInGameMode())
  1877. {
  1878. if (m_pEditor)
  1879. {
  1880. m_pEditor->Update();
  1881. }
  1882. GetIEditor()->Notify(eNotify_OnIdleUpdate);
  1883. }
  1884. }
  1885. else
  1886. {
  1887. if (GetIEditor()->GetSystem() && GetIEditor()->GetSystem()->GetILog())
  1888. {
  1889. GetIEditor()->GetSystem()->GetILog()->Update(); // print messages from other threads
  1890. }
  1891. // If we're backgrounded and not fully background updating, idle to rate limit SystemTick
  1892. static AZ::TimeMs sTimeLastMs = AZ::GetRealElapsedTimeMs();
  1893. const int64_t maxFrameTimeMs = ed_backgroundSystemTickCap;
  1894. if (maxFrameTimeMs > 0)
  1895. {
  1896. const int64_t maxElapsedTimeMs = maxFrameTimeMs + static_cast<int64_t>(sTimeLastMs);
  1897. const int64_t realElapsedTimeMs = static_cast<int64_t>(AZ::GetRealElapsedTimeMs());
  1898. if (maxElapsedTimeMs > realElapsedTimeMs)
  1899. {
  1900. CrySleep(aznumeric_cast<unsigned int>(maxElapsedTimeMs - realElapsedTimeMs));
  1901. }
  1902. }
  1903. sTimeLastMs = AZ::GetRealElapsedTimeMs();
  1904. }
  1905. DisplayLevelLoadErrors();
  1906. if (CConsoleSCB::GetCreatedInstance())
  1907. {
  1908. CConsoleSCB::GetCreatedInstance()->FlushText();
  1909. }
  1910. return res;
  1911. }
  1912. void CCryEditApp::DisplayLevelLoadErrors()
  1913. {
  1914. CCryEditDoc* currentLevel = GetIEditor()->GetDocument();
  1915. if (currentLevel && currentLevel->IsDocumentReady() && !m_levelErrorsHaveBeenDisplayed)
  1916. {
  1917. // Generally it takes a few idle updates for meshes to load and be processed by their components. This value
  1918. // was picked based on examining when mesh components are updated and their materials are checked for
  1919. // errors (2 updates) plus one more for good luck.
  1920. const int IDLE_FRAMES_TO_WAIT = 3;
  1921. ++m_numBeforeDisplayErrorFrames;
  1922. if (m_numBeforeDisplayErrorFrames > IDLE_FRAMES_TO_WAIT)
  1923. {
  1924. GetIEditor()->CommitLevelErrorReport();
  1925. GetIEditor()->GetErrorReport()->Display();
  1926. m_numBeforeDisplayErrorFrames = 0;
  1927. m_levelErrorsHaveBeenDisplayed = true;
  1928. }
  1929. }
  1930. }
  1931. //////////////////////////////////////////////////////////////////////////
  1932. void CCryEditApp::OnEditHold()
  1933. {
  1934. GetIEditor()->GetDocument()->Hold(HOLD_FETCH_FILE);
  1935. }
  1936. //////////////////////////////////////////////////////////////////////////
  1937. void CCryEditApp::OnEditFetch()
  1938. {
  1939. GetIEditor()->GetDocument()->Fetch(HOLD_FETCH_FILE);
  1940. }
  1941. void CCryEditApp::OnMoveObject()
  1942. {
  1943. ////////////////////////////////////////////////////////////////////////
  1944. // Move the selected object to the marker position
  1945. ////////////////////////////////////////////////////////////////////////
  1946. }
  1947. void CCryEditApp::OnRenameObj()
  1948. {
  1949. }
  1950. void CCryEditApp::OnViewSwitchToGame()
  1951. {
  1952. if (IsInPreviewMode())
  1953. {
  1954. return;
  1955. }
  1956. // If switching on game mode...
  1957. if (!GetIEditor()->IsInGameMode())
  1958. {
  1959. // If simulation mode is enabled...
  1960. uint32 flags = GetIEditor()->GetDisplaySettings()->GetSettings();
  1961. if (flags & SETTINGS_PHYSICS)
  1962. {
  1963. // Disable simulation mode
  1964. OnSwitchPhysics();
  1965. // Schedule for next frame to enable game mode
  1966. AZ::Interface<AZ::IEventScheduler>::Get()->AddCallback(
  1967. [this] { OnViewSwitchToGame(); },
  1968. AZ::Name("Enable Game Mode"), AZ::Time::ZeroTimeMs);
  1969. return;
  1970. }
  1971. }
  1972. // close all open menus
  1973. auto activePopup = qApp->activePopupWidget();
  1974. if (qobject_cast<QMenu*>(activePopup))
  1975. {
  1976. activePopup->hide();
  1977. }
  1978. // TODO: Add your command handler code here
  1979. bool inGame = !GetIEditor()->IsInGameMode();
  1980. GetIEditor()->SetInGameMode(inGame);
  1981. }
  1982. void CCryEditApp::OnViewSwitchToGameFullScreen()
  1983. {
  1984. ed_previewGameInFullscreen_once = true;
  1985. OnViewSwitchToGame();
  1986. }
  1987. //////////////////////////////////////////////////////////////////////////
  1988. void CCryEditApp::OnEditLevelData()
  1989. {
  1990. auto dir = QFileInfo(GetIEditor()->GetDocument()->GetLevelPathName()).dir();
  1991. CFileUtil::EditTextFile(dir.absoluteFilePath("leveldata.xml").toUtf8().data());
  1992. }
  1993. //////////////////////////////////////////////////////////////////////////
  1994. void CCryEditApp::OnFileEditLogFile()
  1995. {
  1996. QString file = CLogFile::GetLogFileName();
  1997. QString fullPathName = Path::GamePathToFullPath(file);
  1998. QDesktopServices::openUrl(QUrl::fromLocalFile(fullPathName));
  1999. }
  2000. //////////////////////////////////////////////////////////////////////////
  2001. void CCryEditApp::OnFileEditEditorini()
  2002. {
  2003. CFileUtil::EditTextFile(EDITOR_CFG_FILE);
  2004. }
  2005. void CCryEditApp::OnPreferences()
  2006. {
  2007. /*
  2008. //////////////////////////////////////////////////////////////////////////////
  2009. // Accels edit by CPropertyPage
  2010. CAcceleratorManager tmpAccelManager;
  2011. tmpAccelManager = m_AccelManager;
  2012. CAccelMapPage page(&tmpAccelManager);
  2013. CPropertySheet sheet;
  2014. sheet.SetTitle( _T("Preferences") );
  2015. sheet.AddPage(&page);
  2016. if (sheet.DoModal() == IDOK) {
  2017. m_AccelManager = tmpAccelManager;
  2018. m_AccelManager.UpdateWndTable();
  2019. }
  2020. */
  2021. }
  2022. void CCryEditApp::OnOpenProjectManagerSettings()
  2023. {
  2024. OpenProjectManager("UpdateProject");
  2025. }
  2026. void CCryEditApp::OnOpenProjectManagerNew()
  2027. {
  2028. OpenProjectManager("CreateProject");
  2029. }
  2030. void CCryEditApp::OnOpenProjectManager()
  2031. {
  2032. OpenProjectManager("Projects");
  2033. }
  2034. void CCryEditApp::OpenProjectManager(const AZStd::string& screen)
  2035. {
  2036. // provide the current project path for in case we want to update the project
  2037. AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath();
  2038. const AZStd::vector<AZStd::string> commandLineOptions {
  2039. "--screen", screen,
  2040. "--project-path", AZStd::string::format(R"("%s")", projectPath.c_str()) };
  2041. bool launchSuccess = AzFramework::ProjectManager::LaunchProjectManager(commandLineOptions);
  2042. if (!launchSuccess)
  2043. {
  2044. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Failed to launch O3DE Project Manager"), QObject::tr("Failed to find or start the O3dE Project Manager"));
  2045. }
  2046. }
  2047. //////////////////////////////////////////////////////////////////////////
  2048. void CCryEditApp::OnUndo()
  2049. {
  2050. //GetIEditor()->GetObjectManager()->UndoLastOp();
  2051. GetIEditor()->Undo();
  2052. }
  2053. //////////////////////////////////////////////////////////////////////////
  2054. void CCryEditApp::OnRedo()
  2055. {
  2056. GetIEditor()->Redo();
  2057. }
  2058. //////////////////////////////////////////////////////////////////////////
  2059. void CCryEditApp::OnUpdateRedo(QAction* action)
  2060. {
  2061. if (GetIEditor()->GetUndoManager()->IsHaveRedo())
  2062. {
  2063. action->setEnabled(true);
  2064. }
  2065. else
  2066. {
  2067. action->setEnabled(false);
  2068. }
  2069. }
  2070. //////////////////////////////////////////////////////////////////////////
  2071. void CCryEditApp::OnUpdateUndo(QAction* action)
  2072. {
  2073. if (GetIEditor()->GetUndoManager()->IsHaveUndo())
  2074. {
  2075. action->setEnabled(true);
  2076. }
  2077. else
  2078. {
  2079. action->setEnabled(false);
  2080. }
  2081. }
  2082. //////////////////////////////////////////////////////////////////////////
  2083. void CCryEditApp::OnSwitchPhysics()
  2084. {
  2085. if (GetIEditor()->GetGameEngine() && !GetIEditor()->GetGameEngine()->GetSimulationMode() && !GetIEditor()->GetGameEngine()->IsLevelLoaded())
  2086. {
  2087. // Don't allow physics to be toggled on if we haven't loaded a level yet
  2088. return;
  2089. }
  2090. QWaitCursor wait;
  2091. GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_SWITCH_START, 0, 0);
  2092. uint32 flags = GetIEditor()->GetDisplaySettings()->GetSettings();
  2093. if (flags & SETTINGS_PHYSICS)
  2094. {
  2095. flags &= ~SETTINGS_PHYSICS;
  2096. }
  2097. else
  2098. {
  2099. flags |= SETTINGS_PHYSICS;
  2100. }
  2101. GetIEditor()->GetDisplaySettings()->SetSettings(flags);
  2102. if ((flags & SETTINGS_PHYSICS) == 0)
  2103. {
  2104. GetIEditor()->GetGameEngine()->SetSimulationMode(false);
  2105. GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_CHANGED, 0, 0);
  2106. }
  2107. else
  2108. {
  2109. GetIEditor()->GetGameEngine()->SetSimulationMode(true);
  2110. GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_CHANGED, 1, 0);
  2111. }
  2112. GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_SWITCH_END, 0, 0);
  2113. }
  2114. //////////////////////////////////////////////////////////////////////////
  2115. void CCryEditApp::OnSwitchPhysicsUpdate(QAction* action)
  2116. {
  2117. Q_ASSERT(action->isCheckable());
  2118. action->setChecked(GetIEditor()->GetGameEngine()->GetSimulationMode());
  2119. }
  2120. //////////////////////////////////////////////////////////////////////////
  2121. void CCryEditApp::OnSyncPlayer()
  2122. {
  2123. GetIEditor()->GetGameEngine()->SyncPlayerPosition(!GetIEditor()->GetGameEngine()->IsSyncPlayerPosition());
  2124. }
  2125. //////////////////////////////////////////////////////////////////////////
  2126. void CCryEditApp::OnSyncPlayerUpdate(QAction* action)
  2127. {
  2128. Q_ASSERT(action->isCheckable());
  2129. action->setChecked(!GetIEditor()->GetGameEngine()->IsSyncPlayerPosition());
  2130. }
  2131. void CCryEditApp::OnUpdateNonGameMode(QAction* action)
  2132. {
  2133. action->setEnabled(!GetIEditor()->IsInGameMode());
  2134. }
  2135. void CCryEditApp::OnUpdateNewLevel(QAction* action)
  2136. {
  2137. action->setEnabled(true);
  2138. }
  2139. void CCryEditApp::OnUpdatePlayGame(QAction* action)
  2140. {
  2141. action->setEnabled(GetIEditor()->IsLevelLoaded());
  2142. }
  2143. //////////////////////////////////////////////////////////////////////////
  2144. CCryEditApp::ECreateLevelResult CCryEditApp::CreateLevel(const QString& templateName, const QString& levelName, QString& fullyQualifiedLevelName /* ={} */)
  2145. {
  2146. // If we are creating a new level and we're in simulate mode, then switch it off before we do anything else
  2147. if (GetIEditor()->GetGameEngine() && GetIEditor()->GetGameEngine()->GetSimulationMode())
  2148. {
  2149. // Preserve the modified flag, we don't want this switch of physics to change that flag
  2150. bool bIsDocModified = GetIEditor()->GetDocument()->IsModified();
  2151. OnSwitchPhysics();
  2152. GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified);
  2153. auto* rootSpawnableInterface = AzFramework::RootSpawnableInterface::Get();
  2154. if (rootSpawnableInterface)
  2155. {
  2156. rootSpawnableInterface->ProcessSpawnableQueue();
  2157. }
  2158. }
  2159. const QScopedValueRollback<bool> rollback(m_creatingNewLevel);
  2160. m_creatingNewLevel = true;
  2161. GetIEditor()->Notify(eNotify_OnBeginCreate);
  2162. CrySystemEventBus::Broadcast(&CrySystemEventBus::Events::OnCryEditorBeginCreate);
  2163. QString currentLevel = GetIEditor()->GetLevelFolder();
  2164. if (!currentLevel.isEmpty())
  2165. {
  2166. GetIEditor()->GetSystem()->GetIPak()->ClosePacks(currentLevel.toUtf8().data());
  2167. }
  2168. QString cryFileName = levelName.mid(levelName.lastIndexOf('/') + 1, levelName.length() - levelName.lastIndexOf('/') + 1);
  2169. QString levelPath = QStringLiteral("%1/Levels/%2/").arg(Path::GetEditingGameDataFolder().c_str(), levelName);
  2170. fullyQualifiedLevelName = levelPath + cryFileName + EditorUtils::LevelFile::GetDefaultFileExtension();
  2171. //_MAX_PATH includes null terminator, so we actually want to cap at _MAX_PATH-1
  2172. if (fullyQualifiedLevelName.length() >= _MAX_PATH-1)
  2173. {
  2174. GetIEditor()->Notify(eNotify_OnEndCreate);
  2175. return ECLR_MAX_PATH_EXCEEDED;
  2176. }
  2177. // Does the directory already exist ?
  2178. if (QFileInfo(levelPath).exists())
  2179. {
  2180. GetIEditor()->Notify(eNotify_OnEndCreate);
  2181. return ECLR_ALREADY_EXISTS;
  2182. }
  2183. // Create the directory
  2184. CLogFile::WriteLine("Creating level directory");
  2185. if (!CFileUtil::CreatePath(levelPath))
  2186. {
  2187. GetIEditor()->Notify(eNotify_OnEndCreate);
  2188. return ECLR_DIR_CREATION_FAILED;
  2189. }
  2190. if (GetIEditor()->GetDocument()->IsDocumentReady())
  2191. {
  2192. m_pDocManager->OnFileNew();
  2193. }
  2194. ICVar* sv_map = gEnv->pConsole->GetCVar("sv_map");
  2195. if (sv_map)
  2196. {
  2197. sv_map->Set(levelName.toUtf8().data());
  2198. }
  2199. GetIEditor()->GetDocument()->InitEmptyLevel(128, 1);
  2200. GetIEditor()->SetStatusText("Creating Level...");
  2201. // Save the document to this folder
  2202. GetIEditor()->GetDocument()->SetPathName(fullyQualifiedLevelName);
  2203. GetIEditor()->GetGameEngine()->SetLevelPath(levelPath);
  2204. auto* service = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get();
  2205. if (service)
  2206. {
  2207. const AZStd::string templateNameString(templateName.toUtf8().constData());
  2208. service->CreateNewLevelPrefab(fullyQualifiedLevelName.toUtf8().constData(), templateNameString);
  2209. }
  2210. if (GetIEditor()->GetDocument()->Save())
  2211. {
  2212. GetIEditor()->GetGameEngine()->LoadLevel(true, true);
  2213. GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0);
  2214. GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_END, 0, 0);
  2215. }
  2216. GetIEditor()->GetDocument()->CreateDefaultLevelAssets(128, 1);
  2217. GetIEditor()->GetDocument()->SetDocumentReady(true);
  2218. GetIEditor()->SetStatusText("Ready");
  2219. // At the end of the creating level process, add this level to the MRU list
  2220. CCryEditApp::instance()->AddToRecentFileList(fullyQualifiedLevelName);
  2221. GetIEditor()->Notify(eNotify_OnEndCreate);
  2222. CrySystemEventBus::Broadcast(&CrySystemEventBus::Events::OnCryEditorEndCreate);
  2223. return ECLR_OK;
  2224. }
  2225. //////////////////////////////////////////////////////////////////////////
  2226. void CCryEditApp::OnCreateLevel()
  2227. {
  2228. if (m_creatingNewLevel)
  2229. {
  2230. return;
  2231. }
  2232. bool wasCreateLevelOperationCancelled = false;
  2233. bool isNewLevelCreationSuccess = false;
  2234. // This will show the new level dialog until a valid input has been entered by the user or until the user click cancel
  2235. while (!isNewLevelCreationSuccess && !wasCreateLevelOperationCancelled)
  2236. {
  2237. wasCreateLevelOperationCancelled = false;
  2238. isNewLevelCreationSuccess = CreateLevel(wasCreateLevelOperationCancelled);
  2239. }
  2240. }
  2241. //////////////////////////////////////////////////////////////////////////
  2242. bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled)
  2243. {
  2244. bool bIsDocModified = GetIEditor()->GetDocument()->IsModified();
  2245. if (GetIEditor()->GetDocument()->IsDocumentReady() && bIsDocModified)
  2246. {
  2247. auto* prefabEditorEntityOwnershipInterface = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get();
  2248. auto* prefabIntegrationInterface = AZ::Interface<AzToolsFramework::Prefab::PrefabIntegrationInterface>::Get();
  2249. AZ_Assert(prefabEditorEntityOwnershipInterface != nullptr, "PrefabEditorEntityOwnershipInterface is not found.");
  2250. AZ_Assert(prefabIntegrationInterface != nullptr, "PrefabIntegrationInterface is not found.");
  2251. if (prefabEditorEntityOwnershipInterface == nullptr || prefabIntegrationInterface == nullptr)
  2252. {
  2253. return false;
  2254. }
  2255. AzToolsFramework::Prefab::TemplateId rootPrefabTemplateId = prefabEditorEntityOwnershipInterface->GetRootPrefabTemplateId();
  2256. int prefabSaveSelection = prefabIntegrationInterface->HandleRootPrefabClosure(rootPrefabTemplateId);
  2257. // In order to get the accept and reject codes of QDialog and QDialogButtonBox aligned, we do (1-prefabSaveSelection) here.
  2258. // For example, QDialog::Rejected(0) is emitted when dialog is closed. But the int value corresponds to
  2259. // QDialogButtonBox::AcceptRole(0).
  2260. switch (1 - prefabSaveSelection)
  2261. {
  2262. case QDialogButtonBox::AcceptRole:
  2263. bIsDocModified = false;
  2264. break;
  2265. case QDialogButtonBox::RejectRole:
  2266. wasCreateLevelOperationCancelled = true;
  2267. return false;
  2268. case QDialogButtonBox::InvalidRole:
  2269. // Set Modified flag to false to prevent show Save unchanged dialog again
  2270. GetIEditor()->GetDocument()->SetModifiedFlag(false);
  2271. break;
  2272. }
  2273. }
  2274. const char* temporaryLevelName = GetIEditor()->GetDocument()->GetTemporaryLevelName();
  2275. CNewLevelDialog dlg;
  2276. dlg.m_level = "";
  2277. if (dlg.exec() != QDialog::Accepted)
  2278. {
  2279. wasCreateLevelOperationCancelled = true;
  2280. GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified);
  2281. return false;
  2282. }
  2283. if (!GetIEditor()->GetLevelIndependentFileMan()->PromptChangedFiles())
  2284. {
  2285. return false;
  2286. }
  2287. QString levelNameWithPath = dlg.GetLevel();
  2288. QString levelName = levelNameWithPath.mid(levelNameWithPath.lastIndexOf('/') + 1);
  2289. if (levelName == temporaryLevelName && GetIEditor()->GetLevelName() != temporaryLevelName)
  2290. {
  2291. GetIEditor()->GetDocument()->DeleteTemporaryLevel();
  2292. }
  2293. if (levelName.length() == 0 || !AZ::StringFunc::Path::IsValid(levelName.toUtf8().data()))
  2294. {
  2295. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Level name is invalid, please choose another name."));
  2296. return false;
  2297. }
  2298. //Verify that we are not using the temporary level name
  2299. if (QString::compare(levelName, temporaryLevelName) == 0)
  2300. {
  2301. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Please enter a level name that is different from the temporary name."));
  2302. return false;
  2303. }
  2304. // We're about to start creating a level, so start recording errors to display at the end.
  2305. GetIEditor()->StartLevelErrorReportRecording();
  2306. QString fullyQualifiedLevelName;
  2307. ECreateLevelResult result = CreateLevel(dlg.GetTemplateName(), levelNameWithPath, fullyQualifiedLevelName);
  2308. if (result == ECLR_ALREADY_EXISTS)
  2309. {
  2310. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Level with this name already exists, please choose another name."));
  2311. return false;
  2312. }
  2313. else if (result == ECLR_DIR_CREATION_FAILED)
  2314. {
  2315. QString szLevelRoot = QStringLiteral("%1\\Levels\\%2").arg(Path::GetEditingGameDataFolder().c_str(), levelName);
  2316. QByteArray windowsErrorMessage(ERROR_LEN, 0);
  2317. QByteArray cwd(ERROR_LEN, 0);
  2318. DWORD dw = GetLastError();
  2319. #ifdef WIN32
  2320. wchar_t windowsErrorMessageW[ERROR_LEN];
  2321. windowsErrorMessageW[0] = L'\0';
  2322. FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  2323. nullptr,
  2324. dw,
  2325. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  2326. windowsErrorMessageW,
  2327. ERROR_LEN, nullptr);
  2328. _getcwd(cwd.data(), cwd.length());
  2329. AZStd::to_string(windowsErrorMessage.data(), ERROR_LEN, windowsErrorMessageW);
  2330. #else
  2331. windowsErrorMessage = strerror(dw);
  2332. cwd = QDir::currentPath().toUtf8();
  2333. #endif
  2334. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Failed to create level directory: %1\n Error: %2\nCurrent Path: %3").arg(szLevelRoot, windowsErrorMessage, cwd));
  2335. return false;
  2336. }
  2337. else if (result == ECLR_MAX_PATH_EXCEEDED)
  2338. {
  2339. QFileInfo info(fullyQualifiedLevelName);
  2340. const AZStd::string rawProjectDirectory = Path::GetEditingGameDataFolder();
  2341. const QString projectDirectory = QDir::toNativeSeparators(QString::fromUtf8(rawProjectDirectory.data(), static_cast<int>(rawProjectDirectory.size())));
  2342. const QString elidedLevelName = QStringLiteral("%1...%2").arg(levelName.left(10)).arg(levelName.right(10));
  2343. const QString elidedLevelFileName = QStringLiteral("%1...%2").arg(info.fileName().left(10)).arg(info.fileName().right(10));
  2344. const QString message = QObject::tr(
  2345. "The fully-qualified path for the new level exceeds the maximum supported path length of %1 characters (it's %2 characters long). Please choose a smaller name.\n\n"
  2346. "The fully-qualified path is made up of the project folder (\"%3\", %4 characters), the \"Levels\" sub-folder, a folder named for the level (\"%5\", %6 characters) and the level file (\"%7\", %8 characters), plus necessary separators.\n\n"
  2347. "Please also note that on most platforms, individual components of the path (folder/file names can't exceed approximately 255 characters)\n\n"
  2348. "Click \"Copy to Clipboard\" to copy the fully-qualified name and close this message.")
  2349. .arg(_MAX_PATH - 1).arg(fullyQualifiedLevelName.size())
  2350. .arg(projectDirectory).arg(projectDirectory.size())
  2351. .arg(elidedLevelName).arg(levelName.size())
  2352. .arg(elidedLevelFileName).arg(info.fileName().size());
  2353. QMessageBox messageBox(QMessageBox::Critical, QString(), message, QMessageBox::Ok, AzToolsFramework::GetActiveWindow());
  2354. QPushButton* copyButton = messageBox.addButton(QObject::tr("Copy to Clipboard"), QMessageBox::ActionRole);
  2355. QObject::connect(copyButton, &QPushButton::pressed, this, [fullyQualifiedLevelName]() { QGuiApplication::clipboard()->setText(fullyQualifiedLevelName); });
  2356. messageBox.exec();
  2357. return false;
  2358. }
  2359. // force the level being rendered at least once
  2360. m_bForceProcessIdle = true;
  2361. m_levelErrorsHaveBeenDisplayed = false;
  2362. return true;
  2363. }
  2364. //////////////////////////////////////////////////////////////////////////
  2365. void CCryEditApp::OnOpenLevel()
  2366. {
  2367. CLevelFileDialog levelFileDialog(true);
  2368. levelFileDialog.show();
  2369. levelFileDialog.adjustSize();
  2370. if (levelFileDialog.exec() == QDialog::Accepted)
  2371. {
  2372. OpenDocumentFile(levelFileDialog.GetFileName().toUtf8().data(), true, COpenSameLevelOptions::ReopenLevelIfSame);
  2373. }
  2374. }
  2375. //////////////////////////////////////////////////////////////////////////
  2376. CCryEditDoc* CCryEditApp::OpenDocumentFile(const char* filename, bool addToMostRecentFileList, COpenSameLevelOptions openSameLevelOptions)
  2377. {
  2378. if (m_openingLevel)
  2379. {
  2380. return GetIEditor()->GetDocument();
  2381. }
  2382. // If we are loading and we're in simulate mode, then switch it off before we do anything else
  2383. if (GetIEditor()->GetGameEngine() && GetIEditor()->GetGameEngine()->GetSimulationMode())
  2384. {
  2385. // Preserve the modified flag, we don't want this switch of physics to change that flag
  2386. bool bIsDocModified = GetIEditor()->GetDocument()->IsModified();
  2387. OnSwitchPhysics();
  2388. GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified);
  2389. auto* rootSpawnableInterface = AzFramework::RootSpawnableInterface::Get();
  2390. if (rootSpawnableInterface)
  2391. {
  2392. rootSpawnableInterface->ProcessSpawnableQueue();
  2393. }
  2394. }
  2395. // We're about to start loading a level, so start recording errors to display at the end.
  2396. GetIEditor()->StartLevelErrorReportRecording();
  2397. const QScopedValueRollback<bool> rollback(m_openingLevel, true);
  2398. MainWindow::instance()->menuBar()->setEnabled(false);
  2399. CCryEditDoc* doc = nullptr;
  2400. bool bVisible = false;
  2401. bool bTriggerConsole = false;
  2402. doc = GetIEditor()->GetDocument();
  2403. bVisible = GetIEditor()->ShowConsole(true);
  2404. bTriggerConsole = true;
  2405. if (GetIEditor()->GetLevelIndependentFileMan()->PromptChangedFiles())
  2406. {
  2407. SandboxEditor::StartupTraceHandler openDocTraceHandler;
  2408. openDocTraceHandler.StartCollection();
  2409. if (m_bAutotestMode)
  2410. {
  2411. openDocTraceHandler.SetShowWindow(false);
  2412. }
  2413. // in this case, we set addToMostRecentFileList to always be true because adding files to the MRU list
  2414. // automatically culls duplicate and normalizes paths anyway
  2415. m_pDocManager->OpenDocumentFile(filename, addToMostRecentFileList, openSameLevelOptions);
  2416. if (openDocTraceHandler.HasAnyErrors())
  2417. {
  2418. doc->SetHasErrors();
  2419. }
  2420. }
  2421. if (bTriggerConsole)
  2422. {
  2423. GetIEditor()->ShowConsole(bVisible);
  2424. }
  2425. MainWindow::instance()->menuBar()->setEnabled(true);
  2426. m_levelErrorsHaveBeenDisplayed = false;
  2427. return doc; // the API wants a CDocument* to be returned. It seems not to be used, though, in our current state.
  2428. }
  2429. //////////////////////////////////////////////////////////////////////////
  2430. void CCryEditApp::OnResourcesReduceworkingset()
  2431. {
  2432. #ifdef WIN32 // no such thing on macOS
  2433. SetProcessWorkingSetSize(GetCurrentProcess(), std::numeric_limits<SIZE_T>::max(), std::numeric_limits<SIZE_T>::max());
  2434. #endif
  2435. }
  2436. void CCryEditApp::OnUpdateWireframe(QAction* action)
  2437. {
  2438. Q_ASSERT(action->isCheckable());
  2439. int nWireframe(R_SOLID_MODE);
  2440. ICVar* r_wireframe(gEnv->pConsole->GetCVar("r_wireframe"));
  2441. if (r_wireframe)
  2442. {
  2443. nWireframe = r_wireframe->GetIVal();
  2444. }
  2445. action->setChecked(nWireframe == R_WIREFRAME_MODE);
  2446. }
  2447. //////////////////////////////////////////////////////////////////////////
  2448. void CCryEditApp::OnViewConfigureLayout()
  2449. {
  2450. if (GetIEditor()->IsInGameMode())
  2451. {
  2452. // you may not change your viewports while game mode is running.
  2453. CryLog("You may not change viewport configuration while in game mode.");
  2454. return;
  2455. }
  2456. CLayoutWnd* layout = GetIEditor()->GetViewManager()->GetLayout();
  2457. if (layout)
  2458. {
  2459. CLayoutConfigDialog dlg;
  2460. dlg.SetLayout(layout->GetLayout());
  2461. if (dlg.exec() == QDialog::Accepted)
  2462. {
  2463. // Will kill this Pane. so must be last line in this function.
  2464. layout->CreateLayout(dlg.GetLayout());
  2465. }
  2466. }
  2467. }
  2468. //////////////////////////////////////////////////////////////////////////
  2469. void CCryEditApp::OnToolsLogMemoryUsage()
  2470. {
  2471. gEnv->pConsole->ExecuteString("SaveLevelStats");
  2472. }
  2473. //////////////////////////////////////////////////////////////////////////
  2474. void CCryEditApp::OnCustomizeKeyboard()
  2475. {
  2476. MainWindow::instance()->OnCustomizeToolbar();
  2477. }
  2478. //////////////////////////////////////////////////////////////////////////
  2479. void CCryEditApp::OnToolsScriptHelp()
  2480. {
  2481. AzToolsFramework::CScriptHelpDialog::GetInstance()->show();
  2482. }
  2483. //////////////////////////////////////////////////////////////////////////
  2484. void CCryEditApp::OnViewCycle2dviewport()
  2485. {
  2486. GetIEditor()->GetViewManager()->Cycle2DViewport();
  2487. }
  2488. //////////////////////////////////////////////////////////////////////////
  2489. void CCryEditApp::OnDisplayGotoPosition()
  2490. {
  2491. GotoPositionDialog dialog;
  2492. dialog.exec();
  2493. }
  2494. //////////////////////////////////////////////////////////////////////////
  2495. void CCryEditApp::OnFileSavelevelresources()
  2496. {
  2497. // TODO - Remove this?
  2498. }
  2499. //////////////////////////////////////////////////////////////////////////
  2500. void CCryEditApp::OnClearRegistryData()
  2501. {
  2502. if (QMessageBox::warning(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Clear all sandbox registry data ?"),
  2503. QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
  2504. {
  2505. QSettings settings;
  2506. settings.clear();
  2507. }
  2508. }
  2509. //////////////////////////////////////////////////////////////////////////
  2510. void CCryEditApp::OnToolsPreferences()
  2511. {
  2512. EditorPreferencesDialog dlg(MainWindow::instance());
  2513. dlg.exec();
  2514. }
  2515. //////////////////////////////////////////////////////////////////////////
  2516. void CCryEditApp::OnSwitchToSequenceCamera()
  2517. {
  2518. }
  2519. //////////////////////////////////////////////////////////////////////////
  2520. void CCryEditApp::OnUpdateSwitchToSequenceCamera(QAction* action)
  2521. {
  2522. Q_ASSERT(action->isCheckable());
  2523. {
  2524. action->setEnabled(false);
  2525. }
  2526. }
  2527. //////////////////////////////////////////////////////////////////////////
  2528. void CCryEditApp::OnSwitchToSelectedcamera()
  2529. {
  2530. }
  2531. //////////////////////////////////////////////////////////////////////////
  2532. void CCryEditApp::OnUpdateSwitchToSelectedCamera(QAction* action)
  2533. {
  2534. Q_ASSERT(action->isCheckable());
  2535. {
  2536. action->setEnabled(false);
  2537. }
  2538. }
  2539. //////////////////////////////////////////////////////////////////////////
  2540. void CCryEditApp::OnSwitchcameraNext()
  2541. {
  2542. }
  2543. //////////////////////////////////////////////////////////////////////////
  2544. void CCryEditApp::OnOpenAssetBrowserView()
  2545. {
  2546. QtViewPaneManager::instance()->OpenPane(LyViewPane::AssetBrowser);
  2547. }
  2548. //////////////////////////////////////////////////////////////////////////
  2549. void CCryEditApp::OnOpenTrackView()
  2550. {
  2551. QtViewPaneManager::instance()->OpenPane(LyViewPane::TrackView);
  2552. }
  2553. //////////////////////////////////////////////////////////////////////////
  2554. void CCryEditApp::OnOpenAudioControlsEditor()
  2555. {
  2556. QtViewPaneManager::instance()->OpenPane(LyViewPane::AudioControlsEditor);
  2557. }
  2558. //////////////////////////////////////////////////////////////////////////
  2559. void CCryEditApp::OnOpenUICanvasEditor()
  2560. {
  2561. QtViewPaneManager::instance()->OpenPane(LyViewPane::UiEditor);
  2562. }
  2563. //////////////////////////////////////////////////////////////////////////
  2564. RecentFileList* CCryEditApp::GetRecentFileList()
  2565. {
  2566. static RecentFileList list;
  2567. return &list;
  2568. };
  2569. //////////////////////////////////////////////////////////////////////////
  2570. void CCryEditApp::AddToRecentFileList(const QString& lpszPathName)
  2571. {
  2572. // In later MFC implementations (WINVER >= 0x0601) files must exist before they can be added to the recent files list.
  2573. // Here we override the new CWinApp::AddToRecentFileList code with the old implementation to remove this requirement.
  2574. if (IsInAutotestMode())
  2575. {
  2576. // Never add to the recent file list when in auto test mode
  2577. // This would cause issues for devs running tests locally impacting their normal workflows/setups
  2578. return;
  2579. }
  2580. if (GetRecentFileList())
  2581. {
  2582. GetRecentFileList()->Add(lpszPathName);
  2583. }
  2584. // write the list immediately so it will be remembered even after a crash
  2585. if (GetRecentFileList())
  2586. {
  2587. GetRecentFileList()->WriteList();
  2588. }
  2589. else
  2590. {
  2591. CLogFile::WriteLine("ERROR: Recent File List is NULL!");
  2592. }
  2593. }
  2594. //////////////////////////////////////////////////////////////////////////
  2595. bool CCryEditApp::IsInRegularEditorMode()
  2596. {
  2597. return !IsInTestMode() && !IsInPreviewMode()
  2598. && !IsInConsoleMode() && !IsInLevelLoadTestMode();
  2599. }
  2600. void CCryEditApp::SetEditorWindowTitle(QString sTitleStr, QString sPreTitleStr, QString sPostTitleStr)
  2601. {
  2602. if (MainWindow::instance() || m_pConsoleDialog)
  2603. {
  2604. if (sTitleStr.isEmpty())
  2605. {
  2606. sTitleStr = QObject::tr("O3DE Editor [%1]").arg(FormatVersion(m_pEditor->GetFileVersion()));
  2607. }
  2608. if (!sPreTitleStr.isEmpty())
  2609. {
  2610. sTitleStr.insert(sTitleStr.length(), QStringLiteral(" - %1").arg(sPreTitleStr));
  2611. }
  2612. if (!sPostTitleStr.isEmpty())
  2613. {
  2614. sTitleStr.insert(sTitleStr.length(), QStringLiteral(" - %1").arg(sPostTitleStr));
  2615. }
  2616. MainWindow::instance()->setWindowTitle(sTitleStr);
  2617. if (m_pConsoleDialog)
  2618. {
  2619. m_pConsoleDialog->setWindowTitle(sTitleStr);
  2620. }
  2621. }
  2622. }
  2623. CMainFrame * CCryEditApp::GetMainFrame() const
  2624. {
  2625. return MainWindow::instance()->GetOldMainFrame();
  2626. }
  2627. void CCryEditApp::OpenExternalLuaDebugger(AZStd::string_view luaDebuggerUri, AZStd::string_view projectPath, AZStd::string_view enginePath, const char* files)
  2628. {
  2629. // Put together the whole Url Query String:
  2630. QUrlQuery query;
  2631. query.addQueryItem("projectPath", QString::fromUtf8(projectPath.data(), aznumeric_cast<int>(projectPath.size())));
  2632. if (!enginePath.empty())
  2633. {
  2634. query.addQueryItem("enginePath", QString::fromUtf8(enginePath.data(), aznumeric_cast<int>(enginePath.size())));
  2635. }
  2636. auto ParseFilesList = [&](AZStd::string_view filePath)
  2637. {
  2638. bool fullPathFound = false;
  2639. auto GetFullSourcePath = [&]
  2640. (AzToolsFramework::AssetSystem::AssetSystemRequest* assetSystemRequests)
  2641. {
  2642. AZ::IO::Path assetFullPath;
  2643. if(assetSystemRequests->GetFullSourcePathFromRelativeProductPath(filePath, assetFullPath.Native()))
  2644. {
  2645. fullPathFound = true;
  2646. query.addQueryItem("files[]", QString::fromUtf8(assetFullPath.c_str()));
  2647. }
  2648. };
  2649. AzToolsFramework::AssetSystemRequestBus::Broadcast(AZStd::move(GetFullSourcePath));
  2650. // If the full source path could be found through the Asset System, then
  2651. // attempt to resolve the path using the FileIO instance
  2652. if (!fullPathFound)
  2653. {
  2654. AZ::IO::FixedMaxPath resolvedFilePath;
  2655. if (auto fileIo = AZ::IO::FileIOBase::GetInstance();
  2656. fileIo != nullptr && fileIo->ResolvePath(resolvedFilePath, filePath)
  2657. && fileIo->Exists(resolvedFilePath.c_str()))
  2658. {
  2659. query.addQueryItem("files[]", QString::fromUtf8(resolvedFilePath.c_str()));
  2660. }
  2661. }
  2662. };
  2663. AZ::StringFunc::TokenizeVisitor(files, ParseFilesList, "|");
  2664. QUrl luaDebuggerUrl(QString::fromUtf8(luaDebuggerUri.data(), aznumeric_cast<int>(luaDebuggerUri.size())));
  2665. luaDebuggerUrl.setQuery(query);
  2666. AZ_VerifyError("CCryEditApp", Platform::OpenUri(luaDebuggerUrl),
  2667. "Failed to start external lua debugger with URI: %s", luaDebuggerUrl.toString().toUtf8().constData());
  2668. }
  2669. void CCryEditApp::OpenLUAEditor(const char* files)
  2670. {
  2671. AZ::IO::FixedMaxPathString enginePath = AZ::Utils::GetEnginePath();
  2672. AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath();
  2673. auto registry = AZ::SettingsRegistry::Get();
  2674. if (registry)
  2675. {
  2676. AZStd::string luaDebuggerUri;
  2677. if (registry->Get(luaDebuggerUri, LuaDebuggerUriRegistryKey))
  2678. {
  2679. OpenExternalLuaDebugger(luaDebuggerUri, projectPath, enginePath, files);
  2680. return;
  2681. }
  2682. }
  2683. AZStd::string filename = "LuaIDE";
  2684. AZ::IO::FixedMaxPath executablePath = AZ::Utils::GetExecutableDirectory();
  2685. executablePath /= filename + AZ_TRAIT_OS_EXECUTABLE_EXTENSION;
  2686. if (!AZ::IO::SystemFile::Exists(executablePath.c_str()))
  2687. {
  2688. AZ_Error("LuaIDE", false, "%s not found", executablePath.c_str());
  2689. return;
  2690. }
  2691. AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo;
  2692. AZStd::vector<AZStd::string> launchCmd = { executablePath.String() };
  2693. launchCmd.emplace_back("--engine-path");
  2694. launchCmd.emplace_back(AZStd::string_view{ enginePath });
  2695. launchCmd.emplace_back("--project-path");
  2696. launchCmd.emplace_back(AZStd::string_view{ projectPath });
  2697. launchCmd.emplace_back("--launch");
  2698. launchCmd.emplace_back("lua");
  2699. auto ParseFilesList = [&launchCmd](AZStd::string_view filePath)
  2700. {
  2701. bool fullPathFound = false;
  2702. auto GetFullSourcePath = [&launchCmd, &filePath, &fullPathFound]
  2703. (AzToolsFramework::AssetSystem::AssetSystemRequest* assetSystemRequests)
  2704. {
  2705. AZ::IO::Path assetFullPath;
  2706. if(assetSystemRequests->GetFullSourcePathFromRelativeProductPath(filePath, assetFullPath.Native()))
  2707. {
  2708. fullPathFound = true;
  2709. launchCmd.emplace_back("--files");
  2710. launchCmd.emplace_back(AZStd::move(assetFullPath.Native()));
  2711. }
  2712. };
  2713. AzToolsFramework::AssetSystemRequestBus::Broadcast(AZStd::move(GetFullSourcePath));
  2714. // If the full source path could be found through the Asset System, then
  2715. // attempt to resolve the path using the FileIO instance
  2716. if (!fullPathFound)
  2717. {
  2718. AZ::IO::FixedMaxPath resolvedFilePath;
  2719. if (auto fileIo = AZ::IO::FileIOBase::GetInstance();
  2720. fileIo != nullptr && fileIo->ResolvePath(resolvedFilePath, filePath)
  2721. && fileIo->Exists(resolvedFilePath.c_str()))
  2722. {
  2723. launchCmd.emplace_back("--files");
  2724. launchCmd.emplace_back(resolvedFilePath.String());
  2725. }
  2726. }
  2727. };
  2728. AZ::StringFunc::TokenizeVisitor(files, ParseFilesList, "|");
  2729. processLaunchInfo.m_commandlineParameters = AZStd::move(launchCmd);
  2730. AZ_VerifyError("LuaIDE", AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo),
  2731. "Lua IDE has failed to launch at path %s", executablePath.c_str());
  2732. }
  2733. void CCryEditApp::PrintAlways(const AZStd::string& output)
  2734. {
  2735. m_stdoutRedirection.WriteBypassingRedirect(output.c_str(), static_cast<unsigned int>(output.size()));
  2736. }
  2737. void CCryEditApp::RedirectStdoutToNull()
  2738. {
  2739. m_stdoutRedirection.RedirectTo(AZ::IO::SystemFile::GetNullFilename());
  2740. }
  2741. void CCryEditApp::OnError(AzFramework::AssetSystem::AssetSystemErrors error)
  2742. {
  2743. AZStd::string errorMessage = "";
  2744. switch (error)
  2745. {
  2746. case AzFramework::AssetSystem::ASSETSYSTEM_FAILED_TO_LAUNCH_ASSETPROCESSOR:
  2747. errorMessage = AZStd::string::format("Failed to start the Asset Processor.\r\nPlease make sure that AssetProcessor is available in the same folder the Editor is in.\r\n");
  2748. break;
  2749. case AzFramework::AssetSystem::ASSETSYSTEM_FAILED_TO_CONNECT_TO_ASSETPROCESSOR:
  2750. errorMessage = AZStd::string::format("Failed to connect to the Asset Processor.\r\nPlease make sure that AssetProcessor is available in the same folder the Editor is in and another copy is not already running somewhere else.\r\n");
  2751. break;
  2752. }
  2753. QMessageBox::critical(nullptr,"Error",errorMessage.c_str());
  2754. }
  2755. void CCryEditApp::OnOpenProceduralMaterialEditor()
  2756. {
  2757. QtViewPaneManager::instance()->OpenPane(LyViewPane::SubstanceEditor);
  2758. }
  2759. namespace Editor
  2760. {
  2761. //! This function returns the build system target name
  2762. AZStd::string_view GetBuildTargetName()
  2763. {
  2764. #if !defined (LY_CMAKE_TARGET)
  2765. #error "LY_CMAKE_TARGET must be defined in order to add this source file to a CMake executable target"
  2766. #endif
  2767. return AZStd::string_view{ LY_CMAKE_TARGET };
  2768. }
  2769. }
  2770. #if defined(AZ_PLATFORM_WINDOWS)
  2771. //Due to some laptops not autoswitching to the discrete gpu correctly we are adding these
  2772. //dllspecs as defined in the amd and nvidia white papers to 'force on' the use of the
  2773. //discrete chips. This will be overriden by users setting application profiles
  2774. //and may not work on older drivers or bios. In theory this should be enough to always force on
  2775. //the discrete chips.
  2776. //http://developer.download.nvidia.com/devzone/devcenter/gamegraphics/files/OptimusRenderingPolicies.pdf
  2777. //https://community.amd.com/thread/169965
  2778. // It is unclear if this is also needed for linux or osx at this time(22/02/2017)
  2779. extern "C"
  2780. {
  2781. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  2782. __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
  2783. }
  2784. #endif
  2785. #ifdef Q_OS_WIN
  2786. #pragma comment(lib, "Shell32.lib")
  2787. #endif
  2788. extern "C" int AZ_DLL_EXPORT CryEditMain(int argc, char* argv[])
  2789. {
  2790. // Debugging utilities
  2791. for (int i = 1; i < argc; ++i)
  2792. {
  2793. if (azstricmp(argv[i], "--attach-debugger") == 0)
  2794. {
  2795. AZ::Debug::Trace::AttachDebugger();
  2796. }
  2797. else if (azstricmp(argv[i], "--wait-for-debugger") == 0)
  2798. {
  2799. AZ::Debug::Trace::WaitForDebugger();
  2800. }
  2801. }
  2802. // ensure the EditorEventsBus context gets created inside EditorLib
  2803. [[maybe_unused]] const auto& editorEventsContext = AzToolsFramework::EditorEvents::Bus::GetOrCreateContext();
  2804. // connect relevant buses to global settings
  2805. gSettings.Connect();
  2806. auto theApp = AZStd::make_unique<CCryEditApp>();
  2807. // Must be set before QApplication is initialized, so that we support HighDpi monitors, like the Retina displays
  2808. // on Windows 10
  2809. QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  2810. QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
  2811. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  2812. // QtOpenGL attributes and surface format setup.
  2813. QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true);
  2814. QSurfaceFormat format = QSurfaceFormat::defaultFormat();
  2815. format.setDepthBufferSize(24);
  2816. format.setStencilBufferSize(8);
  2817. format.setVersion(2, 1);
  2818. format.setProfile(QSurfaceFormat::CoreProfile);
  2819. format.setSamples(8);
  2820. format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
  2821. format.setRenderableType(QSurfaceFormat::OpenGL);
  2822. format.setSwapInterval(0);
  2823. #ifdef AZ_DEBUG_BUILD
  2824. format.setOption(QSurfaceFormat::DebugContext);
  2825. #endif
  2826. QSurfaceFormat::setDefaultFormat(format);
  2827. Editor::EditorQtApplication::InstallQtLogHandler();
  2828. AzQtComponents::Utilities::HandleDpiAwareness(AzQtComponents::Utilities::SystemDpiAware);
  2829. Editor::EditorQtApplication* app = Editor::EditorQtApplication::newInstance(argc, argv);
  2830. QStringList qArgs = app->arguments();
  2831. const bool is_automated_test = AZStd::any_of(qArgs.begin(), qArgs.end(),
  2832. [](const QString& elem)
  2833. {
  2834. return elem.endsWith("autotest_mode") || elem.endsWith("runpythontest");
  2835. }
  2836. );
  2837. if (is_automated_test)
  2838. {
  2839. // Nullroute all stdout to null for automated tests, this way we make sure
  2840. // that the test result output is not polluted with unrelated output data.
  2841. theApp->RedirectStdoutToNull();
  2842. }
  2843. // Hook the trace bus to catch errors, boot the AZ app after the QApplication is up
  2844. int ret = 0;
  2845. // open a scope to contain the AZToolsApp instance;
  2846. {
  2847. EditorInternal::EditorToolsApplication AZToolsApp(&argc, &argv);
  2848. {
  2849. CEditCommandLineInfo cmdInfo;
  2850. if (!cmdInfo.m_bAutotestMode && !cmdInfo.m_bConsoleMode &&
  2851. !cmdInfo.m_bNullRenderer && !cmdInfo.m_bTest)
  2852. {
  2853. if (auto nativeUI = AZ::Interface<AZ::NativeUI::NativeUIRequests>::Get(); nativeUI != nullptr)
  2854. {
  2855. nativeUI->SetMode(AZ::NativeUI::Mode::ENABLED);
  2856. }
  2857. }
  2858. }
  2859. // The settings registry has been created by the AZ::ComponentApplication constructor at this point
  2860. AZ::SettingsRegistryInterface& registry = *AZ::SettingsRegistry::Get();
  2861. AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddBuildSystemTargetSpecialization(
  2862. registry, Editor::GetBuildTargetName());
  2863. AZ::Interface<AZ::IConsole>::Get()->PerformCommand("sv_isDedicated false");
  2864. if (!AZToolsApp.Start())
  2865. {
  2866. return -1;
  2867. }
  2868. AzToolsFramework::EditorEvents::Bus::Broadcast(&AzToolsFramework::EditorEvents::NotifyQtApplicationAvailable, app);
  2869. int exitCode = 0;
  2870. bool didCryEditStart = CCryEditApp::instance()->InitInstance();
  2871. AZ_Error("Editor", didCryEditStart, "O3DE Editor did not initialize correctly, and will close."
  2872. "\nThis could be because of incorrectly configured components, or missing required gems."
  2873. "\nSee other errors for more details.");
  2874. AzToolsFramework::EditorEventsBus::Broadcast(&AzToolsFramework::EditorEvents::NotifyEditorInitialized);
  2875. if (didCryEditStart)
  2876. {
  2877. app->EnableOnIdle();
  2878. ret = app->exec();
  2879. }
  2880. else
  2881. {
  2882. exitCode = 1;
  2883. }
  2884. CCryEditApp::instance()->ExitInstance(exitCode);
  2885. }
  2886. delete app;
  2887. gSettings.Disconnect();
  2888. return ret;
  2889. }
  2890. AZ_DECLARE_MODULE_INITIALIZATION
  2891. #include <moc_CryEdit.cpp>