CryEdit.cpp 118 KB

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