Files
UnrealEngineUWP/Engine/Source/Editor/GameProjectGeneration/Private/GameProjectUtils.cpp
Marc Audy 22f58737f9 Copying //UE4/Dev-Framework to //UE4/Dev-Main (Source: //UE4/Dev-Framework @ 3431384)
#lockdown Nick.Penwarden
#rb none

==========================
MAJOR FEATURES + CHANGES
==========================

Change 3252833 on 2017/01/10 by Ori.Cohen

	Refactor constraint so that it can be used for external solvers. (Copying //Tasks/UE4/Dev-ImmediateModePhysics to Dev-Framework (//UE4/Dev-Framework))

Change 3256288 on 2017/01/12 by Ori.Cohen

	Undo constraint refactor as we found a way around it and it made the code much harder to read/debug

Change 3373195 on 2017/03/30 by Mike.Beach

	For nativization, changing it so we key off of the target platform-info struct instead of the platform (in preparation for defining the nativized plugin's platform whitelist).

Change 3381178 on 2017/04/05 by Dan.Oconnor

	Make sure we don't inherit the NATIVE func flag when generating skeleton functions, also make sure all bojects outer'd to the skeleton class are marked transient
	#jira UE-43616

Change 3381532 on 2017/04/05 by Marc.Audy

	(4.16) Fix various cases where built lighting on child actors could be lost when loading a level
	#jira UE-43553

Change 3381586 on 2017/04/05 by Mike.Beach

	Now generating TArrayCaster conversions for nativized UClass arrays that need it (to handle different TSubclassOf arrays).

	#jira UE-42676, UE-43257

Change 3381682 on 2017/04/05 by mason.seay

	Some more changes to test map

Change 3381844 on 2017/04/05 by Dan.Oconnor

	Match existing logic for CPF_ReturnParm/CPF_OutParm. Fixes compilation error in BP_TurbineBlades when using compilation manager

Change 3382054 on 2017/04/05 by Zak.Middleton

	#ue4 - Optimize CharacterMovementComponent::GetPredictionData_Client_Character() and GetPredictionData_Server_Character() to remove virtual calls.

	#jira UE-30998

Change 3382703 on 2017/04/06 by Lukasz.Furman

	fixed missing links between navmesh polys when there are more than 4 neighbor connections
	#jira UE-43524

Change 3383357 on 2017/04/06 by Marc.Audy

	(4.16) Make SetHiddenInGame propagate consistently with SetVisibility
	#jira UE-43709

Change 3383359 on 2017/04/06 by Dan.Oconnor

	Fix last errant SKEL reference when cooking Odin

Change 3383591 on 2017/04/06 by Mike.Beach

	Prevent users from setting object variables as 'config' properties (disallowed by UHT). This prevents some errors that could happen later when users nativize the Blueprint.

	#jira UE-42085

Change 3384762 on 2017/04/07 by Zak.Middleton

	#ue4 - Fix SpringArmComponent not restoring relative transform when bUsePawnControlRotation is turned off. Fixes the editor interaction ignoring transform of the component in the viewport after bUsePawnControlRotation is toggled on then off, since by then the world transform had been overwritten (from tick in editor) and nothing would drive transform changes from the editable value.

	Toggling bUsePawnControlRotation off at runtime now restores the rotation to the initial relative rotation, not stomping it with the current pawn rotation, allowing toggling between the editable/desired base rotation and the control rotation.

	#jira UE-24850

Change 3384948 on 2017/04/07 by Dan.Oconnor

	Prevent GForceDisableBlueprintCompileOnLoad from causing all sorts of badness when dependencies are loaded as part of a Diff operation. Instead of setting a global flag we flag the package as LOAD_DisableCompileOnLoad

Change 3385267 on 2017/04/07 by Michael.Noland

	Graph Editing: Pushed some node diffing code down from UAIGraphNode into UEdGraphNode so nodes with details panel properties will diff correctly (e.g., various animation nodes and BP switch nodes)

	#jira UE-21724

Change 3385473 on 2017/04/07 by Phillip.Kavan

	#jira UE-43067 - Fix broken pin wires after an Expand Node operation, along with some misc. cleanup.

	Change summary:
	- Fixed to use correct string for "Expand Node" transaction name.
	- Modified FBlueprintEditor::OnExpandNodes() to consolidate some redundant code.
	- Fixed to generate a unique node GUID for cases where the source graph is not removed after expansion.

Change 3385583 on 2017/04/07 by Dan.Oconnor

	Handle CreatePropertyOnScope nullptr return values (happens for structs missing a struct property)

	#jira UE-43746

Change 3386581 on 2017/04/10 by Michael.Noland

	Blueprints: Further hardening FBlueprintActionInfo::GetOwnerClass()
	#jira UE-43824

Change 3386615 on 2017/04/10 by Marc.Audy

	Instanced properties can now properly be set on a per-instance basis in blueprint added components.
	#jira UE-42066

Change 3387000 on 2017/04/10 by Marc.Audy

	Fix includes for CIS

Change 3387229 on 2017/04/10 by mason.seay

	More changes to TM-Gameplay

	Added Save Game test (with blueprint)

	Tick Interval test (with blueprint)

	BP logic cleanup

	Level organization

Change 3388437 on 2017/04/11 by Mike.Beach

	Adding support for map/set literals in the backend (so you can use set nodes for structs containing sets/maps, without having to connect a RHS input - resets to struct defaults).

	#jira UE-42617

Change 3388532 on 2017/04/11 by mason.seay

	Submitting latest changes for crash repro

Change 3389026 on 2017/04/11 by Ben.Zeigler

	Performance and bug fixes for incremetal cooking with asset registry, duplicate of several changes made on //Fortnite/Main
	Fix it so AssetRegistry.ScanPathsAndFilesSynchronous won't scan subdirectories inside already scanned directories, this cuts down on the number of cache files
	Fix 2 second stall when shutting down AssetSourceFilenameCache if it had never been previously created

Change 3389163 on 2017/04/11 by Ben.Zeigler

	#jira UE-42922 Fix it so connecting function input node output pins does not clear default value, we only want to clear the value when connecting an input pin. Properly testing this fix depends on UE-43883

Change 3389205 on 2017/04/11 by Marc.Audy

	Protect against a handful of GEditor usages that can now be hit in standalone

Change 3389220 on 2017/04/11 by Marc.Audy

	Don't borrow ClassWithin to masquerade as ParentClass during compilation and instead just set the super struct immediately

Change 3389222 on 2017/04/11 by Michael.Noland

	Framework: Adding a cvar (t.TickComponentLatentActionsWithTheComponent) to allow users to revert to the old behavior on when component latent actions tick
	- Non-zero values behave the same way as actors do, ticking pending latent action when the component ticks, instead of later on in the frame (default behavior in 4.16 and beyond)
	- Prior to 4.16, components behaved as if the value were 0, which meant their latent actions behaved differently to actors

	This CVar will be removed in a future version, defaulting to on

	#jira UE-43661

Change 3389276 on 2017/04/11 by Marc.Audy

	Spelling fix and NULL to nullptr

Change 3389303 on 2017/04/11 by Mieszko.Zielinski

	Made sure AIController::Posses doesn't get called when compiling Pawn BP #UE4

	#jira UE-43873

Change 3390215 on 2017/04/12 by mason.seay

	Removed some tests, will need further review

Change 3390638 on 2017/04/12 by Mike.Beach

	Generalizing the omission of the CoerceProperty (in EmitTerm) - previously we were only omitting properties for our custom array lib. For wildcards, a coerce property should not be used as its type will not match.

	NOTE: There is a slight behavior change in UEdGraphSchema_K2::ConvertPropertyToPinType(), as it will return 'wildcard' for params marked as 'ArrayTypeDependentParams' (previously would have returned 'int').

	#jira UE-42747

Change 3390774 on 2017/04/12 by Ben.Zeigler

	#jira UE-43911 Fix several issues with saving a runtime asset registry containing redirectors that caused crashes in cook on the fly. Don't resolve redirectors on incoming links because it will make a circular link, and fix an issue where chained redirectors would break the for loop iteration and return a bad dependency
	Fix it so the asset registry written out at the beginning of CookOnTheFly uses the registry generator, otherwise it will include all of the stripped editor only tags

Change 3390778 on 2017/04/12 by Ben.Zeigler

	Fix UCookOnTheFlyServer::CollectFilesToCook to check for initial unsolicited packages up front. This is required in iterative mode because it may skip cooking all explicit packages and thus miss a new startup loaded package

Change 3390782 on 2017/04/12 by Ben.Zeigler

	Change RunProjectCommand to not imply -nomcp, and allow reading -clientcmdline to override setting the map parameter to 127.0.0.1 by default
	Fix RunProjectCommand to remove ios-specific checks to not pass weird platform parameters, and instead never pass them
	Fix PS4Platform to pass along command line when calling build cook run, args needs to be the last parameter so explicitly set -target=

Change 3390859 on 2017/04/12 by Mike.Beach

	T3D class fields now export with the class's fully qualified path name (to avoid abiguity). Since we can have multiple classes with the same name (Blueprints in different folders), we have to use the class's fully qualified object path.

	#jira UE-28048

Change 3390914 on 2017/04/12 by Lukasz.Furman

	fixed missing navlink component's transform in exported navigation data
	#jira  UE-43688

Change 3391122 on 2017/04/12 by Ben.Zeigler

	Add new PreloadPrimaryAssets call to AssetManager that stream the desired assets without modifying the official load/unload state. This is useful if you want to preload things in case the might be used in the future, and it also supports recursion
	Fix crash calling GetAssetDataForPath with null path

Change 3391494 on 2017/04/12 by Dan.Oconnor

	Fix bad references in deep object (widget) hierarchies

	#jira UE-43802

Change 3391529 on 2017/04/12 by Dan.Oconnor

	Fix log spam, accidently submitted

	#rnx

Change 3391756 on 2017/04/12 by Dan.Oconnor

	LinkExternalDependencies needs to be performed before we RefreshVariables

	#jira UE-43843

Change 3392542 on 2017/04/13 by Marc.Audy

	Ensure that initialized actors get cleaned up when removed from world even if that world hasn't begun play.
	#jira UE-43879

Change 3392746 on 2017/04/13 by Marc.Audy

	(4.16) When duplicating a blueprint node, correctly make the new node a sibling of the duplicated node, not a child of it (unless duplicating the root component).
	Also resets scale of a duplicated root component to 1 to avoid a squaring of the scale for that component.
	#jira UE-40218
	#jira UE-42086

Change 3393253 on 2017/04/13 by Dan.Oconnor

	Make sure calculated meta data is correctly set on functions generated by the compilation manager (SKEL_ class functions)

	#jira UE-43883

Change 3393509 on 2017/04/13 by Mike.Beach

	Removing hack'ish ResetLoaders() call that was causing undesired side-effects (resetting of a loaded package that other objects were relying on). This was originally intended to release file handles so separate editor processes could make updates and save the file (from CL 1712376). Using ResetLoaders() for this is bad though, as it has too many side effects. Instead we have to wait for GC to run. This also makes sure that GC should run as intended as the CookOnTheFly sever is idling.

	#jira UE-37284

Change 3394350 on 2017/04/14 by Michael.Noland

	Core: Making FDateTime and FTimespan actually reflected, so they get duplicated properly in CopyPropertiesForUnrelatedObjects, etc...
	#jira UE-39921

Change 3395985 on 2017/04/17 by Phillip.Kavan

	#jira UE-38280 - Fix invalid custom type selections on member fields in the User-Defined Structure Editor after a reload.

	Change summary:
	- Ensure that the 'SubCategoryObject' member in a UDS variable descriptor has been loaded when converting to an FEdGraphPinType.

Change 3396152 on 2017/04/17 by Marc.Audy

	TickableGameObjects that have IsTickableInEditor false should not tick in the editor
	#jira UE-40421

Change 3396279 on 2017/04/17 by Phillip.Kavan

	#jira UE-43968 - Fix failed validation of bitmask enum types when serializing bitmask literal nodes.

Change 3396299 on 2017/04/17 by Dan.Oconnor

	Fix resintancing issues exposed by running TM-Gameplay with -game. We cannot reinstance actors in levels on load because the scene is not created.

	#jira UE-43859

Change 3396712 on 2017/04/17 by Marc.Audy

	Call PostLoad on subobjects before copying for unrelated properties to avoid cases where an out of date object patched over in the linker has not been brought up to date
	#jira UE-38234

Change 3396718 on 2017/04/17 by Mike.Beach

	Adding a search bar to the components tree for Blueprints.

	#epicfriday
	#jira UE-17620

Change 3396999 on 2017/04/17 by Mike.Beach

	In generated code, call event '_Implementation' functions directly for interface functions being invoked on self (avoids a UHT runtime error).

	#jira UE-44018

Change 3397700 on 2017/04/18 by Marc.Audy

	UT struct BlueprintType fixups

Change 3397701 on 2017/04/18 by Marc.Audy

	Odin struct BlueprintType fixups

Change 3397703 on 2017/04/18 by Marc.Audy

	Ocean struct BlueprintType fixups

Change 3397704 on 2017/04/18 by Marc.Audy

	WEX struct BlueprintType fixups

Change 3397705 on 2017/04/18 by Marc.Audy

	Additional UT blueprint type struct fixups

Change 3397706 on 2017/04/18 by Marc.Audy

	Fortnite struct BlueprintType fixups

Change 3397708 on 2017/04/18 by Marc.Audy

	Fixup Engine BlueprintType markup of structs

Change 3397709 on 2017/04/18 by Marc.Audy

	Sample Game struct BlueprintType fixups

Change 3397711 on 2017/04/18 by Marc.Audy

	Mark AnimNodes as BlueprintType and BlueprintInternalUseOnly

Change 3397712 on 2017/04/18 by Marc.Audy

	Paragon struct BlueprintType fixups

Change 3397735 on 2017/04/18 by Marc.Audy

	Definition pieces of BlueprintInternalUseOnly to fix UHT errors with structs already marked to use it

Change 3397912 on 2017/04/18 by Mike.Beach

	Fix for CIS warnings about shadowed variables (fallout from CL 3396718).

Change 3398455 on 2017/04/18 by Marc.Audy

	Make less critical errors log an error rather than immediately throwing allowing multiple errors to be reported in the same compile

Change 3398491 on 2017/04/18 by Marc.Audy

	BPRW/BPRO in a non-BlueprintType is now a UHT error

Change 3398539 on 2017/04/18 by Marc.Audy

	Fixup live link struct markups

Change 3399412 on 2017/04/19 by Marc.Audy

	Fix Match3 blueprint type struct markups

Change 3399509 on 2017/04/19 by Phillip.Kavan

	#jira UE-38574 - Fix AnimBlueprint function graphs marked as 'const' to treat 'self' as read-only when compiling.

	Change summary:
	- Modified FKismetCompilerContext::ProcessOneFunctionGraph() to use the function graph schema rather than the compiler context schema for both the function context's schema as well as testing the function for 'const'-ness. For AnimBPs, the compiler context and the function graph context can differ, so we need to make sure we are using the right one when making queries for a specific function context during compilation.
	- Minor cleanup: changed the function context schema to be 'const' in order to be consistent with the function graph GetSchema() API's result. Added a few 'const' qualifiers where needed to match.
	- Added a new object version in order to avoid breaking compilation of existing AnimBP function graphs that may already be violating the 'const' rule (this is the same thing that was done when 'const' was first added to "normal" BP function graphs). Just as with normal function graphs in place before the addition, a warning will be generated for existing AnimBP function graphs if they violate 'const' correctness, and an error will be generated for all new ones.

Change 3399749 on 2017/04/19 by Mike.Beach

	Hiding the Nativized Blueprints plugin from the in-editor browser (prevent users from disabling it).

Change 3399774 on 2017/04/19 by Marc.Audy

	ConditionalPostLoad is already called on StaticMesh earlier in the function

	#rnx

Change 3400313 on 2017/04/19 by Mike.Beach

	Mirroring CL 3398673 from 4.16

	Now, with ICWYU, making sure that the coresponding header gets included first in nativized Blueprint files (else we get a UHT error). Had to fixup some ShooterGame specific files as a result (they had missing includes and forward declarations).

	#jira UE-44124

Change 3400328 on 2017/04/19 by Mike.Beach

	Missing file from mirrored change (CL 3400313 - mirroring CL 3398673 from 4.16)

	#jira UE-44124

Change 3400415 on 2017/04/19 by Chad.Garyet

	adding physx switch build to framework

Change 3400514 on 2017/04/19 by Mike.Beach

	Back out changelist 3400313 / 3400328 (mirrored from CL 3398673 in 4.16), as it was producing "include PCH first" errors. Likely, CL 3398673 was a fix for a 4.16 specific change, altering the expected include order. We'll have to wait for this one to be integrated back.

Change 3400552 on 2017/04/19 by Marc.Audy

	Undo the calling of post load prior to the CPFUO as dependent objects may not yet be loaded. Instead copy the need load flag to the new CDO subobject, similarly to how the top level CDO object copies its flags over.
	#jira UE-44150

Change 3400815 on 2017/04/19 by Marc.Audy

	Spelling fix (part of PR #3490)

	#rnx

Change 3400918 on 2017/04/19 by Marc.Audy

	Partial pull of PR #3490: Improved remapping game controls support (Contributed by projectgheist)
	This portion brings in the exposure of the bindings to blueprint
	#jira UE-44122

Change 3401550 on 2017/04/20 by Marc.Audy

	fix kitedemo blueprint type markup

	#rnx

Change 3401702 on 2017/04/20 by Mike.Beach

	Make it so plugins added to a project through the .uproject's 'AdditionalPluginDirectories' list get folded into the generated code project (for visual studio, etc.).

Change 3401720 on 2017/04/20 by Mike.Beach

	Add white and black lists for target type (game, client, server, etc.) to plugin module descriptors.

Change 3401725 on 2017/04/20 by Mike.Beach

	Whitelisting the nativized Blueprint plugin for only the targets it was built for (game, server, or client).

Change 3401800 on 2017/04/20 by Ben.Zeigler

	Add Algo::BinarySearch, LowerBound, and UpperBound. These are setup to allow binary searching a presorted array, and allow for specifying projection and sort predicates. Convert some engine code to use it
	Add TSortedMap, which is a map data structure that has the same API as TMap, but is backed by a sorted array. It uses half the memory and performance is faster below n=10
	Add FName::CompareIndexes so a SortedMap with FNames can be used without doing very slow string compares, and FNameSortIndexes predicate to sort by it
	Add code to Algo and Container tests. Split up container tests so the new ones aren't run in smoketest as they are a bit slow
	Add RemoveCurrent and SetToEnd to ArrayIterator

Change 3401849 on 2017/04/20 by Marc.Audy

	Partial pull of PR #3490: Improved remapping game controls support (Contributed by projectgheist)

	This portion brings bug fixes and improvements to InputKeySelector UMG widgets.
	#jira UE-44122

Change 3402088 on 2017/04/20 by Marc.Audy

	Focus the search box when expanding the map value type
	#jira UE-44211

Change 3402251 on 2017/04/20 by Ben.Zeigler

	Fix issue where SortedMap needs to be resorted after serialization, because the sorting may have changed from when it was saved out

Change 3402335 on 2017/04/20 by Ben.Zeigler

	Significant changes to FAssetData serialization and memory, cuts memory significantly but will break code that was using some of the internal API that was not properly hidden before
	Both Editor and Runtime cache now use the same FAssetRegistryVersion, which is now registered as a custom version
	Rename FAssetData and FAssetPackage operator<< to SerializeForCache to make it clear that it isn't safe to use for general serialization
	Remove GroupNames from FAssetData, it has not been useful since the UE4 package structure changed around 4.0
	Rename generic-sounding but not actually generic SharedMapView class to AssetDataTagMapSharedView to indicate what it is actually used for
	Change TagsAndValues to use a new array-backed TSortedMap as the base structure instead of a hash map. Also, it only allocates the map on demand, which saves significant memory at runtime as many packages have no tags
	Add bFilterAssetDataWithNoTags to [AssetRegistry] ini section, if set it will only save cooked asset data if it has tags, off by default but saves significant memory if your whitelist is set up properly
	Fix issue where asset registry tags updated by loading assets during cook were not being reflected in the cooked registry
	Add AssetRegistry::GetAllocatedSize and add to MemReport output

Change 3402457 on 2017/04/20 by Ben.Zeigler

	Enable asset registry iteration and stripping unused asset data in Fortnite. Registry iteration is already on in //Fortnite/Main, stripping is a new feature I want to test

Change 3402498 on 2017/04/20 by Ben.Zeigler

	CIS fix. Why did this compile locally?

Change 3402537 on 2017/04/20 by Ben.Zeigler

	Remove ensure for making AssetData for subobjects, the editor does this for thumbnail creation in some cases

Change 3402600 on 2017/04/20 by Ben.Zeigler

	Add bShouldGuessTypeAndNameInEditor to manager settings, can be set false for games where type cannot be safely implied and content must be resaved
	Fix up some bool setting code inside asset manager, and fix const correctness and for iterator issues
	AssetManager can now discover any BlueprintCore type when bHasBlueprintClasses=true
	Add AssetManager.DumpAssetRegistryInfo to output detailed asset registry usage stats
	Add Primary Name to asset audit window by default

Change 3403556 on 2017/04/21 by Marc.Audy

	Fix Orion input key selector override class

	#rnx

Change 3404090 on 2017/04/21 by mason.seay

	Applying Forcefeedback to test map

Change 3404093 on 2017/04/21 by mason.seay

	Changing text in level

Change 3404139 on 2017/04/21 by mason.seay

	Added Force Feedback test and made some tweaks.

Change 3404146 on 2017/04/21 by mason.seay

	Added source reference to Instanced Variable test

Change 3404154 on 2017/04/21 by mason.seay

	More minor tweaks

Change 3404155 on 2017/04/21 by Marc.Audy

	Remove auto

	#rnx

Change 3404188 on 2017/04/21 by Marc.Audy

	Fixed crash changing variable type when any type other than map
	#jira UE-44249

	#rnx

Change 3404463 on 2017/04/21 by Ben.Zeigler

	Fix asset data code to not ensure when loading an object with invalid exports, and instead print warning with name of package that needs to be resaved
	Resave a map that had a redirector from a DIFFERENT package saved in it's exports. I do not understand how this happened, but it appears to be related to the lightmap BuiltData transition when old maps are opened

Change 3404465 on 2017/04/21 by Ben.Zeigler

	Fix issue with trying to load editor-only asset classes in a cooked build
	Fix issues with renaming or changing template Ids of assets from the editor
	Always print the Duplicate Asset ID error, as if you have more than one the ensuremsg only goes off once

Change 3404481 on 2017/04/21 by Dan.Oconnor

	Remove unneeded walk up hierarchy - prevent stale entries in action database if we compile a BP but don't compile its children

Change 3404510 on 2017/04/21 by Phillip.Kavan

	#jira UE-35727 - Collapsed graphs containing a local variable node will no longer cause a compile error when the parent graph is renamed.

Change 3404590 on 2017/04/21 by Michael.Noland

	Editor: Fixed incorrect filtering of abstract/deprecated UDeveloperSettings and UContentBrowserFrontEndFilterExtension classes caused by a typo (HasAnyCastFlags versus HasAnyClassFlags)

Change 3404593 on 2017/04/21 by Marc.Audy

	Fixed another crash to do with input pin secondary combo box
	#jira UE-44269

	#rnx

Change 3404600 on 2017/04/21 by Michael.Noland

	Core: Allow UE_GC_TRACK_OBJ_AVAILABLE to be set externally
	#rnx

Change 3404602 on 2017/04/21 by Michael.Noland

	Engine: Switched from an include to a forward declaration of SWidget in UDeveloperSettings to keep it slim
	#rnx

Change 3404608 on 2017/04/21 by Michael.Noland

	Core: Marked TNumericLimits as constexpr so they can be used in static asserts

Change 3404659 on 2017/04/21 by Michael.Noland

	Engine: Adding includes back to two UDeveloperSettings subclasses

Change 3405289 on 2017/04/24 by Marc.Audy

	Remove auto

	#rnx

Change 3405446 on 2017/04/24 by Marc.Audy

	Fix Win32 unsigned compile issue

Change 3405512 on 2017/04/24 by Mike.Beach

	Piping through NativizationOptions to filename generation (so we're able to gen different files names per target: client vs. server).

Change 3406080 on 2017/04/24 by Ben.Zeigler

	Deprecate UEngine::OnPostEngineInit and move to FCoreDelegates, clean up comments for the initialization delegates
	Call OnPostEngineInit from commandlet initialization as well as normal execution. I thought about making a wrapper function, but the commandlet calls EditorInit directly so it wouldn't work
	Bind delegate to refresh the AssetRegistry native class hierarchy after engine init so it picks up game/plugin classes. Undo ini change that was required to hack around this

Change 3406381 on 2017/04/24 by Ben.Zeigler

	#jira UE-23768 Enable Run Physics With No Controller for montage test pawn. The montage pawn has no controller so wasn't correctly running physics when the root motion stopped. This flag needs to be set to allow it to correctly stop after the montage is over

Change 3406438 on 2017/04/24 by Ben.Zeigler

	Fix deprecation warning

Change 3406519 on 2017/04/24 by Phillip.Kavan

	#jira UE-43612 - Suppress array "Get" node fixup notifications on load when the BP Compilation Manager is enabled.

	Change summary:
	- Wrapped BPCM calls to FBlueprintEditorUtils::ReconstructAllNodes() and ReplaceDeprecatedNodes() duirng compile-on-load with bIsRegeneratingOnLoad = true. This matches the BP's state during compile-on-load when the BPCM is not enabled.

Change 3406565 on 2017/04/24 by Dan.Oconnor

	Make sure all interface functions are added to skeleton

	#jira UE-44152

Change 3407489 on 2017/04/25 by Ben.Zeigler

	#jira UE-44317 Fix game-only TickableGameObjects to correctly tick in PIE

Change 3407558 on 2017/04/25 by Ben.Zeigler

	Fix Fortnite cook warnings, issue had to do with the CDO being registered as a Primary Asset in conflict with the Class being registered
	Fix issue with renaming a BP primary asset not finding the old name

Change 3407701 on 2017/04/25 by Dan.Oconnor

	Remove unneeded null check, static analysis doen't like the inconsistency

Change 3407995 on 2017/04/25 by Marc.Audy

	Fixed maps and sets not working correctly with split pin.
	#jira UE-43857

Change 3408124 on 2017/04/25 by Ben.Zeigler

	#jira UE-39586 Change it so the blueprint String/Name/Object to Text node creates culture invariant text, and also have them show as an expanded node with a comment explaining this
	Fix Transform to actually return in the format specified in the comment, and fix comments on many text conversions

Change 3408134 on 2017/04/25 by Marc.Audy

	Graph pin container type now represented by an enumeration (EPinContainerType) rather than 3 "independent" booleans.
	FEdGraphPinType constructor, UEdGraphNode::CreatePin, and FKismetCompilerContext::SpawnInternalVariable that took 3 booleans deprecated and replaced with a version that takes EPinContainerType.
	UEdGraphNode::CreatePin parameters reorganized so that PinName is before ContainerType and bIsReference, which default to None and false respectively

Change 3408256 on 2017/04/25 by Michael.Noland

	Core: Changed UClass::ClassFlags to be of type EClassFlags for improved type safety

Change 3408282 on 2017/04/25 by Marc.Audy

	(4.16) Fix incorrect positioning of instance components after duplication
	#jira UE-44314

Change 3408404 on 2017/04/25 by Mike.Beach

	Adding and removing the nativized plugin to/from the project when we alter the packaging nativization setting (so it gets picked up by project generation).

Change 3408445 on 2017/04/25 by Marc.Audy

	Fix up missed deprecation cases

	#rnx

Change 3409354 on 2017/04/26 by Marc.Audy

	Fix Linux CIS failure

	#rnx

Change 3409487 on 2017/04/26 by Marc.Audy

	When dragging assets in to the SCS create them as siblings, not nested
	#jira UE-43041

Change 3409776 on 2017/04/26 by Ben.Zeigler

	#jira UE-44401 Fix issue with cooking a map containing a reparented component. In that case the child component may think it's not editor only, but it's archetype is editor only. This is not allowed in EDL, so now the child is marked as editor only as well

Change 3410168 on 2017/04/26 by Dan.Oconnor

	Avoid calling virtual functions in the middle of compile
	#jira UE-44243

Change 3410252 on 2017/04/26 by Lukasz.Furman

	adjusted WITH_GAMEPLAY_DEBUGGER checks after IWYU changes
	#ue4

Change 3410385 on 2017/04/26 by Marc.Audy

	ChildActorComponent SetClass no longer fails when setting at runtime.
	#jira UE-43356

Change 3410466 on 2017/04/26 by Michael.Noland

	Core: Ensuring EClassFlags is 32 bit in a different way (underlying type of the enum is coming out signed even though all members are unsigned, long term fix is probably to move it to an enum class)
	#rnx

Change 3410476 on 2017/04/26 by Michael.Noland

	Automation: Deleting some commented out methods
	#rnx

Change 3411070 on 2017/04/27 by Marc.Audy

	Properly complete deprecation of old attachment API

Change 3411338 on 2017/04/27 by mason.seay

	Map for Latent Action Tick Bug

Change 3411637 on 2017/04/27 by Ben.Zeigler

	Back out CL #3381532 as it was causing crashes when adding new variables to blueprints, as the transaction array was being recursively modified while it was being added to

Change 3412052 on 2017/04/27 by mason.seay

	Updated jump test map and pawn

Change 3412231 on 2017/04/27 by Ben.Zeigler

	Fix issue where running SearchAllAssets multiple times after mounting new paths would throw away the asset registry cache, which slowed down incremental cooking substantially because the cooker mounts the autosave folder
	Duplicate of CL #3411860

Change 3412233 on 2017/04/27 by Ben.Zeigler

	Made FStreamableHandle::GetLoadedCount much faster by taking advantage of existing progress counter
	Duplicate of CL #3411778

Change 3412235 on 2017/04/27 by Ben.Zeigler

	Add code to FStringAssetReferenceThreadContext and FStringAssetReferenceSerializationScope which allows setting package name and collect options for string asset references serialized via something other than linker load
	Make RedirectCollector threadsafe to avoid issues with async loading asset references
	Fix it so ProcessStringAssetReferencePackageList will remove entries from the string asset array like resolve did, and rename function to indicate that
	Fix it so string asset references created by asset labels do not automatically get cooked, and significantly improve the speed of labels with lots of assets
	Add code to cooker and asset manager to explicitly mark non-cookable assets as NeverVook, this stops labels from ending up in the build if set that way
	Added option to not recurse package dependency changes more than one level when hashes change. This ended up not being significantly faster in a realistic case so left disabled
	Duplicate of CL #3412080

Change 3412352 on 2017/04/27 by Marc.Audy

	Refix lighting getting wrong position when getting component instance data

Change 3412426 on 2017/04/27 by Marc.Audy

	Take first steps to making ComponentToWorld private and force use of accessor
	Make bWorldToComponentUpdated private
	Make ComponentToWorld and bWorldToComponentUpdated mutable
	Add a SetComponentToWorld function for the (likely ill-advised) places that were setting it directly.

Change 3412468 on 2017/04/27 by Marc.Audy

	Remove last remnants of deprecated (4.11) custom location system

Change 3413398 on 2017/04/28 by Marc.Audy

	Fix up missed deprecated attachment API  uses

Change 3413403 on 2017/04/28 by Marc.Audy

	Fix Orion compile error

	#rnx

Change 3413448 on 2017/04/28 by Marc.Audy

	Fix up kite demo component to world privataization warnings

	#rnx

Change 3413792 on 2017/04/28 by Ben.Zeigler

	Fix many bugs with blueprint pin default values, and add "Reset to Default Value" option to pin context menu
	Deprecate and rename SetPinDefaultValue because it actually sets the Autogenerated default. This was being called in bad places and destroying the stored autogenerated defaults
	#jira UE-40101 Fix expose on spawn pins to correctly update when the spawned object's defaults change
	#jira UE-21642 Fix struct pin default values to properly update when the struct is changed
	#jira UE-39418 Fix changed function/macro default values to properly update in already placed call nodes

Change 3413839 on 2017/04/28 by samuel.proctor

	Added some Blueprint focused tests for TM-Gameplay

Change 3414030 on 2017/04/28 by Ben.Zeigler

	Enable use of AssetPtr variables with Config, for native and blueprint
	This incorporates CL #3302487 but also enables for blueprint usage as that code is new to framework branch

Change 3414229 on 2017/04/28 by Marc.Audy

	Fixup virtuals not calling their Super
	Remove some autos

	#rnx

Change 3414451 on 2017/04/28 by Lukasz.Furman

	static analysis fix for gameplay debugger

Change 3414482 on 2017/04/28 by Ben.Zeigler

	Fix crash found where changing pin type on ConvertAsset accessed an array while deleting it

Change 3414609 on 2017/04/28 by Ben.Zeigler

	#jira UE-18146 Refresh graph when disconnecting a resolve asset id node

Change 3415852 on 2017/05/01 by Marc.Audy

	Remove unused code

	#rnx

Change 3415856 on 2017/05/01 by Marc.Audy

	auto removal

	#rnx

Change 3415858 on 2017/05/01 by Marc.Audy

	Fix function taking an input as reference when unneeded and causing (still unclear why it suddenly started showing up) error in cooking

	#rnx

Change 3415946 on 2017/05/01 by Marc.Audy

	Have K2Node_StructOperation skip the K2Node_Variable validation as it doesn't need a property (per CL# 1756451)

	#rnx

Change 3415988 on 2017/05/01 by Lukasz.Furman

	renamed WorldContext param in AI related static blueprint functions to remove load/cook warnings
	#jira UE-44544

Change 3416030 on 2017/05/01 by Ben.Zeigler

	Fix issue with WorldContext pins being broken by my pin value refactor, partial paths like "WorldContext" need to be stored as strings and not as broken object references.

Change 3416230 on 2017/05/01 by Marc.Audy

	Fix spelling error

	#rnx

Change 3416419 on 2017/05/01 by Phillip.Kavan

	#jira UE-44213 - Nativizing a Blueprint class with a non-nativized Blueprint class subobject dependency will no longer lead to a crash at load time.

	Change summary:
	- Modified the FFakeImportTableHelper ctor to inject subobject CDOs into the 'SerializeBeforeCreateCDODependencies' array. This in turn ensures that EDL will serialize those subobject CDOs (if necessary) before we create the subobject's nativized owner's CDO at load time.
	- Modified FEmitDefaultValueHelper::GenerateCustomDynamicClassInitialization() to emit MiscConvertedSubobject instantiations AFTER we emit the FillUsedAssetsInDynamicClass() call. This is now consistent with the code emitted for other subobjects (all of which assumes that the UsedAssets array has been initialized).
	- Modified FFindAssetsToInclude::HandleObjectReference() to add UField owner CDOs in addition to the owner class to the asset dependency list. This ensures that owner CDOs will be emitted alongside the class to both the nativized asset dependency table as well as to the fake import table associated with the UDynamicClass linker for the nativized BP asset.

Change 3416425 on 2017/05/01 by Phillip.Kavan

	#jira UE-44219 - Nativizing a Blueprint class with a nativized DOBP class dependency will no longer lead to a compile error at cook/nativization time.

	- Modified the FGatherConvertedClassDependencies ctor to properly handle DOBPs in exclusive mode that have been explicitly enabled for nativization. Previously, this code wasn't taking that possibility into account, and as a result could lead to a missing header file in a dependent nativized class body's include set.
	- Modified FGatherConvertedClassDependencies::GetFirstNativeOrConvertedClass() to remove the 'bExcludeBPDataOnly' parameter, as it was primarily just being used for a redundant exclusion check when called from the FGatherConvertedClassDependencies ctor. That call site has now been modified to start searching from the super class instead. Additionally, any DOBPs will already fail the preceding WillClassBeConverted() check if they have not been explicitly enabled for nativization in exclusive mode, and will always fail if nativizing in inclusive mode. The extra check was breaking the explicitly-enabled case, so it was removed to allow explicitly-enabled DOBPs to pass.

	Notes:
	- Allowing for explicitly-enabled DOBPs in exclusive mode may be removed in a future change, but since it is currently supported, the changes noted above will at least ensure that the generated code will compile properly for now.

Change 3416570 on 2017/05/01 by mason.seay

	Added UMG test to map.  Tweaked force feedback test

Change 3416580 on 2017/05/01 by mason.seay

	Resubmitting sub levels

Change 3416597 on 2017/05/01 by Dan.Oconnor

	Compilation manager iteration, adds machinery for individual blueprint compilation, adds comments, cleans up duplicated code

Change 3416636 on 2017/05/01 by Phillip.Kavan

	#jira UE-44505 - Potential fix for a low-repro crash tied to the Blueprint graph context menu.

	Change summary:
	- Switched FBlueprintActionInfo::ActionOwner to be a weak object reference.

Change 3416960 on 2017/05/01 by Dan.Oconnor

	Use compilation manager when clicking the compile button, PIE'ing, etc

Change 3417207 on 2017/05/01 by Ben.Zeigler

	Fix issue with None strings causing default value parsing failures
	Add SetPinDefaultValueAtConstruction needed by some other changes

Change 3417519 on 2017/05/01 by Ben.Zeigler

	Fix BP compile errors caused by local variables with invalid default values. There's no reason to set autogenerated here because the nodes are transient and invisible in the UI.
	There is still a problem here, local variables are not getting their default values validated when type is changed, so you end up with an integer that has the default value of a struct.

Change 3418659 on 2017/05/02 by Ben.Zeigler

	#jira UE-44534 Fix it so animation node pins get properly created autogenerated default values that are based on the node struct defaults. This fixes issues when they are reset to other defaults
	#jira UE-44532 Fix it so connecting an animation asset pin on a node player resets the pin value to the autogenerated default instead of the cached asset. This was causing old unused assets to get unnecessarily cooked
	Fix it so any animation node with an exposed pin that is an object property will reset that object propery when the pin is exposed. This fixes UE-31015 in a generic way
	Change the OptionalPinManager to take a Defaults address as well as a current address, to allow setting autogenerated defaults properly
	Remove Import/ExportKismetDefaultValueToProperty as they were redundant with PropertyValueFromString and were using the wrong pin setting functions, replaced with PropertyValueFromString_Direct and calling the schema pin set functions
	I need to write some backward compatibility code to fix existing nodes, I'll do that in a later checkin

Change 3418700 on 2017/05/02 by Ben.Zeigler

	Actually fix None object paths for real this time. I did not test sufficiently before

Change 3418811 on 2017/05/02 by Ben.Zeigler

	Fix existing animation blueprint nodes with dead asset references duplicated by pins. This code can be applied independent of the other change to fix specific games

Change 3419165 on 2017/05/02 by Dan.Oconnor

	Add misc. functionality from FKismetEditorUtilities::CompileBlueprint

Change 3419202 on 2017/05/02 by Marc.Audy

	Merging //UE4/Dev-Main to Dev-Framework (//UE4/Dev-Framework) @ 3417825

	#rnx

Change 3419236 on 2017/05/02 by mason.seay

	Removed OnPressed event from Widget BP

Change 3419314 on 2017/05/02 by Marc.Audy

	Fix bad auto-resolve

	#rnx

Change 3419524 on 2017/05/02 by Marc.Audy

	PR #3528: Improved Input BP library node display names (Contributed by projectgheist)
	#jira UE-44587
	#rn Improved Input BP library node display names

Change 3419570 on 2017/05/02 by Zak.Middleton

	#ue4 - Fix typo in TFunctionRef comment/example.

Change 3419709 on 2017/05/02 by Dan.Oconnor

	Fix missing category metadata on SkeletonGeneratedClass when using compilation manager

Change 3419756 on 2017/05/02 by Dan.Oconnor

	Remove unintentional verbosity increase

Change 3420875 on 2017/05/03 by Marc.Audy

	Make IsExecPin static
	Minor optimization to IsMetaPin

	#rnx

Change 3420981 on 2017/05/03 by Marc.Audy

	Change tagging temporarily until other changes are done so that we don't have warnings in the meantime

	#rnx

Change 3421367 on 2017/05/03 by Marc.Audy

	Manually introduce changes from CL# 3398673 in 4.16 that failed to make it to Dev-Framework as a result of the integration submitted as CL# 3401725.

	#rnx

Change 3421685 on 2017/05/03 by Ben.Zeigler

	#jira UE-23001 Convert literal Asset ID/Class ID pins to store path as string instead of as hard object reference. Old pins are fixed on load, after resaving the hard references will go away
	Refactor the way that FStringAssetReference and FAssetPtr are serialized, it now does the various fixups in FStringAssetReference::SerializePath, which is called from archivers
	Change it so the asset registry reads in a list of all scanned redirectors and adds them to GRedirectCollector, this means that saving a string asset reference will automatically fix it up to point to the redirector destination
	Change the default behavior of FAssetPtr serialize on ArchiveUObject to match what most of it's children want, and remove several special case hacks. It now serializes as asset reference when saving/loading, and as object for other cases
	Deprecate StringAssetReferenceLoaded/StringAssetReferenceSaving delegates, replace with PreSavePath and PostLoadPath on FStringAssetReference
	Make AssetLongPathname private on FStringAssetReference, it was deprecated in 4.9

Change 3421728 on 2017/05/03 by Phillip.Kavan

	Mirror CL 3408285 from //UE4/Release-4.16.

	#jira UE-44124

	#rnx

Change 3422370 on 2017/05/03 by Dan.Oconnor

	Mirror 3422359

	Implement UBlueprintGeneratedClass::NeedsLoadForEditorGame to match UBlueprint, also tag a class's CDO as NeedsLoadForEditorGame.

	This prevents us from failing to load a UBlueprint's GeneratedClass when running the editor with -server.

	#jira UE-44659

Change 3423192 on 2017/05/04 by Ben.Zeigler

	CIS Fix

Change 3423305 on 2017/05/04 by Ben.Zeigler

	Fix "Missing opening parenthesis" warnings for Vector and Rotator the same way they were fixed for Transform

Change 3423358 on 2017/05/04 by Marc.Audy

	Merging //UE4/Dev-Main to Dev-Framework (//UE4/Dev-Framework) @ 3422809

	#rnx

Change 3423766 on 2017/05/04 by Ben.Zeigler

	#jira UE-44680 Delete some corrupted redirectors that are no longer in use

Change 3423804 on 2017/05/04 by Dan.Oconnor

	Honor SaveIntermediateCompilerResults when using compilation manager

Change 3424010 on 2017/05/04 by Marc.Audy

	Validate that switch string cases are unique

Change 3424011 on 2017/05/04 by Marc.Audy

	Re-fix switch node default pin not appearing as an exec output
	Remove unused boolean

Change 3424071 on 2017/05/04 by Ben.Zeigler

	Delete FixupRedirects commandlet, replace with -FixupRedirects/FixupRedirectors option on ResavePackages. This new method is much faster than the old commandlet as it uses the asset registry vs loading all packages, fixing up all redirectors in Fortnite only took about an hour vs 12+ hours the old way
	Removed some hacky bits in Core that only existed to support FixupRedirects
	Change it so the AssetRegistry listens to DirectoryWatcher callbacks in commandlets now that commandlets use the asset registry properly. This won't do anything unless you tick directory watcher the way that ResavePackages does

Change 3424313 on 2017/05/04 by Dan.Oconnor

	Address missing property flags on SkeletonGeneratedClass when using compilation manager
	#jira UE-44705

Change 3424325 on 2017/05/04 by Phillip.Kavan

	#jira UE-44222 - Move nativized UDS implementation details into its own .cpp file in order to avoid circular dependencies.

	Change summary:
	- Modified IKismetCompilerInterface::GenerateCppCodeForStruct() to include an output parameter for CPP source and modified FKismet2CompilerModule to match the updated API.
	- Modified IBlueprintCompilerCppBackend::GenerateCodeFromStruct() to include an output parameter for CPP source and modified FBlueprintCompilerCppBackendBase to match the updated API.
	- Modified FBlueprintNativeCodeGenUtils::GenerateCppCode() to adjust the call to GenerateCppCodeForStruct() to include CPP source output.
	- Modified FGatherConvertedClassDependencies::DependenciesForHeader() to switch UDS property dependencies to be forward declarations rather than includes (for default value init code).
	- Modified FEmitDefaultValueHelper::GenerateGetDefaultValue() to emit implementation details to the 'Body' container, and adjust the header content to be a declaration only.
	- Modified FIncludeHeaderHelper::EmitInner() to exclude a potentially-redundant line for the module's .h file, for the case when the caller has included the base filename in the 'AlreadyIncluded' set.
	- Modified FEmitterLocalContext::FindGloballyMappedObject() to limit the 'TryUsedAssetsList' path to UClass conversions only (since that requires a UDynamicClass target to work).
	- Modified FGatherConvertedClassDependencies::DependenciesForHeader() to only include BPGC fields if they are also being converted. Eliminates an issue with missing header files in generated code.

Change 3424359 on 2017/05/04 by Ben.Zeigler

	Fix issue where StreamableManager would break when requesting an async load that failed the first time. Because our game supports downloading assets during gameplay it's not safe to assume it will never load again.
	Port of CL #3424159

Change 3424367 on 2017/05/04 by Ben.Zeigler

	Fix some asset manager warnings to not go off in invalid cases

Change 3425270 on 2017/05/05 by Marc.Audy

	Pack booleans/enums in UEdGraphNode and FOptionalPinFromProperty

	#rnx

Change 3425696 on 2017/05/05 by Ben.Zeigler

	#jira UE-44672 Fix it so select node option pins get populated with default values properly
	#jira UE-43927 Fix it so select node opion pin type is correctly maintained accross node recreation, as opposed to deriving from the attached pins
	#jira UE-44675 Fix it to correctly refresh select node when switching from bool to integer index

Change 3425833 on 2017/05/05 by Ben.Zeigler

	#jira UE-31749 Fix it so Undo works properly when modifying a local variable
	#jira UE-44736 Fix it so changing the type of a local variable correctly resets the default value

Change 3425890 on 2017/05/05 by Marc.Audy

	Fix Copy/Paste of child actor components losing the template
	#jira UE-44566

Change 3425947 on 2017/05/05 by Ben.Zeigler

	This was meant to be part of last checkin

Change 3425959 on 2017/05/05 by Ben.Zeigler

	#jira UE-44692 Fix it so only the sequentially last node can be removed from a Switch On Int, and for Switch On Name stop it from removing an exec pin if it's the only non-default one

Change 3425979 on 2017/05/05 by Dan.Oconnor

	PVS fix

Change 3425985 on 2017/05/05 by Phillip.Kavan

	Fix an uninitialized variable.

	#rnx

Change 3426043 on 2017/05/05 by Ben.Zeigler

	#jira UE-35583 Correctly refresh array node UI when connecting pins that change it away from wildcard

Change 3426174 on 2017/05/05 by Zak.Middleton

	#ue4 - Avoid call to virtual getSimulationFilterData() to only use it when needed in PreFilter if we actually have items in the IgnoreComponents list (which is rare). The sim filter data 'word2' stores the component ID.

Change 3426621 on 2017/05/05 by Phillip.Kavan

	#jira UE-44708 - Fix an issue that re-introduced component data loss in a non-nativized child Blueprint class with a nativized parent Blueprint class.

	Change summary:
	- Removed an unnecessary additional check I had for the presence of "-NativizeAssets" switch on the command line in UBlueprint::BeginCacheForCookedPlatformData(). This check was failing because the usage was recently changed to include an optional value. It was not needed anyway so I just removed it.

	#rnx

Change 3426906 on 2017/05/05 by Ben.Zeigler

	#jira UE-11189 Fix function/macro input default values to show as a pin customization instead of as a broken text box that doesn't work correctly for most types. This fixes enums and provide validation for other types
	Types that don't have a customization (most structs) will now show any more, they did not work before either
	#jira UE-21754 Hide function default values if pass by reference is set
	Fix it so changing input parameter will also reset default value, to avoid having the wrong type value set and to work the same as local variables

Change 3426941 on 2017/05/05 by Dan.Oconnor

	Fix determinstic cooking of LoadAssetClass nodes in macros

Change 3427021 on 2017/05/05 by Dan.Oconnor

	Build fix, make initialization order in source match artifact

	#rnx

Change 3427135 on 2017/05/05 by Phillip.Kavan

	#jira UE-44702 - Restore code-based interface classes to Blueprint editor UI.

	Change summary:
	- Partially backed out CL# 3348513 to return to previous behavior for 4.16. The UI is no longer filtering on the __is_abstract() type trait for interface classes.
	- Modified FNativeClassHeaderGenerator::ExportClassFromSourceFileInner() to emit the _getUObject() declaration for native interface types as a default implementation that returns NULL rather than as a pure virtual declaration.

	#rnx

Change 3427144 on 2017/05/06 by Marc.Audy

	Fix init order

	#rnx

Change 3427146 on 2017/05/06 by Marc.Audy

	remove stray semicolon

	#rnx

Change 3427242 on 2017/05/06 by Phillip.Kavan

	#jira UE-44744 - Fix a regression in which a UMG Widget Blueprint property not explicitly marked as a variable would cause Blueprint nativization to fail at package time.

	Change summary:
	- Modified FWidgetBlueprintCompiler::CreateClassVariablesFromBlueprint() to only add 'Category' metadata when we set the 'CPF_BlueprintVisible' flag on the UProperty, which in is now tied to whether or not the property has been explcitly marked as a variable. This avoids a UHT warning when compiling the nativized codegen that would cause packaging to fail.

	#rnx

Change 3427720 on 2017/05/08 by Dan.Oconnor

	Backing out 3419202

	#rnx

Change 3427725 on 2017/05/08 by Dan.Oconnor

	SA fix

	#rnx

Change 3427734 on 2017/05/08 by Dan.Oconnor

	More exhaustive GEditor null checks, to appease SA

	#rnx

Change 3427882 on 2017/05/08 by Marc.Audy

	Properly order all booleans in intialization

	#rnx

Change 3428049 on 2017/05/08 by Marc.Audy

	Merging //UE4/Dev-Main to Dev-Framework (//UE4/Dev-Framework) @ 3427804

	#rnx

Change 3428523 on 2017/05/08 by Ben.Zeigler

	#jira UE-44781 Refresh function input UI when blueprint graph refreshes, needed as pins may have gone away

Change 3428563 on 2017/05/08 by Ben.Zeigler

	#jira UE-44783 If setting a hard reference pin type from a string, load the referenced object.

Change 3428595 on 2017/05/08 by Dan.Oconnor

	Avoid node reconstruction when we're compiling a blueprint with no linker (e.g., a duplicated blueprint)

	#jira UE-44777

Change 3428599 on 2017/05/08 by Ben.Zeigler

	#jira UE-44789 Fix string asset renamer to not mark IsPersistent becuase that crashes in lightmap code, change it so the path fixup doesn't require the persistent flag

Change 3428609 on 2017/05/08 by Dan.Oconnor

	Improved fix for UE-44777

	#jira UE-44777
	#rnx

Change 3429176 on 2017/05/08 by Phillip.Kavan

	#jira UE-44755 - Fix nativization build errors when packaging a game project that is not IWYU-compliant for a build target that disables PCH files.

	- Mirrored from //UE4/Release-4.16 (CL# 3429030).

	#rnx

Change 3429198 on 2017/05/08 by Phillip.Kavan

	CIS fix.

	#rnx

Change 3429583 on 2017/05/08 by Ben.Zeigler

	Fix SGraphPinClass to work properly after my changes to allow unloaded assets. For Class pins we need to store separate Runtime and Editor asset data objects, as one has _C and refers to the class, and the other doesn't and refers to the blueprint. The content browser wants the editor path, the pin defaults want the runtime path.
	Change default value widgets to look more like properties widgets by forcing them to act as highlighted and disabling black background

Change 3429640 on 2017/05/08 by Marc.Audy

	Fix issues with select nodes in macros connected to wildcard pins.
	#jira UE-44799

	#rnx

Change 3429890 on 2017/05/08 by Ben.Zeigler

	Fix function/macro defaults to properly propagate when changed using the new edit UI
	Refactor some code out of the details customization into the k2 schema
	Disable defaults UI for object/class/interface hard references as it is disabled in KismetCompiler

Change 3429947 on 2017/05/08 by Michael.Noland

	Core: Backing out CL# 3394352 (marking FDateTime and FTimespan nonexport member Tick with UPROPERTY()), which will re-break UE-39921 but fix UE-44418
	There appears to be a more serious underlying issue with how the CDO is instanced which needs to be addressed
	#jira UE-44418

	#reimplementing 3411681 from Release 4.16

Change 3429987 on 2017/05/08 by Ben.Zeigler

	#jira UE-44798 Do a better job of validating object paths saved as default values, due to an old bug with local variables some object paths are saved as struct exportext
	At load time clear invalid default value for local variables
	Add IsValidObjectPath to FPackageName that validates the passed in path would be valid to load with LoadObject

Change 3430392 on 2017/05/09 by Marc.Audy

	Fix SA CIS error

	#rnx

Change 3430747 on 2017/05/09 by Ben.Zeigler

	#jira UE-44836 Don't reconstruct node during callback for param value changing, this can happen during a reconstruction and recursive reconstruction is unsafe
	Don't call ModifyUserDefinedPinDefaultValue unless the default value has actually changed

Change 3431027 on 2017/05/09 by Marc.Audy

	Fix BPRW mark up causing Ocean warnings

	#rnx

Change 3431353 on 2017/05/09 by Marc.Audy

	Fix UHT error due to exposing FJsonObjectWrapper to blueprints

	#rnx

[CL 3431398 by Marc Audy in Main branch]
2017-05-09 17:15:32 -04:00

3783 lines
132 KiB
C++

// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "GameProjectUtils.h"
#include "Misc/Guid.h"
#include "UObject/Class.h"
#include "FeaturePackContentSource.h"
#include "TemplateProjectDefs.h"
#include "HAL/PlatformFilemanager.h"
#include "Misc/MessageDialog.h"
#include "HAL/FileManager.h"
#include "Misc/CommandLine.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"
#include "Misc/ConfigCacheIni.h"
#include "Misc/ScopedSlowTask.h"
#include "Misc/App.h"
#include "Misc/EngineVersion.h"
#include "Widgets/DeclarativeSyntaxSupport.h"
#include "Widgets/SWindow.h"
#include "Framework/Application/SlateApplication.h"
#include "Components/ActorComponent.h"
#include "Components/SceneComponent.h"
#include "GameFramework/Actor.h"
#include "GameFramework/Pawn.h"
#include "Editor/EditorPerProjectUserSettings.h"
#include "ISourceControlOperation.h"
#include "SourceControlOperations.h"
#include "ISourceControlProvider.h"
#include "ISourceControlModule.h"
#include "GeneralProjectSettings.h"
#include "GameFramework/Character.h"
#include "Misc/FeedbackContext.h"
#include "UObject/UObjectHash.h"
#include "UObject/UObjectIterator.h"
#include "GameFramework/GameModeBase.h"
#include "UnrealEdMisc.h"
#include "PluginDescriptor.h"
#include "Interfaces/IPluginManager.h"
#include "ProjectDescriptor.h"
#include "Interfaces/IProjectManager.h"
#include "GameProjectGenerationLog.h"
#include "DefaultTemplateProjectDefs.h"
#include "SNewClassDialog.h"
#include "FeaturedClasses.inl"
#include "Interfaces/IMainFrameModule.h"
#include "AnalyticsEventAttribute.h"
#include "Interfaces/IAnalyticsProvider.h"
#include "EngineAnalytics.h"
#include "DesktopPlatformModule.h"
#include "Interfaces/ITargetPlatform.h"
#include "Interfaces/ITargetPlatformManagerModule.h"
#include "Styling/SlateIconFinder.h"
#include "SourceCodeNavigation.h"
#include "Misc/UProjectInfo.h"
#include "Framework/Notifications/NotificationManager.h"
#include "Widgets/Notifications/SNotificationList.h"
#include "Misc/HotReloadInterface.h"
#include "Dialogs/SOutputLogDialog.h"
#include "Sound/SoundEffectSubmix.h"
#include "Sound/SoundEffectSource.h"
#include "Components/SynthComponent.h"
#include "PlatformInfo.h"
#include "Blueprint/BlueprintSupport.h"
#define LOCTEXT_NAMESPACE "GameProjectUtils"
#define MAX_PROJECT_PATH_BUFFER_SPACE 130 // Leave a reasonable buffer of additional characters to account for files created in the content directory during or after project generation
#define MAX_PROJECT_NAME_LENGTH 20 // Enforce a reasonable project name length so the path is not too long for PLATFORM_MAX_FILEPATH_LENGTH
static_assert(PLATFORM_MAX_FILEPATH_LENGTH - MAX_PROJECT_PATH_BUFFER_SPACE > 0, "File system path shorter than project creation buffer space.");
#define MAX_CLASS_NAME_LENGTH 32 // Enforce a reasonable class name length so the path is not too long for PLATFORM_MAX_FILEPATH_LENGTH
TWeakPtr<SNotificationItem> GameProjectUtils::UpdateGameProjectNotification = NULL;
TWeakPtr<SNotificationItem> GameProjectUtils::WarningProjectNameNotification = NULL;
FString GameProjectUtils::DefaultFeaturePackExtension(TEXT(".upack"));
FText FNewClassInfo::GetClassName() const
{
switch(ClassType)
{
case EClassType::UObject:
return BaseClass ? BaseClass->GetDisplayNameText() : FText::GetEmpty();
case EClassType::EmptyCpp:
return LOCTEXT("NoParentClass", "None");
case EClassType::SlateWidget:
return LOCTEXT("SlateWidgetParentClass", "Slate Widget");
case EClassType::SlateWidgetStyle:
return LOCTEXT("SlateWidgetStyleParentClass", "Slate Widget Style");
case EClassType::UInterface:
return LOCTEXT("UInterfaceParentClass", "Unreal Interface");
default:
break;
}
return FText::GetEmpty();
}
FText FNewClassInfo::GetClassDescription(const bool bFullDescription/* = true*/) const
{
switch(ClassType)
{
case EClassType::UObject:
{
if(BaseClass)
{
FString ClassDescription = BaseClass->GetToolTipText(/*bShortTooltip=*/!bFullDescription).ToString();
if(!bFullDescription)
{
int32 FullStopIndex = 0;
if(ClassDescription.FindChar('.', FullStopIndex))
{
// Only show the first sentence so as not to clutter up the UI with a detailed description of implementation details
ClassDescription = ClassDescription.Left(FullStopIndex + 1);
}
// Strip out any new-lines in the description
ClassDescription.ReplaceInline(TEXT("\n"), TEXT(" "));
}
return FText::FromString(ClassDescription);
}
}
break;
case EClassType::EmptyCpp:
return LOCTEXT("EmptyClassDescription", "An empty C++ class with a default constructor and destructor.");
case EClassType::SlateWidget:
return LOCTEXT("SlateWidgetClassDescription", "A custom Slate widget, deriving from SCompoundWidget.");
case EClassType::SlateWidgetStyle:
return LOCTEXT("SlateWidgetStyleClassDescription", "A custom Slate widget style, deriving from FSlateWidgetStyle, along with its associated UObject wrapper class.");
case EClassType::UInterface:
return LOCTEXT("UInterfaceClassDescription", "A UObject Interface class, to be implemented by other UObject-based classes.");
default:
break;
}
return FText::GetEmpty();
}
const FSlateBrush* FNewClassInfo::GetClassIcon() const
{
// Safe to do even if BaseClass is null, since FindIconForClass will return the default icon
return FSlateIconFinder::FindIconBrushForClass(BaseClass);
}
FString FNewClassInfo::GetClassPrefixCPP() const
{
switch(ClassType)
{
case EClassType::UObject:
return BaseClass ? BaseClass->GetPrefixCPP() : TEXT("");
case EClassType::EmptyCpp:
return TEXT("");
case EClassType::SlateWidget:
return TEXT("S");
case EClassType::SlateWidgetStyle:
return TEXT("F");
case EClassType::UInterface:
return TEXT("U");
default:
break;
}
return TEXT("");
}
FString FNewClassInfo::GetClassNameCPP() const
{
switch(ClassType)
{
case EClassType::UObject:
return BaseClass ? BaseClass->GetName() : TEXT("");
case EClassType::EmptyCpp:
return TEXT("");
case EClassType::SlateWidget:
return TEXT("CompoundWidget");
case EClassType::SlateWidgetStyle:
return TEXT("SlateWidgetStyle");
case EClassType::UInterface:
return TEXT("Interface");
default:
break;
}
return TEXT("");
}
FString FNewClassInfo::GetCleanClassName(const FString& ClassName) const
{
FString CleanClassName = ClassName;
switch(ClassType)
{
case EClassType::SlateWidgetStyle:
{
// Slate widget style classes always take the form FMyThingWidget, and UMyThingWidgetStyle
// if our class ends with either Widget or WidgetStyle, we need to strip those out to avoid silly looking duplicates
if(CleanClassName.EndsWith(TEXT("Style")))
{
CleanClassName = CleanClassName.LeftChop(5); // 5 for "Style"
}
if(CleanClassName.EndsWith(TEXT("Widget")))
{
CleanClassName = CleanClassName.LeftChop(6); // 6 for "Widget"
}
}
break;
default:
break;
}
return CleanClassName;
}
FString FNewClassInfo::GetFinalClassName(const FString& ClassName) const
{
const FString CleanClassName = GetCleanClassName(ClassName);
switch(ClassType)
{
case EClassType::SlateWidgetStyle:
return FString::Printf(TEXT("%sWidgetStyle"), *CleanClassName);
default:
break;
}
return CleanClassName;
}
bool FNewClassInfo::GetIncludePath(FString& OutIncludePath) const
{
switch(ClassType)
{
case EClassType::UObject:
if(BaseClass && BaseClass->HasMetaData(TEXT("IncludePath")))
{
OutIncludePath = BaseClass->GetMetaData(TEXT("IncludePath"));
return true;
}
break;
case EClassType::SlateWidget:
OutIncludePath = "Widgets/SCompoundWidget.h";
return true;
case EClassType::SlateWidgetStyle:
OutIncludePath = "Styling/SlateWidgetStyle.h";
return true;
default:
break;
}
return false;
}
FString FNewClassInfo::GetBaseClassHeaderFilename() const
{
FString IncludePath;
switch (ClassType)
{
case EClassType::UObject:
if (BaseClass)
{
FString ClassHeaderPath;
if (FSourceCodeNavigation::FindClassHeaderPath(BaseClass, ClassHeaderPath) && IFileManager::Get().FileSize(*ClassHeaderPath) != INDEX_NONE)
{
return ClassHeaderPath;
}
}
break;
case EClassType::SlateWidget:
case EClassType::SlateWidgetStyle:
GetIncludePath(IncludePath);
return FPaths::EngineDir() / TEXT("Source") / TEXT("Runtime") / TEXT("SlateCore") / TEXT("Public") / IncludePath;
default:
return FString();
}
return FString();
}
FString FNewClassInfo::GetHeaderFilename(const FString& ClassName) const
{
const FString HeaderFilename = GetFinalClassName(ClassName) + TEXT(".h");
switch(ClassType)
{
case EClassType::SlateWidget:
return TEXT("S") + HeaderFilename;
default:
break;
}
return HeaderFilename;
}
FString FNewClassInfo::GetSourceFilename(const FString& ClassName) const
{
const FString SourceFilename = GetFinalClassName(ClassName) + TEXT(".cpp");
switch(ClassType)
{
case EClassType::SlateWidget:
return TEXT("S") + SourceFilename;
default:
break;
}
return SourceFilename;
}
FString FNewClassInfo::GetHeaderTemplateFilename() const
{
switch(ClassType)
{
case EClassType::UObject:
{
if (BaseClass != nullptr)
{
if ((BaseClass == UActorComponent::StaticClass()) || (BaseClass == USceneComponent::StaticClass()))
{
return TEXT("ActorComponentClass.h.template");
}
else if (BaseClass == AActor::StaticClass())
{
return TEXT("ActorClass.h.template");
}
else if (BaseClass == APawn::StaticClass())
{
return TEXT("PawnClass.h.template");
}
else if (BaseClass == ACharacter::StaticClass())
{
return TEXT("CharacterClass.h.template");
}
else if (BaseClass == USoundEffectSourcePreset::StaticClass())
{
return TEXT("SoundEffectSourceClass.h.template");
}
else if (BaseClass == USoundEffectSubmixPreset::StaticClass())
{
return TEXT("SoundEffectSubmixClass.h.template");
}
else if (BaseClass == USynthComponent::StaticClass())
{
return TEXT("SynthComponentClass.h.template");
}
}
// Some other non-actor, non-component UObject class
return TEXT( "UObjectClass.h.template" );
}
case EClassType::EmptyCpp:
return TEXT("EmptyClass.h.template");
case EClassType::SlateWidget:
return TEXT("SlateWidget.h.template");
case EClassType::SlateWidgetStyle:
return TEXT("SlateWidgetStyle.h.template");
case EClassType::UInterface:
return TEXT("InterfaceClass.h.template");
default:
break;
}
return TEXT("");
}
FString FNewClassInfo::GetSourceTemplateFilename() const
{
switch(ClassType)
{
case EClassType::UObject:
if (BaseClass != nullptr)
{
if ((BaseClass == UActorComponent::StaticClass()) || (BaseClass == USceneComponent::StaticClass()))
{
return TEXT("ActorComponentClass.cpp.template");
}
else if (BaseClass == AActor::StaticClass())
{
return TEXT("ActorClass.cpp.template");
}
else if (BaseClass == APawn::StaticClass())
{
return TEXT("PawnClass.cpp.template");
}
else if (BaseClass == ACharacter::StaticClass())
{
return TEXT("CharacterClass.cpp.template");
}
else if (BaseClass == USoundEffectSubmixPreset::StaticClass())
{
return TEXT("SoundEffectSubmixClass.cpp.template");
}
else if (BaseClass == USoundEffectSourcePreset::StaticClass())
{
return TEXT("SoundEffectSourceClass.cpp.template");
}
else if (BaseClass == USynthComponent::StaticClass())
{
return TEXT("SynthComponentClass.cpp.template");
}
}
// Some other non-actor, non-component UObject class
return TEXT( "UObjectClass.cpp.template" );
case EClassType::EmptyCpp:
return TEXT("EmptyClass.cpp.template");
case EClassType::SlateWidget:
return TEXT("SlateWidget.cpp.template");
case EClassType::SlateWidgetStyle:
return TEXT("SlateWidgetStyle.cpp.template");
case EClassType::UInterface:
return TEXT("InterfaceClass.cpp.template");
default:
break;
}
return TEXT("");
}
bool GameProjectUtils::IsValidProjectFileForCreation(const FString& ProjectFile, FText& OutFailReason)
{
const FString BaseProjectFile = FPaths::GetBaseFilename(ProjectFile);
if ( FPaths::GetPath(ProjectFile).IsEmpty() )
{
OutFailReason = LOCTEXT( "NoProjectPath", "You must specify a path." );
return false;
}
if ( BaseProjectFile.IsEmpty() )
{
OutFailReason = LOCTEXT( "NoProjectName", "You must specify a project name." );
return false;
}
if ( BaseProjectFile.Contains(TEXT(" ")) )
{
OutFailReason = LOCTEXT( "ProjectNameContainsSpace", "Project names may not contain a space." );
return false;
}
if ( !FChar::IsAlpha(BaseProjectFile[0]) )
{
OutFailReason = LOCTEXT( "ProjectNameMustBeginWithACharacter", "Project names must begin with an alphabetic character." );
return false;
}
if ( BaseProjectFile.Len() > MAX_PROJECT_NAME_LENGTH )
{
FFormatNamedArguments Args;
Args.Add( TEXT("MaxProjectNameLength"), MAX_PROJECT_NAME_LENGTH );
OutFailReason = FText::Format( LOCTEXT( "ProjectNameTooLong", "Project names must not be longer than {MaxProjectNameLength} characters." ), Args );
return false;
}
const int32 MaxProjectPathLength = PLATFORM_MAX_FILEPATH_LENGTH - MAX_PROJECT_PATH_BUFFER_SPACE;
if ( FPaths::GetBaseFilename(ProjectFile, false).Len() > MaxProjectPathLength )
{
FFormatNamedArguments Args;
Args.Add( TEXT("MaxProjectPathLength"), MaxProjectPathLength );
OutFailReason = FText::Format( LOCTEXT( "ProjectPathTooLong", "A project's path must not be longer than {MaxProjectPathLength} characters." ), Args );
return false;
}
if ( FPaths::GetExtension(ProjectFile) != FProjectDescriptor::GetExtension() )
{
FFormatNamedArguments Args;
Args.Add( TEXT("ProjectFileExtension"), FText::FromString( FProjectDescriptor::GetExtension() ) );
OutFailReason = FText::Format( LOCTEXT( "InvalidProjectFileExtension", "File extension is not {ProjectFileExtension}" ), Args );
return false;
}
FString IllegalNameCharacters;
if ( !NameContainsOnlyLegalCharacters(BaseProjectFile, IllegalNameCharacters) )
{
FFormatNamedArguments Args;
Args.Add( TEXT("IllegalNameCharacters"), FText::FromString( IllegalNameCharacters ) );
OutFailReason = FText::Format( LOCTEXT( "ProjectNameContainsIllegalCharacters", "Project names may not contain the following characters: {IllegalNameCharacters}" ), Args );
return false;
}
if (NameContainsUnderscoreAndXB1Installed(BaseProjectFile))
{
OutFailReason = LOCTEXT( "ProjectNameContainsIllegalCharactersOnXB1", "Project names may not contain an underscore when the Xbox One XDK is installed." );
return false;
}
if ( !FPaths::ValidatePath(FPaths::GetPath(ProjectFile), &OutFailReason) )
{
return false;
}
if ( ProjectFileExists(ProjectFile) )
{
OutFailReason = LOCTEXT( "ProjectFileAlreadyExists", "This project file already exists." );
return false;
}
if ( FPaths::ConvertRelativePathToFull(FPaths::GetPath(ProjectFile)).StartsWith( FPaths::ConvertRelativePathToFull(FPaths::EngineDir())) )
{
OutFailReason = LOCTEXT( "ProjectFileCannotBeUnderEngineFolder", "Project cannot be saved under the Engine folder. Please choose a different directory." );
return false;
}
if ( AnyProjectFilesExistInFolder(FPaths::GetPath(ProjectFile)) )
{
FFormatNamedArguments Args;
Args.Add( TEXT("ProjectFileExtension"), FText::FromString( FProjectDescriptor::GetExtension() ) );
OutFailReason = FText::Format( LOCTEXT( "AProjectFileAlreadyExistsAtLoction", "Another .{ProjectFileExtension} file already exists in the specified folder" ), Args );
return false;
}
// Don't allow any files within target directory so we can safely delete everything on failure
TArray<FString> ExistingFiles;
IFileManager::Get().FindFiles(ExistingFiles, *(FPaths::GetPath(ProjectFile) / TEXT("*")), true, true);
if (ExistingFiles.Num() > 0)
{
OutFailReason = LOCTEXT("ProjectFileCannotBeWithExistingFiles", "Project cannot be saved in a folder with existing files. Please choose a different directory/project name.");
return false;
}
return true;
}
bool GameProjectUtils::OpenProject(const FString& ProjectFile, FText& OutFailReason)
{
if ( ProjectFile.IsEmpty() )
{
OutFailReason = LOCTEXT( "NoProjectFileSpecified", "You must specify a project file." );
return false;
}
const FString BaseProjectFile = FPaths::GetBaseFilename(ProjectFile);
if ( BaseProjectFile.Contains(TEXT(" ")) )
{
OutFailReason = LOCTEXT( "ProjectNameContainsSpace", "Project names may not contain a space." );
return false;
}
if ( !FChar::IsAlpha(BaseProjectFile[0]) )
{
OutFailReason = LOCTEXT( "ProjectNameMustBeginWithACharacter", "Project names must begin with an alphabetic character." );
return false;
}
const int32 MaxProjectPathLength = PLATFORM_MAX_FILEPATH_LENGTH - MAX_PROJECT_PATH_BUFFER_SPACE;
if ( FPaths::GetBaseFilename(ProjectFile, false).Len() > MaxProjectPathLength )
{
FFormatNamedArguments Args;
Args.Add( TEXT("MaxProjectPathLength"), MaxProjectPathLength );
OutFailReason = FText::Format( LOCTEXT( "ProjectPathTooLong", "A project's path must not be longer than {MaxProjectPathLength} characters." ), Args );
return false;
}
if ( FPaths::GetExtension(ProjectFile) != FProjectDescriptor::GetExtension() )
{
FFormatNamedArguments Args;
Args.Add( TEXT("ProjectFileExtension"), FText::FromString( FProjectDescriptor::GetExtension() ) );
OutFailReason = FText::Format( LOCTEXT( "InvalidProjectFileExtension", "File extension is not {ProjectFileExtension}" ), Args );
return false;
}
FString IllegalNameCharacters;
if ( !NameContainsOnlyLegalCharacters(BaseProjectFile, IllegalNameCharacters) )
{
FFormatNamedArguments Args;
Args.Add( TEXT("IllegalNameCharacters"), FText::FromString( IllegalNameCharacters ) );
OutFailReason = FText::Format( LOCTEXT( "ProjectNameContainsIllegalCharacters", "Project names may not contain the following characters: {IllegalNameCharacters}" ), Args );
return false;
}
if (NameContainsUnderscoreAndXB1Installed(BaseProjectFile))
{
OutFailReason = LOCTEXT( "ProjectNameContainsIllegalCharactersOnXB1", "Project names may not contain an underscore when the Xbox One XDK is installed." );
return false;
}
if ( !FPaths::ValidatePath(FPaths::GetPath(ProjectFile), &OutFailReason) )
{
return false;
}
if ( !ProjectFileExists(ProjectFile) )
{
FFormatNamedArguments Args;
Args.Add( TEXT("ProjectFile"), FText::FromString( ProjectFile ) );
OutFailReason = FText::Format( LOCTEXT( "ProjectFileDoesNotExist", "{ProjectFile} does not exist." ), Args );
return false;
}
FUnrealEdMisc::Get().SwitchProject(ProjectFile, false);
return true;
}
bool GameProjectUtils::OpenCodeIDE(const FString& ProjectFile, FText& OutFailReason)
{
if ( ProjectFile.IsEmpty() )
{
OutFailReason = LOCTEXT( "NoProjectFileSpecified", "You must specify a project file." );
return false;
}
// Check whether this project is a foreign project. Don't use the cached project dictionary; we may have just created a new project.
FString SolutionFolder;
FString SolutionFilenameWithoutExtension;
if( FUProjectDictionary(FPaths::RootDir()).IsForeignProject(ProjectFile) )
{
SolutionFolder = IFileManager::Get().ConvertToAbsolutePathForExternalAppForRead(*FPaths::GetPath(ProjectFile));
SolutionFilenameWithoutExtension = FPaths::GetBaseFilename(ProjectFile);
}
else
{
SolutionFolder = IFileManager::Get().ConvertToAbsolutePathForExternalAppForRead(*FPaths::RootDir());
SolutionFilenameWithoutExtension = TEXT("UE4");
}
// Get the solution filename
FString CodeSolutionFile;
#if PLATFORM_WINDOWS
CodeSolutionFile = SolutionFilenameWithoutExtension + TEXT(".sln");
#elif PLATFORM_MAC
CodeSolutionFile = SolutionFilenameWithoutExtension + TEXT(".xcworkspace");
#elif PLATFORM_LINUX
// FIXME: Should depend on PreferredAccessor setting
CodeSolutionFile = SolutionFilenameWithoutExtension + TEXT(".workspace");
#else
OutFailReason = LOCTEXT( "OpenCodeIDE_UnknownPlatform", "could not open the code editing IDE. The operating system is unknown." );
return false;
#endif
// Open the solution with the default application
const FString FullPath = FPaths::Combine(*SolutionFolder, *CodeSolutionFile);
#if PLATFORM_MAC
if ( IFileManager::Get().DirectoryExists(*FullPath) )
#else
if ( FPaths::FileExists(FullPath) )
#endif
{
FPlatformProcess::LaunchFileInDefaultExternalApplication( *FullPath );
return true;
}
else
{
FFormatNamedArguments Args;
Args.Add( TEXT("Path"), FText::FromString( FullPath ) );
OutFailReason = FText::Format( LOCTEXT( "OpenCodeIDE_MissingFile", "Could not edit the code editing IDE. {Path} could not be found." ), Args );
return false;
}
}
void GameProjectUtils::GetStarterContentFiles(TArray<FString>& OutFilenames)
{
FString const SrcFolder = FPaths::FeaturePackDir();
FString SearchPath = TEXT("*");
SearchPath += DefaultFeaturePackExtension;
IFileManager::Get().FindFilesRecursive(OutFilenames, *SrcFolder, *SearchPath, /*Files=*/true, /*Directories=*/false);
}
bool GameProjectUtils::CreateProject(const FProjectInformation& InProjectInfo, FText& OutFailReason, FText& OutFailLog, TArray<FString>* OutCreatedFiles)
{
if ( !IsValidProjectFileForCreation(InProjectInfo.ProjectFilename, OutFailReason) )
{
return false;
}
FScopedSlowTask SlowTask(0, LOCTEXT( "CreatingProjectStatus", "Creating project..." ));
SlowTask.MakeDialog();
bool bProjectCreationSuccessful = false;
FString TemplateName;
if ( InProjectInfo.TemplateFile.IsEmpty() )
{
bProjectCreationSuccessful = GenerateProjectFromScratch(InProjectInfo, OutFailReason, OutFailLog);
TemplateName = InProjectInfo.bShouldGenerateCode ? TEXT("Basic Code") : TEXT("Blank");
}
else
{
bProjectCreationSuccessful = CreateProjectFromTemplate(InProjectInfo, OutFailReason, OutFailLog, OutCreatedFiles);
TemplateName = FPaths::GetBaseFilename(InProjectInfo.TemplateFile);
}
if (!bProjectCreationSuccessful && CleanupIsEnabled())
{
// Delete the new project folder
const FString NewProjectFolder = FPaths::GetPath(InProjectInfo.ProjectFilename);
IFileManager::Get().DeleteDirectory(*NewProjectFolder, /*RequireExists=*/false, /*Tree=*/true);
if( OutCreatedFiles != nullptr )
{
OutCreatedFiles->Empty();
}
}
if( FEngineAnalytics::IsAvailable() )
{
TArray<FAnalyticsEventAttribute> EventAttributes;
EventAttributes.Add(FAnalyticsEventAttribute(TEXT("Template"), TemplateName));
EventAttributes.Add(FAnalyticsEventAttribute(TEXT("ProjectType"), InProjectInfo.bShouldGenerateCode ? TEXT("C++ Code") : TEXT("Content Only")));
EventAttributes.Add(FAnalyticsEventAttribute(TEXT("Outcome"), bProjectCreationSuccessful ? TEXT("Successful") : TEXT("Failed")));
UEnum* Enum = FindObject<UEnum>(ANY_PACKAGE, TEXT("EHardwareClass"), true);
EventAttributes.Add(FAnalyticsEventAttribute(TEXT("HardwareClass"), Enum ? Enum->GetNameStringByValue(InProjectInfo.TargetedHardware) : FString()));
Enum = FindObject<UEnum>(ANY_PACKAGE, TEXT("EGraphicsPreset"), true);
EventAttributes.Add(FAnalyticsEventAttribute(TEXT("GraphicsPreset"), Enum ? Enum->GetNameStringByValue(InProjectInfo.DefaultGraphicsPerformance) : FString()));
EventAttributes.Add(FAnalyticsEventAttribute(TEXT("StarterContent"), InProjectInfo.bCopyStarterContent ? TEXT("Yes") : TEXT("No")));
FEngineAnalytics::GetProvider().RecordEvent( TEXT( "Editor.NewProject.ProjectCreated" ), EventAttributes );
}
return bProjectCreationSuccessful;
}
void GameProjectUtils::CheckForOutOfDateGameProjectFile()
{
if ( FPaths::IsProjectFilePathSet() )
{
if (IProjectManager::Get().IsCurrentProjectDirty())
{
FText FailMessage;
TryMakeProjectFileWriteable(FPaths::GetProjectFilePath());
if (!IProjectManager::Get().SaveCurrentProjectToDisk(FailMessage))
{
FMessageDialog::Open(EAppMsgType::Ok, FailMessage);
}
}
FProjectStatus ProjectStatus;
if (IProjectManager::Get().QueryStatusForCurrentProject(ProjectStatus))
{
if ( ProjectStatus.bRequiresUpdate )
{
const FText UpdateProjectText = LOCTEXT("UpdateProjectFilePrompt", "Project file is saved in an older format. Would you like to update it?");
const FText UpdateProjectConfirmText = LOCTEXT("UpdateProjectFileConfirm", "Update");
const FText UpdateProjectCancelText = LOCTEXT("UpdateProjectFileCancel", "Not Now");
FNotificationInfo Info(UpdateProjectText);
Info.bFireAndForget = false;
Info.bUseLargeFont = false;
Info.bUseThrobber = false;
Info.bUseSuccessFailIcons = false;
Info.FadeOutDuration = 3.f;
Info.ButtonDetails.Add(FNotificationButtonInfo(UpdateProjectConfirmText, FText(), FSimpleDelegate::CreateStatic(&GameProjectUtils::OnUpdateProjectConfirm)));
Info.ButtonDetails.Add(FNotificationButtonInfo(UpdateProjectCancelText, FText(), FSimpleDelegate::CreateStatic(&GameProjectUtils::OnUpdateProjectCancel)));
if (UpdateGameProjectNotification.IsValid())
{
UpdateGameProjectNotification.Pin()->ExpireAndFadeout();
UpdateGameProjectNotification.Reset();
}
UpdateGameProjectNotification = FSlateNotificationManager::Get().AddNotification(Info);
if (UpdateGameProjectNotification.IsValid())
{
UpdateGameProjectNotification.Pin()->SetCompletionState(SNotificationItem::CS_Pending);
}
}
}
// Check if there are any installed plugins which aren't referenced by the project file
if(!UpdateGameProjectNotification.IsValid())
{
const FProjectDescriptor* Project = IProjectManager::Get().GetCurrentProject();
if(Project != nullptr)
{
TArray<FPluginReferenceDescriptor> NewPluginReferences;
for(TSharedRef<IPlugin>& Plugin: IPluginManager::Get().GetEnabledPlugins())
{
if(Plugin->GetDescriptor().bInstalled && Project->FindPluginReferenceIndex(Plugin->GetName()) == INDEX_NONE)
{
FPluginReferenceDescriptor PluginReference(Plugin->GetName(), true, Plugin->GetDescriptor().MarketplaceURL);
NewPluginReferences.Add(PluginReference);
}
}
if(NewPluginReferences.Num() > 0)
{
UpdateProject(FProjectDescriptorModifier::CreateLambda(
[NewPluginReferences](FProjectDescriptor& Descriptor){ Descriptor.Plugins.Append(NewPluginReferences); return true; }
));
}
}
}
}
}
void GameProjectUtils::CheckAndWarnProjectFilenameValid()
{
const FString& LoadedProjectFilePath = FPaths::IsProjectFilePathSet() ? FPaths::GetProjectFilePath() : FString();
if ( !LoadedProjectFilePath.IsEmpty() )
{
const FString BaseProjectFile = FPaths::GetBaseFilename(LoadedProjectFilePath);
if ( BaseProjectFile.Len() > MAX_PROJECT_NAME_LENGTH )
{
FFormatNamedArguments Args;
Args.Add( TEXT("MaxProjectNameLength"), MAX_PROJECT_NAME_LENGTH );
const FText WarningReason = FText::Format( LOCTEXT( "WarnProjectNameTooLong", "Project names must not be longer than {MaxProjectNameLength} characters.\nYou might have problems saving or modifying a project with a longer name." ), Args );
const FText WarningReasonOkText = LOCTEXT("WarningReasonOkText", "Ok");
FNotificationInfo Info(WarningReason);
Info.bFireAndForget = false;
Info.bUseLargeFont = false;
Info.bUseThrobber = false;
Info.bUseSuccessFailIcons = false;
Info.FadeOutDuration = 3.f;
Info.ButtonDetails.Add(FNotificationButtonInfo(WarningReasonOkText, FText(), FSimpleDelegate::CreateStatic(&GameProjectUtils::OnWarningReasonOk)));
if (WarningProjectNameNotification.IsValid())
{
WarningProjectNameNotification.Pin()->ExpireAndFadeout();
WarningProjectNameNotification.Reset();
}
WarningProjectNameNotification = FSlateNotificationManager::Get().AddNotification(Info);
if (WarningProjectNameNotification.IsValid())
{
WarningProjectNameNotification.Pin()->SetCompletionState(SNotificationItem::CS_Pending);
}
}
}
}
void GameProjectUtils::OnWarningReasonOk()
{
if ( WarningProjectNameNotification.IsValid() )
{
WarningProjectNameNotification.Pin()->SetCompletionState(SNotificationItem::CS_None);
WarningProjectNameNotification.Pin()->ExpireAndFadeout();
WarningProjectNameNotification.Reset();
}
}
bool GameProjectUtils::UpdateStartupModuleNames(FProjectDescriptor& Descriptor, const TArray<FString>* StartupModuleNames)
{
if (StartupModuleNames == nullptr)
{
return false;
}
// Replace the modules names, if specified
Descriptor.Modules.Empty();
for (int32 Idx = 0; Idx < StartupModuleNames->Num(); Idx++)
{
Descriptor.Modules.Add(FModuleDescriptor(*(*StartupModuleNames)[Idx]));
}
return true;
}
bool GameProjectUtils::UpdateRequiredAdditionalDependencies(FProjectDescriptor& Descriptor, TArray<FString>& RequiredDependencies, const FString& ModuleName)
{
bool bNeedsUpdate = false;
for (auto& ModuleDesc : Descriptor.Modules)
{
if (ModuleDesc.Name != *ModuleName)
{
continue;
}
for (const auto& RequiredDep : RequiredDependencies)
{
if (!ModuleDesc.AdditionalDependencies.Contains(RequiredDep))
{
ModuleDesc.AdditionalDependencies.Add(RequiredDep);
bNeedsUpdate = true;
}
}
}
return bNeedsUpdate;
}
bool GameProjectUtils::UpdateGameProject(const FString& ProjectFile, const FString& EngineIdentifier, FText& OutFailReason)
{
return UpdateGameProjectFile(ProjectFile, EngineIdentifier, OutFailReason);
}
void GameProjectUtils::OpenAddToProjectDialog(const FAddToProjectConfig& Config, EClassDomain InDomain)
{
// If we've been given a class then we only show the second page of the dialog, so we can make the window smaller as that page doesn't have as much content
const FVector2D WindowSize = (Config._ParentClass) ? (InDomain == EClassDomain::Blueprint) ? FVector2D(940, 480) : FVector2D(940, 380) : FVector2D(940, 540);
FText WindowTitle = Config._WindowTitle;
if (WindowTitle.IsEmpty())
{
WindowTitle = InDomain == EClassDomain::Native ? LOCTEXT("AddCodeWindowHeader_Native", "Add C++ Class") : LOCTEXT("AddCodeWindowHeader_Blueprint", "Add Blueprint Class");
}
TSharedRef<SWindow> AddCodeWindow =
SNew(SWindow)
.Title( WindowTitle )
.ClientSize( WindowSize )
.SizingRule( ESizingRule::FixedSize )
.SupportsMinimize(false) .SupportsMaximize(false);
TSharedRef<SNewClassDialog> NewClassDialog =
SNew(SNewClassDialog)
.Class(Config._ParentClass)
.ClassViewerFilter(Config._AllowableParents)
.ClassDomain(InDomain)
.FeaturedClasses(Config._FeaturedClasses)
.InitialPath(Config._InitialPath)
.OnAddedToProject( Config._OnAddedToProject )
.DefaultClassPrefix( Config._DefaultClassPrefix )
.DefaultClassName( Config._DefaultClassName );
AddCodeWindow->SetContent( NewClassDialog );
TSharedPtr<SWindow> ParentWindow = Config._ParentWindow;
if (!ParentWindow.IsValid())
{
static const FName MainFrameModuleName = "MainFrame";
IMainFrameModule& MainFrameModule = FModuleManager::LoadModuleChecked<IMainFrameModule>(MainFrameModuleName);
ParentWindow = MainFrameModule.GetParentWindow();
}
if (Config._bModal)
{
FSlateApplication::Get().AddModalWindow(AddCodeWindow, ParentWindow);
}
else if (ParentWindow.IsValid())
{
FSlateApplication::Get().AddWindowAsNativeChild(AddCodeWindow, ParentWindow.ToSharedRef());
}
else
{
FSlateApplication::Get().AddWindow(AddCodeWindow);
}
}
bool GameProjectUtils::IsValidClassNameForCreation(const FString& NewClassName, FText& OutFailReason)
{
if ( NewClassName.IsEmpty() )
{
OutFailReason = LOCTEXT( "NoClassName", "You must specify a class name." );
return false;
}
if ( NewClassName.Contains(TEXT(" ")) )
{
OutFailReason = LOCTEXT( "ClassNameContainsSpace", "Your class name may not contain a space." );
return false;
}
if ( !FChar::IsAlpha(NewClassName[0]) )
{
OutFailReason = LOCTEXT( "ClassNameMustBeginWithACharacter", "Your class name must begin with an alphabetic character." );
return false;
}
if ( NewClassName.Len() > MAX_CLASS_NAME_LENGTH )
{
OutFailReason = FText::Format( LOCTEXT( "ClassNameTooLong", "The class name must not be longer than {0} characters." ), FText::AsNumber(MAX_CLASS_NAME_LENGTH) );
return false;
}
FString IllegalNameCharacters;
if ( !NameContainsOnlyLegalCharacters(NewClassName, IllegalNameCharacters) )
{
FFormatNamedArguments Args;
Args.Add( TEXT("IllegalNameCharacters"), FText::FromString( IllegalNameCharacters ) );
OutFailReason = FText::Format( LOCTEXT( "ClassNameContainsIllegalCharacters", "The class name may not contain the following characters: {IllegalNameCharacters}" ), Args );
return false;
}
return true;
}
bool GameProjectUtils::IsValidClassNameForCreation(const FString& NewClassName, const FModuleContextInfo& ModuleInfo, const TSet<FString>& DisallowedHeaderNames, FText& OutFailReason)
{
if (!IsValidClassNameForCreation(NewClassName, OutFailReason))
{
return false;
}
// Look for a duplicate class in memory
for ( TObjectIterator<UClass> ClassIt; ClassIt; ++ClassIt )
{
if ( ClassIt->GetName() == NewClassName )
{
FFormatNamedArguments Args;
Args.Add( TEXT("NewClassName"), FText::FromString( NewClassName ) );
OutFailReason = FText::Format( LOCTEXT("ClassNameAlreadyExists", "The name {NewClassName} is already used by another class."), Args );
return false;
}
}
// Look for a duplicate class on disk in their project
{
FString UnusedFoundPath;
if ( FindSourceFileInProject(NewClassName + ".h", ModuleInfo.ModuleSourcePath, UnusedFoundPath) )
{
FFormatNamedArguments Args;
Args.Add( TEXT("NewClassName"), FText::FromString( NewClassName ) );
OutFailReason = FText::Format( LOCTEXT("ClassNameAlreadyExists", "The name {NewClassName} is already used by another class."), Args );
return false;
}
}
// See if header name clashes with an engine header
{
FString UnusedFoundPath;
if (DisallowedHeaderNames.Contains(NewClassName))
{
FFormatNamedArguments Args;
Args.Add(TEXT("NewHeaderName"), FText::FromString(NewClassName + ".h"));
OutFailReason = FText::Format(LOCTEXT("HeaderNameAlreadyExists", "The file {NewHeaderName} already exists elsewhere in the engine."), Args);
return false;
}
}
return true;
}
bool GameProjectUtils::IsValidBaseClassForCreation(const UClass* InClass, const FModuleContextInfo& InModuleInfo)
{
auto DoesClassNeedAPIExport = [&InModuleInfo](const FString& InClassModuleName) -> bool
{
return InModuleInfo.ModuleName != InClassModuleName;
};
return IsValidBaseClassForCreation_Internal(InClass, FDoesClassNeedAPIExportCallback::CreateLambda(DoesClassNeedAPIExport));
}
bool GameProjectUtils::IsValidBaseClassForCreation(const UClass* InClass, const TArray<FModuleContextInfo>& InModuleInfoArray)
{
auto DoesClassNeedAPIExport = [&InModuleInfoArray](const FString& InClassModuleName) -> bool
{
for(const FModuleContextInfo& ModuleInfo : InModuleInfoArray)
{
if(ModuleInfo.ModuleName == InClassModuleName)
{
return false;
}
}
return true;
};
return IsValidBaseClassForCreation_Internal(InClass, FDoesClassNeedAPIExportCallback::CreateLambda(DoesClassNeedAPIExport));
}
bool GameProjectUtils::IsValidBaseClassForCreation_Internal(const UClass* InClass, const FDoesClassNeedAPIExportCallback& InDoesClassNeedAPIExport)
{
// You may not make native classes based on blueprint generated classes
const bool bIsBlueprintClass = (InClass->ClassGeneratedBy != nullptr);
// UObject is special cased to be extensible since it would otherwise not be since it doesn't pass the API check (intrinsic class).
const bool bIsExplicitlyUObject = (InClass == UObject::StaticClass());
// You need API if you are not UObject itself, and you're in a module that was validated as needing API export
const FString ClassModuleName = InClass->GetOutermost()->GetName().RightChop( FString(TEXT("/Script/")).Len() );
const bool bNeedsAPI = !bIsExplicitlyUObject && InDoesClassNeedAPIExport.Execute(ClassModuleName);
// You may not make a class that is not DLL exported.
// MinimalAPI classes aren't compatible with the DLL export macro, but can still be used as a valid base
const bool bHasAPI = InClass->HasAnyClassFlags(CLASS_RequiredAPI) || InClass->HasAnyClassFlags(CLASS_MinimalAPI);
// @todo should we support interfaces?
const bool bIsInterface = InClass->IsChildOf(UInterface::StaticClass());
return !bIsBlueprintClass && (!bNeedsAPI || bHasAPI) && !bIsInterface;
}
GameProjectUtils::EAddCodeToProjectResult GameProjectUtils::AddCodeToProject(const FString& NewClassName, const FString& NewClassPath, const FModuleContextInfo& ModuleInfo, const FNewClassInfo ParentClassInfo, const TSet<FString>& DisallowedHeaderNames, FString& OutHeaderFilePath, FString& OutCppFilePath, FText& OutFailReason)
{
const EAddCodeToProjectResult Result = AddCodeToProject_Internal(NewClassName, NewClassPath, ModuleInfo, ParentClassInfo, DisallowedHeaderNames, OutHeaderFilePath, OutCppFilePath, OutFailReason);
if( FEngineAnalytics::IsAvailable() )
{
const FString ParentClassName = ParentClassInfo.GetClassNameCPP();
TArray<FAnalyticsEventAttribute> EventAttributes;
EventAttributes.Add(FAnalyticsEventAttribute(TEXT("ParentClass"), ParentClassName.IsEmpty() ? TEXT("None") : ParentClassName));
EventAttributes.Add(FAnalyticsEventAttribute(TEXT("Outcome"), Result == EAddCodeToProjectResult::Succeeded ? TEXT("Successful") : TEXT("Failed")));
EventAttributes.Add(FAnalyticsEventAttribute(TEXT("FailureReason"), OutFailReason.ToString()));
FEngineAnalytics::GetProvider().RecordEvent( TEXT( "Editor.AddCodeToProject.CodeAdded" ), EventAttributes );
}
return Result;
}
UTemplateProjectDefs* GameProjectUtils::LoadTemplateDefs(const FString& ProjectDirectory)
{
UTemplateProjectDefs* TemplateDefs = NULL;
const FString TemplateDefsIniFilename = ProjectDirectory / TEXT("Config") / GetTemplateDefsFilename();
if ( FPlatformFileManager::Get().GetPlatformFile().FileExists(*TemplateDefsIniFilename) )
{
UClass* ClassToConstruct = UDefaultTemplateProjectDefs::StaticClass();
// see if template uses a custom project defs object
FString ClassName;
const bool bFoundValue = GConfig->GetString(*UTemplateProjectDefs::StaticClass()->GetPathName(), TEXT("TemplateProjectDefsClass"), ClassName, TemplateDefsIniFilename);
if (bFoundValue && ClassName.Len() > 0)
{
UClass* OverrideClass = FindObject<UClass>(ANY_PACKAGE, *ClassName, false);
if (nullptr != OverrideClass)
{
ClassToConstruct = OverrideClass;
}
else
{
UE_LOG(LogGameProjectGeneration, Error, TEXT("Failed to find template project defs class '%s', using default."), *ClassName);
}
}
TemplateDefs = NewObject<UTemplateProjectDefs>(GetTransientPackage(), ClassToConstruct);
TemplateDefs->LoadConfig(UTemplateProjectDefs::StaticClass(), *TemplateDefsIniFilename);
}
return TemplateDefs;
}
bool GameProjectUtils::GenerateProjectFromScratch(const FProjectInformation& InProjectInfo, FText& OutFailReason, FText& OutFailLog)
{
FScopedSlowTask SlowTask(5);
const FString NewProjectFolder = FPaths::GetPath(InProjectInfo.ProjectFilename);
const FString NewProjectName = FPaths::GetBaseFilename(InProjectInfo.ProjectFilename);
TArray<FString> CreatedFiles;
SlowTask.EnterProgressFrame();
// Generate config files
if (!GenerateConfigFiles(InProjectInfo, CreatedFiles, OutFailReason))
{
return false;
}
// Insert any required feature packs (EG starter content) into ini file. These will be imported automatically when the editor is first run
if(!InsertFeaturePacksIntoINIFile(InProjectInfo, OutFailReason))
{
return false;
}
// Make the Content folder
const FString ContentFolder = NewProjectFolder / TEXT("Content");
if ( !IFileManager::Get().MakeDirectory(*ContentFolder) )
{
FFormatNamedArguments Args;
Args.Add( TEXT("ContentFolder"), FText::FromString( ContentFolder ) );
OutFailReason = FText::Format( LOCTEXT("FailedToCreateContentFolder", "Failed to create the content folder {ContentFolder}"), Args );
return false;
}
SlowTask.EnterProgressFrame();
TArray<FString> StartupModuleNames;
if ( InProjectInfo.bShouldGenerateCode )
{
FScopedSlowTask LocalScope(2);
LocalScope.EnterProgressFrame();
// Generate basic source code files
if ( !GenerateBasicSourceCode(NewProjectFolder / TEXT("Source"), NewProjectName, NewProjectFolder, StartupModuleNames, CreatedFiles, OutFailReason) )
{
return false;
}
LocalScope.EnterProgressFrame();
// Generate game framework source code files
if ( !GenerateGameFrameworkSourceCode(NewProjectFolder / TEXT("Source"), NewProjectName, CreatedFiles, OutFailReason) )
{
return false;
}
}
SlowTask.EnterProgressFrame();
// Generate the project file
{
// Set up the descriptor
FProjectDescriptor Descriptor;
for(int32 Idx = 0; Idx < StartupModuleNames.Num(); Idx++)
{
Descriptor.Modules.Add(FModuleDescriptor(*StartupModuleNames[Idx]));
}
// Try to save it
FText LocalFailReason;
if(!Descriptor.Save(InProjectInfo.ProjectFilename, LocalFailReason))
{
OutFailReason = LocalFailReason;
return false;
}
CreatedFiles.Add(InProjectInfo.ProjectFilename);
// Set the engine identifier for it. Do this after saving, so it can be correctly detected as foreign or non-foreign.
if(!SetEngineAssociationForForeignProject(InProjectInfo.ProjectFilename, OutFailReason))
{
return false;
}
}
SlowTask.EnterProgressFrame();
if ( InProjectInfo.bShouldGenerateCode )
{
// Generate project files
if ( !GenerateCodeProjectFiles(InProjectInfo.ProjectFilename, OutFailReason, OutFailLog) )
{
return false;
}
}
SlowTask.EnterProgressFrame();
UE_LOG(LogGameProjectGeneration, Log, TEXT("Created new project with %d files (plus project files)"), CreatedFiles.Num());
return true;
}
bool GameProjectUtils::CreateProjectFromTemplate(const FProjectInformation& InProjectInfo, FText& OutFailReason, FText& OutFailLog,TArray<FString>* OutCreatedFiles)
{
FScopedSlowTask SlowTask(10);
const FString ProjectName = FPaths::GetBaseFilename(InProjectInfo.ProjectFilename);
const FString TemplateName = FPaths::GetBaseFilename(InProjectInfo.TemplateFile);
const FString SrcFolder = FPaths::GetPath(InProjectInfo.TemplateFile);
const FString DestFolder = FPaths::GetPath(InProjectInfo.ProjectFilename);
if ( !FPlatformFileManager::Get().GetPlatformFile().FileExists(*InProjectInfo.TemplateFile) )
{
FFormatNamedArguments Args;
Args.Add( TEXT("TemplateFile"), FText::FromString( InProjectInfo.TemplateFile ) );
OutFailReason = FText::Format( LOCTEXT("InvalidTemplate_MissingProject", "Template project \"{TemplateFile}\" does not exist."), Args );
return false;
}
SlowTask.EnterProgressFrame();
UTemplateProjectDefs* TemplateDefs = LoadTemplateDefs(SrcFolder);
if ( TemplateDefs == NULL )
{
FFormatNamedArguments Args;
Args.Add( TEXT("TemplateFile"), FText::FromString( FPaths::GetBaseFilename(InProjectInfo.TemplateFile) ) );
Args.Add( TEXT("TemplateDefinesFile"), FText::FromString( GetTemplateDefsFilename() ) );
OutFailReason = FText::Format( LOCTEXT("InvalidTemplate_MissingDefs", "Template project \"{TemplateFile}\" does not have definitions file: '{TemplateDefinesFile}'."), Args );
return false;
}
SlowTask.EnterProgressFrame();
// Fix up the replacement strings using the specified project name
TemplateDefs->FixupStrings(TemplateName, ProjectName);
// Form a list of all extensions we care about
TSet<FString> ReplacementsInFilesExtensions;
for ( const FTemplateReplacement& Replacement : TemplateDefs->ReplacementsInFiles )
{
ReplacementsInFilesExtensions.Append(Replacement.Extensions);
}
// Keep a list of created files so we can delete them if project creation fails
TArray<FString> CreatedFiles;
SlowTask.EnterProgressFrame();
// Discover and copy all files in the src folder to the destination, excluding a few files and folders
TArray<FString> FilesToCopy;
TArray<FString> FilesThatNeedContentsReplaced;
TMap<FString, FString> ClassRenames;
IFileManager::Get().FindFilesRecursive(FilesToCopy, *SrcFolder, TEXT("*"), /*Files=*/true, /*Directories=*/false);
SlowTask.EnterProgressFrame();
{
// Open a new feedback scope for the loop so we can report how far through the copy we are
FScopedSlowTask InnerSlowTask(FilesToCopy.Num());
for ( const FString& SrcFilename : FilesToCopy )
{
// Update the progress
FFormatNamedArguments Args;
Args.Add( TEXT("SrcFilename"), FText::FromString( FPaths::GetCleanFilename(SrcFilename) ) );
InnerSlowTask.EnterProgressFrame(1, FText::Format( LOCTEXT( "CreatingProjectStatus_CopyingFile", "Copying File {SrcFilename}..." ), Args ));
// Get the file path, relative to the src folder
const FString SrcFileSubpath = SrcFilename.RightChop(SrcFolder.Len() + 1);
// Skip any files that were configured to be ignored
if ( TemplateDefs->FilesToIgnore.Contains(SrcFileSubpath) )
{
// This file was marked as "ignored"
continue;
}
// Skip any folders that were configured to be ignored
if ( const FString* IgnoredFolder = TemplateDefs->FoldersToIgnore.FindByPredicate([&SrcFileSubpath](const FString& Ignore){ return SrcFileSubpath.StartsWith(Ignore + TEXT("/")); }) )
{
// This folder was marked as "ignored"
UE_LOG(LogGameProjectGeneration, Verbose, TEXT("'%s': Skipping as it is in an ignored folder '%s'"), *SrcFilename, **IgnoredFolder);
continue;
}
// Retarget any folders that were chosen to be renamed by choosing a new destination subpath now
FString DestFileSubpathWithoutFilename = FPaths::GetPath(SrcFileSubpath) + TEXT("/");
for ( const FTemplateFolderRename& FolderRename : TemplateDefs->FolderRenames )
{
if ( SrcFileSubpath.StartsWith(FolderRename.From + TEXT("/")) )
{
// This was a file in a renamed folder. Retarget to the new location
DestFileSubpathWithoutFilename = FolderRename.To / DestFileSubpathWithoutFilename.RightChop( FolderRename.From.Len() );
UE_LOG(LogGameProjectGeneration, Verbose, TEXT("'%s': Moving to '%s' as it matched folder rename ('%s'->'%s')"), *SrcFilename, *DestFileSubpathWithoutFilename, *FolderRename.From, *FolderRename.To);
}
}
// Retarget any files that were chosen to have parts of their names replaced here
FString DestBaseFilename = FPaths::GetBaseFilename(SrcFileSubpath);
const FString FileExtension = FPaths::GetExtension(SrcFileSubpath);
for ( const FTemplateReplacement& Replacement : TemplateDefs->FilenameReplacements )
{
if ( Replacement.Extensions.Contains( FileExtension ) )
{
// This file matched a filename replacement extension, apply it now
FString LastDestBaseFilename = DestBaseFilename;
DestBaseFilename = DestBaseFilename.Replace(*Replacement.From, *Replacement.To, Replacement.bCaseSensitive ? ESearchCase::CaseSensitive : ESearchCase::IgnoreCase);
if (LastDestBaseFilename != DestBaseFilename)
{
UE_LOG(LogGameProjectGeneration, Verbose, TEXT("'%s': Renaming to '%s/%s' as it matched file rename ('%s'->'%s')"), *SrcFilename, *DestFileSubpathWithoutFilename, *DestBaseFilename, *Replacement.From, *Replacement.To);
}
}
}
// Perform the copy
const FString DestFilename = DestFolder / DestFileSubpathWithoutFilename + DestBaseFilename + TEXT(".") + FileExtension;
if ( IFileManager::Get().Copy(*DestFilename, *SrcFilename) == COPY_OK )
{
CreatedFiles.Add(DestFilename);
if ( ReplacementsInFilesExtensions.Contains(FileExtension) )
{
FilesThatNeedContentsReplaced.Add(DestFilename);
}
// Allow project template to extract class renames from this file copy
if (FPaths::GetBaseFilename(SrcFilename) != FPaths::GetBaseFilename(DestFilename)
&& TemplateDefs->IsClassRename(DestFilename, SrcFilename, FileExtension))
{
// Looks like a UObject file!
ClassRenames.Add(FPaths::GetBaseFilename(SrcFilename), FPaths::GetBaseFilename(DestFilename));
}
}
else
{
FFormatNamedArguments FailArgs;
FailArgs.Add(TEXT("SrcFilename"), FText::FromString(SrcFilename));
FailArgs.Add(TEXT("DestFilename"), FText::FromString(DestFilename));
OutFailReason = FText::Format(LOCTEXT("FailedToCopyFile", "Failed to copy \"{SrcFilename}\" to \"{DestFilename}\"."), FailArgs);
return false;
}
}
}
SlowTask.EnterProgressFrame();
{
// Open a new feedback scope for the loop so we can report how far through the process we are
FScopedSlowTask InnerSlowTask(FilesThatNeedContentsReplaced.Num());
// Open all files with the specified extensions and replace text
for ( const FString& FileToFix : FilesThatNeedContentsReplaced )
{
InnerSlowTask.EnterProgressFrame();
bool bSuccessfullyProcessed = false;
FString FileContents;
if ( FFileHelper::LoadFileToString(FileContents, *FileToFix) )
{
for ( const FTemplateReplacement& Replacement : TemplateDefs->ReplacementsInFiles )
{
if ( Replacement.Extensions.Contains( FPaths::GetExtension(FileToFix) ) )
{
FileContents = FileContents.Replace(*Replacement.From, *Replacement.To, Replacement.bCaseSensitive ? ESearchCase::CaseSensitive : ESearchCase::IgnoreCase);
}
}
if ( FFileHelper::SaveStringToFile(FileContents, *FileToFix) )
{
bSuccessfullyProcessed = true;
}
}
if ( !bSuccessfullyProcessed )
{
FFormatNamedArguments Args;
Args.Add( TEXT("FileToFix"), FText::FromString( FileToFix ) );
OutFailReason = FText::Format( LOCTEXT("FailedToFixUpFile", "Failed to process file \"{FileToFix}\"."), Args );
return false;
}
}
}
SlowTask.EnterProgressFrame();
const FString ProjectConfigPath = DestFolder / TEXT("Config");
// Write out the hardware class target settings chosen for this project
{
const FString DefaultEngineIniFilename = ProjectConfigPath / TEXT("DefaultEngine.ini");
FString FileContents;
// Load the existing file - if it doesn't exist we create it
FFileHelper::LoadFileToString(FileContents, *DefaultEngineIniFilename);
FileContents += LINE_TERMINATOR;
FileContents += GetHardwareConfigString(InProjectInfo);
if ( !WriteOutputFile(DefaultEngineIniFilename, FileContents, OutFailReason) )
{
return false;
}
}
// Fixup specific ini values
TArray<FTemplateConfigValue> ConfigValuesToSet;
TemplateDefs->AddConfigValues(ConfigValuesToSet, TemplateName, ProjectName, InProjectInfo.bShouldGenerateCode);
ConfigValuesToSet.Emplace(TEXT("DefaultGame.ini"), TEXT("/Script/EngineSettings.GeneralProjectSettings"), TEXT("ProjectID"), FGuid::NewGuid().ToString(), /*InShouldReplaceExistingValue=*/true);
// Add all classname fixups
for ( const TPair<FString, FString>& Rename : ClassRenames )
{
const FString ClassRedirectString = FString::Printf(TEXT("(OldClassName=\"%s\",NewClassName=\"%s\")"), *Rename.Key, *Rename.Value);
ConfigValuesToSet.Emplace(TEXT("DefaultEngine.ini"), TEXT("/Script/Engine.Engine"), TEXT("+ActiveClassRedirects"), *ClassRedirectString, /*InShouldReplaceExistingValue=*/false);
}
// Fix all specified config values
for ( const FTemplateConfigValue& ConfigValue : ConfigValuesToSet )
{
const FString IniFilename = ProjectConfigPath / ConfigValue.ConfigFile;
bool bSuccessfullyProcessed = false;
TArray<FString> FileLines;
if ( FFileHelper::LoadANSITextFileToStrings(*IniFilename, &IFileManager::Get(), FileLines) )
{
FString FileOutput;
const FString TargetSection = ConfigValue.ConfigSection;
FString CurSection;
bool bFoundTargetKey = false;
for ( const FString& LineIn : FileLines )
{
FString Line = LineIn;
Line.Trim().TrimTrailing();
bool bShouldExcludeLineFromOutput = false;
// If we not yet found the target key parse each line looking for it
if ( !bFoundTargetKey )
{
// Check for an empty line. No work needs to be done on these lines
if ( Line.Len() == 0 )
{
}
// Comment lines start with ";". Skip these lines entirely.
else if ( Line.StartsWith(TEXT(";")) )
{
}
// If this is a section line, update the section
else if ( Line.StartsWith(TEXT("[")) )
{
// If we are entering a new section and we have not yet found our key in the target section, add it to the end of the section
if ( CurSection == TargetSection )
{
FileOutput += ConfigValue.ConfigKey + TEXT("=") + ConfigValue.ConfigValue + LINE_TERMINATOR + LINE_TERMINATOR;
bFoundTargetKey = true;
}
// Update the current section
CurSection = Line.Mid(1, Line.Len() - 2);
}
// This is possibly an actual key/value pair
else if ( CurSection == TargetSection )
{
// Key value pairs contain an equals sign
const int32 EqualsIdx = Line.Find(TEXT("="));
if ( EqualsIdx != INDEX_NONE )
{
// Determine the key and see if it is the target key
const FString Key = Line.Left(EqualsIdx);
if ( Key == ConfigValue.ConfigKey )
{
// Found the target key, add it to the output and skip the current line if the target value is supposed to replace
FileOutput += ConfigValue.ConfigKey + TEXT("=") + ConfigValue.ConfigValue + LINE_TERMINATOR;
bShouldExcludeLineFromOutput = ConfigValue.bShouldReplaceExistingValue;
bFoundTargetKey = true;
}
}
}
}
// Unless we replaced the key, add this line to the output
if ( !bShouldExcludeLineFromOutput )
{
FileOutput += Line;
if ( &LineIn != &FileLines.Last() )
{
// Add a line terminator on every line except the last
FileOutput += LINE_TERMINATOR;
}
}
}
// If the key did not exist, add it here
if ( !bFoundTargetKey )
{
// If we did not end in the correct section, add the section to the bottom of the file
if ( CurSection != TargetSection )
{
FileOutput += LINE_TERMINATOR;
FileOutput += LINE_TERMINATOR;
FileOutput += FString::Printf(TEXT("[%s]"), *TargetSection) + LINE_TERMINATOR;
}
// Add the key/value here
FileOutput += ConfigValue.ConfigKey + TEXT("=") + ConfigValue.ConfigValue + LINE_TERMINATOR;
}
if ( FFileHelper::SaveStringToFile(FileOutput, *IniFilename) )
{
bSuccessfullyProcessed = true;
}
}
if ( !bSuccessfullyProcessed )
{
OutFailReason = LOCTEXT("FailedToFixUpDefaultEngine", "Failed to process file DefaultEngine.ini");
return false;
}
}
// Insert any required feature packs (EG starter content) into ini file. These will be imported automatically when the editor is first run
if(!InsertFeaturePacksIntoINIFile(InProjectInfo, OutFailReason))
{
return false;
}
if( !AddSharedContentToProject(InProjectInfo, CreatedFiles, OutFailReason ) )
{
return false;
}
SlowTask.EnterProgressFrame();
// Generate the project file
{
// Load the source project
FProjectDescriptor Project;
if(!Project.Load(InProjectInfo.TemplateFile, OutFailReason))
{
return false;
}
// Update it to current
Project.EngineAssociation.Empty();
Project.EpicSampleNameHash = 0;
// Fix up module names
const FString BaseSourceName = FPaths::GetBaseFilename(InProjectInfo.TemplateFile);
const FString BaseNewName = FPaths::GetBaseFilename(InProjectInfo.ProjectFilename);
for ( FModuleDescriptor& ModuleInfo : Project.Modules )
{
ModuleInfo.Name = FName(*ModuleInfo.Name.ToString().Replace(*BaseSourceName, *BaseNewName));
}
// Save it to disk
if(!Project.Save(InProjectInfo.ProjectFilename, OutFailReason))
{
return false;
}
// Set the engine identifier if it's a foreign project. Do this after saving, so it can be correctly detected as foreign.
if(!SetEngineAssociationForForeignProject(InProjectInfo.ProjectFilename, OutFailReason))
{
return false;
}
// Add it to the list of created files
CreatedFiles.Add(InProjectInfo.ProjectFilename);
}
SlowTask.EnterProgressFrame();
SlowTask.EnterProgressFrame();
if ( InProjectInfo.bShouldGenerateCode )
{
// Generate project files
if ( !GenerateCodeProjectFiles(InProjectInfo.ProjectFilename, OutFailReason, OutFailLog) )
{
return false;
}
}
SlowTask.EnterProgressFrame();
if (!TemplateDefs->PostGenerateProject(DestFolder, SrcFolder, InProjectInfo.ProjectFilename, InProjectInfo.TemplateFile, InProjectInfo.bShouldGenerateCode, OutFailReason))
{
return false;
}
if( OutCreatedFiles != nullptr )
{
OutCreatedFiles->Append(CreatedFiles);
}
return true;
}
bool GameProjectUtils::SetEngineAssociationForForeignProject(const FString& ProjectFileName, FText& OutFailReason)
{
if(FUProjectDictionary(FPaths::RootDir()).IsForeignProject(ProjectFileName))
{
if(!FDesktopPlatformModule::Get()->SetEngineIdentifierForProject(ProjectFileName, FDesktopPlatformModule::Get()->GetCurrentEngineIdentifier()))
{
OutFailReason = LOCTEXT("FailedToSetEngineIdentifier", "Couldn't set engine identifier for project");
return false;
}
}
return true;
}
FString GameProjectUtils::GetTemplateDefsFilename()
{
return TEXT("TemplateDefs.ini");
}
bool GameProjectUtils::NameContainsOnlyLegalCharacters(const FString& TestName, FString& OutIllegalCharacters)
{
bool bContainsIllegalCharacters = false;
// Only allow alphanumeric characters in the project name
bool bFoundAlphaNumericChar = false;
for ( int32 CharIdx = 0 ; CharIdx < TestName.Len() ; ++CharIdx )
{
const FString& Char = TestName.Mid( CharIdx, 1 );
if ( !FChar::IsAlnum(Char[0]) && Char != TEXT("_") )
{
if ( !OutIllegalCharacters.Contains( Char ) )
{
OutIllegalCharacters += Char;
}
bContainsIllegalCharacters = true;
}
}
return !bContainsIllegalCharacters;
}
bool GameProjectUtils::NameContainsUnderscoreAndXB1Installed(const FString& TestName)
{
// disabled for now so people with the SDK installed can use the editor
return false;
bool bContainsIllegalCharacters = false;
// Only allow alphanumeric characters in the project name
for ( int32 CharIdx = 0 ; CharIdx < TestName.Len() ; ++CharIdx )
{
const FString& Char = TestName.Mid( CharIdx, 1 );
if ( Char == TEXT("_") )
{
const ITargetPlatform* Platform = GetTargetPlatformManager()->FindTargetPlatform(TEXT("XboxOne"));
if (Platform)
{
FString NotInstalledDocLink;
if (Platform->IsSdkInstalled(true, NotInstalledDocLink))
{
bContainsIllegalCharacters = true;
}
}
}
}
return bContainsIllegalCharacters;
}
bool GameProjectUtils::ProjectFileExists(const FString& ProjectFile)
{
return FPlatformFileManager::Get().GetPlatformFile().FileExists(*ProjectFile);
}
bool GameProjectUtils::AnyProjectFilesExistInFolder(const FString& Path)
{
TArray<FString> ExistingFiles;
const FString Wildcard = FString::Printf(TEXT("%s/*.%s"), *Path, *FProjectDescriptor::GetExtension());
IFileManager::Get().FindFiles(ExistingFiles, *Wildcard, /*Files=*/true, /*Directories=*/false);
return ExistingFiles.Num() > 0;
}
bool GameProjectUtils::CleanupIsEnabled()
{
// Clean up files when running Rocket (unless otherwise specified on the command line)
return FParse::Param(FCommandLine::Get(), TEXT("norocketcleanup")) == false;
}
void GameProjectUtils::DeleteCreatedFiles(const FString& RootFolder, const TArray<FString>& CreatedFiles)
{
if (CleanupIsEnabled())
{
for ( auto FileToDeleteIt = CreatedFiles.CreateConstIterator(); FileToDeleteIt; ++FileToDeleteIt )
{
IFileManager::Get().Delete(**FileToDeleteIt);
}
// If the project folder is empty after deleting all the files we created, delete the directory as well
TArray<FString> RemainingFiles;
IFileManager::Get().FindFilesRecursive(RemainingFiles, *RootFolder, TEXT("*.*"), /*Files=*/true, /*Directories=*/false);
if ( RemainingFiles.Num() == 0 )
{
IFileManager::Get().DeleteDirectory(*RootFolder, /*RequireExists=*/false, /*Tree=*/true);
}
}
}
FString GameProjectUtils::GetHardwareConfigString(const FProjectInformation& InProjectInfo)
{
FString HardwareTargeting;
FString TargetHardwareAsString;
UEnum::GetValueAsString(TEXT("/Script/HardwareTargeting.EHardwareClass"), InProjectInfo.TargetedHardware, /*out*/ TargetHardwareAsString);
FString GraphicsPresetAsString;
UEnum::GetValueAsString(TEXT("/Script/HardwareTargeting.EGraphicsPreset"), InProjectInfo.DefaultGraphicsPerformance, /*out*/ GraphicsPresetAsString);
HardwareTargeting += TEXT("[/Script/HardwareTargeting.HardwareTargetingSettings]") LINE_TERMINATOR;
HardwareTargeting += FString::Printf(TEXT("TargetedHardwareClass=%s") LINE_TERMINATOR, *TargetHardwareAsString);
HardwareTargeting += FString::Printf(TEXT("DefaultGraphicsPerformance=%s") LINE_TERMINATOR, *GraphicsPresetAsString);
HardwareTargeting += LINE_TERMINATOR;
return HardwareTargeting;
}
bool GameProjectUtils::GenerateConfigFiles(const FProjectInformation& InProjectInfo, TArray<FString>& OutCreatedFiles, FText& OutFailReason)
{
const FString NewProjectFolder = FPaths::GetPath(InProjectInfo.ProjectFilename);
const FString NewProjectName = FPaths::GetBaseFilename(InProjectInfo.ProjectFilename);
FString ProjectConfigPath = NewProjectFolder / TEXT("Config");
// DefaultEngine.ini
{
const FString DefaultEngineIniFilename = ProjectConfigPath / TEXT("DefaultEngine.ini");
FString FileContents;
FileContents += TEXT("[URL]") LINE_TERMINATOR;
FileContents += GetHardwareConfigString(InProjectInfo);
FileContents += LINE_TERMINATOR;
if (InProjectInfo.bCopyStarterContent)
{
FString SpecificEditorStartupMap;
FString SpecificGameDefaultMap;
// If we have starter content packs available, specify starter map
if( IsStarterContentAvailableForNewProjects() == true )
{
if (InProjectInfo.TargetedHardware == EHardwareClass::Mobile)
{
SpecificEditorStartupMap = TEXT("/Game/MobileStarterContent/Maps/Minimal_Default");
SpecificGameDefaultMap = TEXT("/Game/MobileStarterContent/Maps/Minimal_Default");
}
else
{
SpecificEditorStartupMap = TEXT("/Game/StarterContent/Maps/Minimal_Default");
SpecificGameDefaultMap = TEXT("/Game/StarterContent/Maps/Minimal_Default");
}
}
// Write out the settings for startup map and game default map
FileContents += TEXT("[/Script/EngineSettings.GameMapsSettings]") LINE_TERMINATOR;
FileContents += FString::Printf(TEXT("EditorStartupMap=%s") LINE_TERMINATOR, *SpecificEditorStartupMap);
FileContents += FString::Printf(TEXT("GameDefaultMap=%s") LINE_TERMINATOR, *SpecificGameDefaultMap);
if (InProjectInfo.bShouldGenerateCode)
{
FileContents += FString::Printf(TEXT("GlobalDefaultGameMode=\"/Script/%s.%sGameMode\"") LINE_TERMINATOR, *NewProjectName, *NewProjectName);
}
}
if (WriteOutputFile(DefaultEngineIniFilename, FileContents, OutFailReason))
{
OutCreatedFiles.Add(DefaultEngineIniFilename);
}
else
{
return false;
}
}
// DefaultEditor.ini
{
const FString DefaultEditorIniFilename = ProjectConfigPath / TEXT("DefaultEditor.ini");
FString FileContents;
if (WriteOutputFile(DefaultEditorIniFilename, FileContents, OutFailReason))
{
OutCreatedFiles.Add(DefaultEditorIniFilename);
}
else
{
return false;
}
}
// DefaultGame.ini
{
const FString DefaultGameIniFilename = ProjectConfigPath / TEXT("DefaultGame.ini");
FString FileContents;
FileContents += TEXT("[/Script/EngineSettings.GeneralProjectSettings]") LINE_TERMINATOR;
FileContents += TEXT("ProjectID=") + FGuid::NewGuid().ToString() + LINE_TERMINATOR;
if (WriteOutputFile(DefaultGameIniFilename, FileContents, OutFailReason))
{
OutCreatedFiles.Add(DefaultGameIniFilename);
}
else
{
return false;
}
}
return true;
}
bool GameProjectUtils::GenerateBasicSourceCode(TArray<FString>& OutCreatedFiles, FText& OutFailReason)
{
TArray<FString> StartupModuleNames;
if (GameProjectUtils::GenerateBasicSourceCode(FPaths::GameSourceDir().LeftChop(1), FApp::GetGameName(), FPaths::GameDir(), StartupModuleNames, OutCreatedFiles, OutFailReason))
{
GameProjectUtils::UpdateProject(
FProjectDescriptorModifier::CreateLambda(
[&StartupModuleNames](FProjectDescriptor& Descriptor)
{
return UpdateStartupModuleNames(Descriptor, &StartupModuleNames);
}));
return true;
}
return false;
}
bool GameProjectUtils::GenerateBasicSourceCode(const FString& NewProjectSourcePath, const FString& NewProjectName, const FString& NewProjectRoot, TArray<FString>& OutGeneratedStartupModuleNames, TArray<FString>& OutCreatedFiles, FText& OutFailReason)
{
const FString GameModulePath = NewProjectSourcePath / NewProjectName;
const FString EditorName = NewProjectName + TEXT("Editor");
// MyGame.Build.cs
{
const FString NewBuildFilename = GameModulePath / NewProjectName + TEXT(".Build.cs");
TArray<FString> PublicDependencyModuleNames;
PublicDependencyModuleNames.Add(TEXT("Core"));
PublicDependencyModuleNames.Add(TEXT("CoreUObject"));
PublicDependencyModuleNames.Add(TEXT("Engine"));
PublicDependencyModuleNames.Add(TEXT("InputCore"));
TArray<FString> PrivateDependencyModuleNames;
if ( GenerateGameModuleBuildFile(NewBuildFilename, NewProjectName, PublicDependencyModuleNames, PrivateDependencyModuleNames, OutFailReason) )
{
OutGeneratedStartupModuleNames.Add(NewProjectName);
OutCreatedFiles.Add(NewBuildFilename);
}
else
{
return false;
}
}
// MyGame.Target.cs
{
const FString NewTargetFilename = NewProjectSourcePath / NewProjectName + TEXT(".Target.cs");
TArray<FString> ExtraModuleNames;
ExtraModuleNames.Add( NewProjectName );
if ( GenerateGameModuleTargetFile(NewTargetFilename, NewProjectName, ExtraModuleNames, OutFailReason) )
{
OutCreatedFiles.Add(NewTargetFilename);
}
else
{
return false;
}
}
// MyGameEditor.Target.cs
{
const FString NewTargetFilename = NewProjectSourcePath / EditorName + TEXT(".Target.cs");
// Include the MyGame module...
TArray<FString> ExtraModuleNames;
ExtraModuleNames.Add(NewProjectName);
if ( GenerateEditorModuleTargetFile(NewTargetFilename, EditorName, ExtraModuleNames, OutFailReason) )
{
OutCreatedFiles.Add(NewTargetFilename);
}
else
{
return false;
}
}
// MyGame.h
{
const FString NewHeaderFilename = GameModulePath / NewProjectName + TEXT(".h");
TArray<FString> PublicHeaderIncludes;
if ( GenerateGameModuleHeaderFile(NewHeaderFilename, PublicHeaderIncludes, OutFailReason) )
{
OutCreatedFiles.Add(NewHeaderFilename);
}
else
{
return false;
}
}
// MyGame.cpp
{
const FString NewCPPFilename = GameModulePath / NewProjectName + TEXT(".cpp");
if ( GenerateGameModuleCPPFile(NewCPPFilename, NewProjectName, NewProjectName, OutFailReason) )
{
OutCreatedFiles.Add(NewCPPFilename);
}
else
{
return false;
}
}
return true;
}
bool GameProjectUtils::GenerateGameFrameworkSourceCode(const FString& NewProjectSourcePath, const FString& NewProjectName, TArray<FString>& OutCreatedFiles, FText& OutFailReason)
{
const FString GameModulePath = NewProjectSourcePath / NewProjectName;
// Used to override the code generation validation since the module we're creating isn't the same as the project we currently have loaded
FModuleContextInfo NewModuleInfo;
NewModuleInfo.ModuleName = NewProjectName;
NewModuleInfo.ModuleType = EHostType::Runtime;
NewModuleInfo.ModuleSourcePath = FPaths::ConvertRelativePathToFull(GameModulePath / ""); // Ensure trailing /
// MyGameGameMode.h
{
const UClass* BaseClass = AGameModeBase::StaticClass();
const FString NewClassName = NewProjectName + BaseClass->GetName();
const FString NewHeaderFilename = GameModulePath / NewClassName + TEXT(".h");
FString UnusedSyncLocation;
if ( GenerateClassHeaderFile(NewHeaderFilename, NewClassName, FNewClassInfo(BaseClass), TArray<FString>(), TEXT(""), TEXT(""), UnusedSyncLocation, NewModuleInfo, false, OutFailReason) )
{
OutCreatedFiles.Add(NewHeaderFilename);
}
else
{
return false;
}
}
// MyGameGameMode.cpp
{
const UClass* BaseClass = AGameModeBase::StaticClass();
const FString NewClassName = NewProjectName + BaseClass->GetName();
const FString NewCPPFilename = GameModulePath / NewClassName + TEXT(".cpp");
TArray<FString> PropertyOverrides;
TArray<FString> AdditionalIncludes;
FString UnusedSyncLocation;
if ( GenerateClassCPPFile(NewCPPFilename, NewClassName, FNewClassInfo(BaseClass), AdditionalIncludes, PropertyOverrides, TEXT(""), UnusedSyncLocation, NewModuleInfo, OutFailReason) )
{
OutCreatedFiles.Add(NewCPPFilename);
}
else
{
return false;
}
}
return true;
}
bool GameProjectUtils::BuildCodeProject(const FString& ProjectFilename)
{
// Build the project while capturing the log output. Passing GWarn to CompileGameProject will allow Slate to display the progress bar.
FStringOutputDevice OutputLog;
OutputLog.SetAutoEmitLineTerminator(true);
GLog->AddOutputDevice(&OutputLog);
bool bCompileSucceeded = FDesktopPlatformModule::Get()->CompileGameProject(FPaths::RootDir(), ProjectFilename, GWarn);
GLog->RemoveOutputDevice(&OutputLog);
// Try to compile the modules
if(!bCompileSucceeded)
{
FText DevEnvName = FSourceCodeNavigation::GetSuggestedSourceCodeIDE( true );
TArray<FText> CompileFailedButtons;
int32 OpenIDEButton = CompileFailedButtons.Add(FText::Format(LOCTEXT("CompileFailedOpenIDE", "Open with {0}"), DevEnvName));
CompileFailedButtons.Add(LOCTEXT("CompileFailedCancel", "Cancel"));
FText LogText = FText::FromString(OutputLog.Replace(LINE_TERMINATOR, TEXT("\n")).TrimTrailing());
int32 CompileFailedChoice = SOutputLogDialog::Open(LOCTEXT("CompileFailedTitle", "Compile Failed"), FText::Format(LOCTEXT("CompileFailedHeader", "The project could not be compiled. Would you like to open it in {0}?"), DevEnvName), LogText, FText::GetEmpty(), CompileFailedButtons);
FText FailReason;
if(CompileFailedChoice == OpenIDEButton && !GameProjectUtils::OpenCodeIDE(ProjectFilename, FailReason))
{
FMessageDialog::Open(EAppMsgType::Ok, FailReason);
}
}
return bCompileSucceeded;
}
bool GameProjectUtils::GenerateCodeProjectFiles(const FString& ProjectFilename, FText& OutFailReason, FText& OutFailLog)
{
FStringOutputDevice OutputLog;
OutputLog.SetAutoEmitLineTerminator(true);
GLog->AddOutputDevice(&OutputLog);
bool bHaveProjectFiles = FDesktopPlatformModule::Get()->GenerateProjectFiles(FPaths::RootDir(), ProjectFilename, GWarn);
GLog->RemoveOutputDevice(&OutputLog);
if ( !bHaveProjectFiles )
{
OutFailReason = LOCTEXT("ErrorWhileGeneratingProjectFiles", "An error occurred while trying to generate project files.");
OutFailLog = FText::FromString(OutputLog);
return false;
}
return true;
}
bool GameProjectUtils::IsStarterContentAvailableForNewProjects()
{
TArray<FString> StarterContentFiles;
GetStarterContentFiles(StarterContentFiles);
bool bHasStaterContent = StarterContentFiles.FindByPredicate([&](const FString& Str){ return Str.Contains("StarterContent"); }) != nullptr;
return bHasStaterContent;
}
TArray<FModuleContextInfo> GameProjectUtils::GetCurrentProjectModules()
{
const FProjectDescriptor* const CurrentProject = IProjectManager::Get().GetCurrentProject();
check(CurrentProject);
TArray<FModuleContextInfo> RetModuleInfos;
if (!GameProjectUtils::ProjectHasCodeFiles() || CurrentProject->Modules.Num() == 0)
{
// If this project doesn't currently have any code in it, we need to add a dummy entry for the game
// so that we can still use the class wizard (this module will be created once we add a class)
FModuleContextInfo ModuleInfo;
ModuleInfo.ModuleName = FApp::GetGameName();
ModuleInfo.ModuleType = EHostType::Runtime;
ModuleInfo.ModuleSourcePath = FPaths::ConvertRelativePathToFull(FPaths::GameSourceDir() / ModuleInfo.ModuleName / ""); // Ensure trailing /
RetModuleInfos.Emplace(ModuleInfo);
}
// Resolve out the paths for each module and add the cut-down into to our output array
for (const FModuleDescriptor& ModuleDesc : CurrentProject->Modules)
{
FModuleContextInfo ModuleInfo;
ModuleInfo.ModuleName = ModuleDesc.Name.ToString();
ModuleInfo.ModuleType = ModuleDesc.Type;
// Try and find the .Build.cs file for this module within our currently loaded project's Source directory
FString TmpPath;
if (!FindSourceFileInProject(ModuleInfo.ModuleName + ".Build.cs", FPaths::GameSourceDir(), TmpPath))
{
continue;
}
// Chop the .Build.cs file off the end of the path
ModuleInfo.ModuleSourcePath = FPaths::GetPath(TmpPath);
ModuleInfo.ModuleSourcePath = FPaths::ConvertRelativePathToFull(ModuleInfo.ModuleSourcePath / ""); // Ensure trailing /
RetModuleInfos.Emplace(ModuleInfo);
}
return RetModuleInfos;
}
TArray<FModuleContextInfo> GameProjectUtils::GetCurrentProjectPluginModules()
{
const FProjectDescriptor* const CurrentProject = IProjectManager::Get().GetCurrentProject();
check(CurrentProject);
TArray<FModuleContextInfo> RetModuleInfos;
if (!GameProjectUtils::ProjectHasCodeFiles() || CurrentProject->Modules.Num() == 0)
{
// Don't get plugins if the game project has no source tree.
return RetModuleInfos;
}
// Resolve out the paths for each module and add the cut-down into to our output array
for (const auto& Plugin : IPluginManager::Get().GetDiscoveredPlugins())
{
// Only get plugins that are a part of the game project
if (Plugin->GetLoadedFrom() == EPluginLoadedFrom::GameProject)
{
for (const auto& PluginModule : Plugin->GetDescriptor().Modules)
{
FModuleContextInfo ModuleInfo;
ModuleInfo.ModuleName = PluginModule.Name.ToString();
ModuleInfo.ModuleType = PluginModule.Type;
// Try and find the .Build.cs file for this module within the plugin source tree
FString TmpPath;
if (!FindSourceFileInProject(ModuleInfo.ModuleName + ".Build.cs", Plugin->GetBaseDir(), TmpPath))
{
continue;
}
// Chop the .Build.cs file off the end of the path
ModuleInfo.ModuleSourcePath = FPaths::GetPath(TmpPath);
ModuleInfo.ModuleSourcePath = FPaths::ConvertRelativePathToFull(ModuleInfo.ModuleSourcePath / ""); // Ensure trailing /
RetModuleInfos.Emplace(ModuleInfo);
}
}
}
return RetModuleInfos;
}
bool GameProjectUtils::IsValidSourcePath(const FString& InPath, const FModuleContextInfo& ModuleInfo, FText* const OutFailReason)
{
const FString AbsoluteInPath = FPaths::ConvertRelativePathToFull(InPath) / ""; // Ensure trailing /
// Validate the path contains no invalid characters
if(!FPaths::ValidatePath(AbsoluteInPath, OutFailReason))
{
return false;
}
if(!AbsoluteInPath.StartsWith(ModuleInfo.ModuleSourcePath))
{
if(OutFailReason)
{
FFormatNamedArguments Args;
Args.Add(TEXT("ModuleName"), FText::FromString(ModuleInfo.ModuleName));
Args.Add(TEXT("RootSourcePath"), FText::FromString(ModuleInfo.ModuleSourcePath));
*OutFailReason = FText::Format( LOCTEXT("SourcePathInvalidForModule", "All source code for '{ModuleName}' must exist within '{RootSourcePath}'"), Args );
}
return false;
}
return true;
}
bool GameProjectUtils::CalculateSourcePaths(const FString& InPath, const FModuleContextInfo& ModuleInfo, FString& OutHeaderPath, FString& OutSourcePath, FText* const OutFailReason)
{
const FString AbsoluteInPath = FPaths::ConvertRelativePathToFull(InPath) / ""; // Ensure trailing /
OutHeaderPath = AbsoluteInPath;
OutSourcePath = AbsoluteInPath;
EClassLocation ClassPathLocation = EClassLocation::UserDefined;
if(!GetClassLocation(InPath, ModuleInfo, ClassPathLocation, OutFailReason))
{
return false;
}
const FString RootPath = ModuleInfo.ModuleSourcePath;
const FString PublicPath = RootPath / "Public" / ""; // Ensure trailing /
const FString PrivatePath = RootPath / "Private" / ""; // Ensure trailing /
const FString ClassesPath = RootPath / "Classes" / ""; // Ensure trailing /
// The root path must exist; we will allow the creation of sub-folders, but not the module root!
// We ignore this check if the project doesn't already have source code in it, as the module folder won't yet have been created
const bool bHasCodeFiles = GameProjectUtils::ProjectHasCodeFiles();
if(!IFileManager::Get().DirectoryExists(*RootPath) && bHasCodeFiles)
{
if(OutFailReason)
{
FFormatNamedArguments Args;
Args.Add(TEXT("ModuleSourcePath"), FText::FromString(RootPath));
*OutFailReason = FText::Format(LOCTEXT("SourcePathMissingModuleRoot", "The specified module path does not exist on disk: {ModuleSourcePath}"), Args);
}
return false;
}
// The rules for placing header files are as follows:
// 1) If InPath is the source root, and GetClassLocation has said the class header should be in the Public folder, put it in the Public folder
// 2) Otherwise, just place the header at InPath (the default set above)
if(AbsoluteInPath == RootPath)
{
OutHeaderPath = (ClassPathLocation == EClassLocation::Public) ? PublicPath : AbsoluteInPath;
}
// The rules for placing source files are as follows:
// 1) If InPath is the source root, and GetClassLocation has said the class header should be in the Public folder, put the source file in the Private folder
// 2) If InPath is contained within the Public or Classes folder of this module, place it in the equivalent path in the Private folder
// 3) Otherwise, just place the source file at InPath (the default set above)
if(AbsoluteInPath == RootPath)
{
OutSourcePath = (ClassPathLocation == EClassLocation::Public) ? PrivatePath : AbsoluteInPath;
}
else if(ClassPathLocation == EClassLocation::Public)
{
OutSourcePath = AbsoluteInPath.Replace(*PublicPath, *PrivatePath);
}
else if(ClassPathLocation == EClassLocation::Classes)
{
OutSourcePath = AbsoluteInPath.Replace(*ClassesPath, *PrivatePath);
}
return !OutHeaderPath.IsEmpty() && !OutSourcePath.IsEmpty();
}
bool GameProjectUtils::GetClassLocation(const FString& InPath, const FModuleContextInfo& ModuleInfo, EClassLocation& OutClassLocation, FText* const OutFailReason)
{
const FString AbsoluteInPath = FPaths::ConvertRelativePathToFull(InPath) / ""; // Ensure trailing /
OutClassLocation = EClassLocation::UserDefined;
if(!IsValidSourcePath(InPath, ModuleInfo, OutFailReason))
{
return false;
}
const FString RootPath = ModuleInfo.ModuleSourcePath;
const FString PublicPath = RootPath / "Public" / ""; // Ensure trailing /
const FString PrivatePath = RootPath / "Private" / ""; // Ensure trailing /
const FString ClassesPath = RootPath / "Classes" / ""; // Ensure trailing /
// If either the Public or Private path exists, and we're in the root, force the header/source file to use one of these folders
const bool bPublicPathExists = IFileManager::Get().DirectoryExists(*PublicPath);
const bool bPrivatePathExists = IFileManager::Get().DirectoryExists(*PrivatePath);
const bool bForceInternalPath = AbsoluteInPath == RootPath && (bPublicPathExists || bPrivatePathExists);
if(AbsoluteInPath == RootPath)
{
OutClassLocation = (bPublicPathExists || bForceInternalPath) ? EClassLocation::Public : EClassLocation::UserDefined;
}
else if(AbsoluteInPath.StartsWith(PublicPath))
{
OutClassLocation = EClassLocation::Public;
}
else if(AbsoluteInPath.StartsWith(PrivatePath))
{
OutClassLocation = EClassLocation::Private;
}
else if(AbsoluteInPath.StartsWith(ClassesPath))
{
OutClassLocation = EClassLocation::Classes;
}
else
{
OutClassLocation = EClassLocation::UserDefined;
}
return true;
}
GameProjectUtils::EProjectDuplicateResult GameProjectUtils::DuplicateProjectForUpgrade( const FString& InProjectFile, FString& OutNewProjectFile )
{
IPlatformFile &PlatformFile = FPlatformFileManager::Get().GetPlatformFile();
// Get the directory part of the project name
FString OldDirectoryName = FPaths::GetPath(InProjectFile);
FPaths::NormalizeDirectoryName(OldDirectoryName);
FString NewDirectoryName = OldDirectoryName;
// Strip off any previous version number from the project name
for(int32 LastSpace; NewDirectoryName.FindLastChar(' ', LastSpace); )
{
const TCHAR *End = *NewDirectoryName + LastSpace + 1;
if(End[0] != '4' || End[1] != '.' || !FChar::IsDigit(End[2]))
{
break;
}
End += 3;
while(FChar::IsDigit(*End))
{
End++;
}
if(*End != 0)
{
break;
}
NewDirectoryName = NewDirectoryName.Left(LastSpace).TrimTrailing();
}
// Append the new version number
NewDirectoryName += FString::Printf(TEXT(" %s"), *FEngineVersion::Current().ToString(EVersionComponent::Minor));
// Find a directory name that doesn't exist
FString BaseDirectoryName = NewDirectoryName;
for(int32 Idx = 2; IFileManager::Get().DirectoryExists(*NewDirectoryName); Idx++)
{
NewDirectoryName = FString::Printf(TEXT("%s - %d"), *BaseDirectoryName, Idx);
}
// Recursively find all the files we need to copy, excluding those that are within the directories listed in SourceDirectoriesToSkip
struct FGatherFilesToCopyHelper
{
public:
FGatherFilesToCopyHelper(FString InRootSourceDirectory)
: RootSourceDirectory(MoveTemp(InRootSourceDirectory))
{
static const FString RelativeDirectoriesToSkip[] = {
TEXT("Binaries"),
TEXT("DerivedDataCache"),
TEXT("Intermediate"),
TEXT("Saved/Autosaves"),
TEXT("Saved/Backup"),
TEXT("Saved/Config"),
TEXT("Saved/Cooked"),
TEXT("Saved/HardwareSurvey"),
TEXT("Saved/Logs"),
TEXT("Saved/StagedBuilds"),
};
SourceDirectoriesToSkip.Reserve(ARRAY_COUNT(RelativeDirectoriesToSkip));
for (const FString& RelativeDirectoryToSkip : RelativeDirectoriesToSkip)
{
SourceDirectoriesToSkip.Emplace(RootSourceDirectory / RelativeDirectoryToSkip);
}
}
void GatherFilesToCopy(TArray<FString>& OutSourceDirectories, TArray<FString>& OutSourceFiles)
{
GatherFilesToCopy(RootSourceDirectory, OutSourceDirectories, OutSourceFiles);
}
private:
void GatherFilesToCopy(const FString& InSourceDirectoryPath, TArray<FString>& OutSourceDirectories, TArray<FString>& OutSourceFiles)
{
const FString SourceDirectorySearchWildcard = InSourceDirectoryPath / TEXT("*");
OutSourceDirectories.Emplace(InSourceDirectoryPath);
TArray<FString> SourceFilenames;
IFileManager::Get().FindFiles(SourceFilenames, *SourceDirectorySearchWildcard, true, false);
OutSourceFiles.Reserve(OutSourceFiles.Num() + SourceFilenames.Num());
for (const FString& SourceFilename : SourceFilenames)
{
OutSourceFiles.Emplace(InSourceDirectoryPath / SourceFilename);
}
TArray<FString> SourceSubDirectoryNames;
IFileManager::Get().FindFiles(SourceSubDirectoryNames, *SourceDirectorySearchWildcard, false, true);
for (const FString& SourceSubDirectoryName : SourceSubDirectoryNames)
{
const FString SourceSubDirectoryPath = InSourceDirectoryPath / SourceSubDirectoryName;
if (!SourceDirectoriesToSkip.Contains(SourceSubDirectoryPath))
{
GatherFilesToCopy(SourceSubDirectoryPath, OutSourceDirectories, OutSourceFiles);
}
}
}
FString RootSourceDirectory;
TArray<FString> SourceDirectoriesToSkip;
};
TArray<FString> SourceDirectories;
TArray<FString> SourceFiles;
FGatherFilesToCopyHelper(OldDirectoryName).GatherFilesToCopy(SourceDirectories, SourceFiles);
// Copy everything
bool bCopySucceeded = true;
bool bUserCanceled = false;
GWarn->BeginSlowTask(LOCTEXT("CreatingCopyOfProject", "Creating copy of project..."), true, true);
for(int32 Idx = 0; Idx < SourceDirectories.Num() && bCopySucceeded; Idx++)
{
FString TargetDirectory = NewDirectoryName + SourceDirectories[Idx].Mid(OldDirectoryName.Len());
bUserCanceled = GWarn->ReceivedUserCancel();
bCopySucceeded = !bUserCanceled && PlatformFile.CreateDirectory(*TargetDirectory);
GWarn->UpdateProgress(Idx + 1, SourceDirectories.Num() + SourceFiles.Num());
}
for(int32 Idx = 0; Idx < SourceFiles.Num() && bCopySucceeded; Idx++)
{
FString TargetFile = NewDirectoryName + SourceFiles[Idx].Mid(OldDirectoryName.Len());
bUserCanceled = GWarn->ReceivedUserCancel();
bCopySucceeded = !bUserCanceled && PlatformFile.CopyFile(*TargetFile, *SourceFiles[Idx]);
GWarn->UpdateProgress(SourceDirectories.Num() + Idx + 1, SourceDirectories.Num() + SourceFiles.Num());
}
GWarn->EndSlowTask();
// Wipe the directory if the user canceled or we couldn't update
if(!bCopySucceeded)
{
PlatformFile.DeleteDirectoryRecursively(*NewDirectoryName);
if(bUserCanceled)
{
return EProjectDuplicateResult::UserCanceled;
}
else
{
return EProjectDuplicateResult::Failed;
}
}
// Otherwise fixup the output project filename
OutNewProjectFile = NewDirectoryName / FPaths::GetCleanFilename(InProjectFile);
return EProjectDuplicateResult::Succeeded;
}
void GameProjectUtils::UpdateSupportedTargetPlatforms(const FName& InPlatformName, const bool bIsSupported)
{
const FString& ProjectFilename = FPaths::GetProjectFilePath();
if(!ProjectFilename.IsEmpty())
{
// First attempt to check out the file if SCC is enabled
if(ISourceControlModule::Get().IsEnabled())
{
FText UnusedFailReason;
CheckoutGameProjectFile(ProjectFilename, UnusedFailReason);
}
// Second make sure the file is writable
if(FPlatformFileManager::Get().GetPlatformFile().IsReadOnly(*ProjectFilename))
{
FPlatformFileManager::Get().GetPlatformFile().SetReadOnly(*ProjectFilename, false);
}
IProjectManager::Get().UpdateSupportedTargetPlatformsForCurrentProject(InPlatformName, bIsSupported);
}
}
void GameProjectUtils::ClearSupportedTargetPlatforms()
{
const FString& ProjectFilename = FPaths::GetProjectFilePath();
if(!ProjectFilename.IsEmpty())
{
// First attempt to check out the file if SCC is enabled
if(ISourceControlModule::Get().IsEnabled())
{
FText UnusedFailReason;
CheckoutGameProjectFile(ProjectFilename, UnusedFailReason);
}
// Second make sure the file is writable
if(FPlatformFileManager::Get().GetPlatformFile().IsReadOnly(*ProjectFilename))
{
FPlatformFileManager::Get().GetPlatformFile().SetReadOnly(*ProjectFilename, false);
}
IProjectManager::Get().ClearSupportedTargetPlatformsForCurrentProject();
}
}
void GameProjectUtils::UpdateAdditionalPluginDirectory(const FString& InDir, const bool bAddOrRemove)
{
const FString& ProjectFilename = FPaths::GetProjectFilePath();
if (!ProjectFilename.IsEmpty())
{
// First attempt to check out the file if SCC is enabled
if (ISourceControlModule::Get().IsEnabled())
{
FText UnusedFailReason;
CheckoutGameProjectFile(ProjectFilename, UnusedFailReason);
}
// Second make sure the file is writable
if (FPlatformFileManager::Get().GetPlatformFile().IsReadOnly(*ProjectFilename))
{
FPlatformFileManager::Get().GetPlatformFile().SetReadOnly(*ProjectFilename, false);
}
IProjectManager::Get().UpdateAdditionalPluginDirectory(InDir, bAddOrRemove);
}
}
bool GameProjectUtils::ReadTemplateFile(const FString& TemplateFileName, FString& OutFileContents, FText& OutFailReason)
{
const FString FullFileName = FPaths::EngineContentDir() / TEXT("Editor") / TEXT("Templates") / TemplateFileName;
if ( FFileHelper::LoadFileToString(OutFileContents, *FullFileName) )
{
return true;
}
FFormatNamedArguments Args;
Args.Add( TEXT("FullFileName"), FText::FromString( FullFileName ) );
OutFailReason = FText::Format( LOCTEXT("FailedToReadTemplateFile", "Failed to read template file \"{FullFileName}\""), Args );
return false;
}
bool GameProjectUtils::WriteOutputFile(const FString& OutputFilename, const FString& OutputFileContents, FText& OutFailReason)
{
if ( FFileHelper::SaveStringToFile(OutputFileContents, *OutputFilename ) )
{
return true;
}
FFormatNamedArguments Args;
Args.Add( TEXT("OutputFilename"), FText::FromString( OutputFilename ) );
OutFailReason = FText::Format( LOCTEXT("FailedToWriteOutputFile", "Failed to write output file \"{OutputFilename}\". Perhaps the file is Read-Only?"), Args );
return false;
}
FString GameProjectUtils::MakeCopyrightLine()
{
const FString CopyrightNotice = GetDefault<UGeneralProjectSettings>()->CopyrightNotice;
if (!CopyrightNotice.IsEmpty())
{
return FString(TEXT("// ")) + CopyrightNotice;
}
else
{
return FString();
}
}
FString GameProjectUtils::MakeCommaDelimitedList(const TArray<FString>& InList, bool bPlaceQuotesAroundEveryElement)
{
FString ReturnString;
for ( auto ListIt = InList.CreateConstIterator(); ListIt; ++ListIt )
{
FString ElementStr;
if ( bPlaceQuotesAroundEveryElement )
{
ElementStr = FString::Printf( TEXT("\"%s\""), **ListIt);
}
else
{
ElementStr = *ListIt;
}
if ( ReturnString.Len() > 0 )
{
// If this is not the first item in the list, prepend with a comma
ElementStr = FString::Printf(TEXT(", %s"), *ElementStr);
}
ReturnString += ElementStr;
}
return ReturnString;
}
FString GameProjectUtils::MakeIncludeList(const TArray<FString>& InList)
{
FString ReturnString;
for ( auto ListIt = InList.CreateConstIterator(); ListIt; ++ListIt )
{
ReturnString += FString::Printf( TEXT("#include \"%s\"") LINE_TERMINATOR, **ListIt);
}
return ReturnString;
}
FString GameProjectUtils::DetermineModuleIncludePath(const FModuleContextInfo& ModuleInfo, const FString& FileRelativeTo)
{
FString ModuleIncludePath;
if(FindSourceFileInProject(ModuleInfo.ModuleName + ".h", ModuleInfo.ModuleSourcePath, ModuleIncludePath))
{
// Work out where the module header is;
// if it's Public then we can include it without any path since all Public and Classes folders are on the include path
// if it's located elsewhere, then we'll need to include it relative to the module source root as we can't guarantee
// that other folders are on the include paths
EClassLocation ModuleLocation;
if(GetClassLocation(ModuleIncludePath, ModuleInfo, ModuleLocation))
{
if(ModuleLocation == EClassLocation::Public || ModuleLocation == EClassLocation::Classes)
{
ModuleIncludePath = ModuleInfo.ModuleName + ".h";
}
else
{
// If the path to our new class is the same as the path to the module, we can include it directly
const FString ModulePath = FPaths::ConvertRelativePathToFull(FPaths::GetPath(ModuleIncludePath));
const FString ClassPath = FPaths::ConvertRelativePathToFull(FPaths::GetPath(FileRelativeTo));
if(ModulePath == ClassPath)
{
ModuleIncludePath = ModuleInfo.ModuleName + ".h";
}
else
{
// Updates ModuleIncludePath internally
if(!FPaths::MakePathRelativeTo(ModuleIncludePath, *ModuleInfo.ModuleSourcePath))
{
// Failed; just assume we can include it without any relative path
ModuleIncludePath = ModuleInfo.ModuleName + ".h";
}
}
}
}
else
{
// Failed; just assume we can include it without any relative path
ModuleIncludePath = ModuleInfo.ModuleName + ".h";
}
}
else
{
// This could potentially fail when generating new projects if the module file hasn't yet been created; just assume we can include it without any relative path
ModuleIncludePath = ModuleInfo.ModuleName + ".h";
}
return ModuleIncludePath;
}
/**
* Generates UObject class constructor definition with property overrides.
*
* @param Out String to assign generated constructor to.
* @param PrefixedClassName Prefixed class name for which we generate the constructor.
* @param PropertyOverridesStr String with property overrides in the constructor.
* @param OutFailReason Template read function failure reason.
*
* @returns True on success. False otherwise.
*/
bool GenerateConstructorDefinition(FString& Out, const FString& PrefixedClassName, const FString& PropertyOverridesStr, FText& OutFailReason)
{
FString Template;
if (!GameProjectUtils::ReadTemplateFile(TEXT("UObjectClassConstructorDefinition.template"), Template, OutFailReason))
{
return false;
}
Out = Template.Replace(TEXT("%PREFIXED_CLASS_NAME%"), *PrefixedClassName, ESearchCase::CaseSensitive);
Out = Out.Replace(TEXT("%PROPERTY_OVERRIDES%"), *PropertyOverridesStr, ESearchCase::CaseSensitive);
return true;
}
/**
* Generates UObject class constructor declaration.
*
* @param Out String to assign generated constructor to.
* @param PrefixedClassName Prefixed class name for which we generate the constructor.
* @param OutFailReason Template read function failure reason.
*
* @returns True on success. False otherwise.
*/
bool GenerateConstructorDeclaration(FString& Out, const FString& PrefixedClassName, FText& OutFailReason)
{
FString Template;
if (!GameProjectUtils::ReadTemplateFile(TEXT("UObjectClassConstructorDeclaration.template"), Template, OutFailReason))
{
return false;
}
Out = Template.Replace(TEXT("%PREFIXED_CLASS_NAME%"), *PrefixedClassName, ESearchCase::CaseSensitive);
return true;
}
bool GameProjectUtils::GenerateClassHeaderFile(const FString& NewHeaderFileName, const FString UnPrefixedClassName, const FNewClassInfo ParentClassInfo, const TArray<FString>& ClassSpecifierList, const FString& ClassProperties, const FString& ClassFunctionDeclarations, FString& OutSyncLocation, const FModuleContextInfo& ModuleInfo, bool bDeclareConstructor, FText& OutFailReason)
{
FString Template;
if ( !ReadTemplateFile(ParentClassInfo.GetHeaderTemplateFilename(), Template, OutFailReason) )
{
return false;
}
const FString ClassPrefix = ParentClassInfo.GetClassPrefixCPP();
const FString PrefixedClassName = ClassPrefix + UnPrefixedClassName;
const FString PrefixedBaseClassName = ClassPrefix + ParentClassInfo.GetClassNameCPP();
FString BaseClassIncludeDirective;
FString BaseClassIncludePath;
if(ParentClassInfo.GetIncludePath(BaseClassIncludePath))
{
BaseClassIncludeDirective = FString::Printf(TEXT("#include \"%s\""), *BaseClassIncludePath);
}
FString ModuleAPIMacro;
{
EClassLocation ClassPathLocation = EClassLocation::UserDefined;
if ( GetClassLocation(NewHeaderFileName, ModuleInfo, ClassPathLocation) )
{
// If this class isn't Private, make sure and include the API macro so it can be linked within other modules
if ( ClassPathLocation != EClassLocation::Private )
{
ModuleAPIMacro = ModuleInfo.ModuleName.ToUpper() + "_API "; // include a trailing space for the template formatting
}
}
}
FString EventualConstructorDeclaration;
if (bDeclareConstructor)
{
if (!GenerateConstructorDeclaration(EventualConstructorDeclaration, PrefixedClassName, OutFailReason))
{
return false;
}
}
// Not all of these will exist in every class template
FString FinalOutput = Template.Replace(TEXT("%COPYRIGHT_LINE%"), *MakeCopyrightLine(), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%UNPREFIXED_CLASS_NAME%"), *UnPrefixedClassName, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%CLASS_MODULE_API_MACRO%"), *ModuleAPIMacro, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%UCLASS_SPECIFIER_LIST%"), *MakeCommaDelimitedList(ClassSpecifierList, false), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%PREFIXED_CLASS_NAME%"), *PrefixedClassName, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%PREFIXED_BASE_CLASS_NAME%"), *PrefixedBaseClassName, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%EVENTUAL_CONSTRUCTOR_DECLARATION%"), *EventualConstructorDeclaration, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%CLASS_PROPERTIES%"), *ClassProperties, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%CLASS_FUNCTION_DECLARATIONS%"), *ClassFunctionDeclarations, ESearchCase::CaseSensitive);
if (BaseClassIncludeDirective.Len() == 0)
{
FinalOutput = FinalOutput.Replace(TEXT("%BASE_CLASS_INCLUDE_DIRECTIVE%") LINE_TERMINATOR, TEXT(""), ESearchCase::CaseSensitive);
}
FinalOutput = FinalOutput.Replace(TEXT("%BASE_CLASS_INCLUDE_DIRECTIVE%"), *BaseClassIncludeDirective, ESearchCase::CaseSensitive);
HarvestCursorSyncLocation( FinalOutput, OutSyncLocation );
return WriteOutputFile(NewHeaderFileName, FinalOutput, OutFailReason);
}
static bool TryParseIncludeDirective(const FString& Text, int StartPos, int EndPos, FString& IncludePath)
{
// Check if the line starts with a # character
int Pos = StartPos;
while (Pos < EndPos && FChar::IsWhitespace(Text[Pos]))
{
Pos++;
}
if (Pos == EndPos || Text[Pos++] != '#')
{
return false;
}
while (Pos < EndPos && FChar::IsWhitespace(Text[Pos]))
{
Pos++;
}
// Check it's an include directive
const TCHAR* IncludeText = TEXT("include");
for (int Idx = 0; IncludeText[Idx] != 0; Idx++)
{
if (Pos == EndPos || Text[Pos] != IncludeText[Idx])
{
return false;
}
Pos++;
}
while (Pos < EndPos && FChar::IsWhitespace(Text[Pos]))
{
Pos++;
}
// Parse out the quoted include path
if (Pos == EndPos || Text[Pos++] != '"')
{
return false;
}
int IncludePathPos = Pos;
while (Pos < EndPos && Text[Pos] != '"')
{
Pos++;
}
IncludePath = Text.Mid(IncludePathPos, Pos - IncludePathPos);
return true;
}
static bool IsUsingOldStylePch(FString BaseDir)
{
// Find all the cpp files under the base directory
TArray<FString> Files;
IFileManager::Get().FindFilesRecursive(Files, *BaseDir, TEXT("*.cpp"), true, false, false);
// Parse the first include directive for up to 16 include paths
TArray<FString> FirstIncludedFiles;
for (int Idx = 0; Idx < Files.Num() && Idx < 16; Idx++)
{
FString Text;
FFileHelper::LoadFileToString(Text, *Files[Idx]);
int LinePos = 0;
while(LinePos < Text.Len())
{
int EndOfLinePos = LinePos;
while (EndOfLinePos < Text.Len() && Text[EndOfLinePos] != '\n')
{
EndOfLinePos++;
}
FString IncludePath;
if (TryParseIncludeDirective(Text, LinePos, EndOfLinePos, IncludePath))
{
FirstIncludedFiles.AddUnique(FPaths::GetCleanFilename(IncludePath));
break;
}
LinePos = EndOfLinePos + 1;
}
}
return FirstIncludedFiles.Num() == 1 && Files.Num() > 1;
}
bool GameProjectUtils::GenerateClassCPPFile(const FString& NewCPPFileName, const FString UnPrefixedClassName, const FNewClassInfo ParentClassInfo, const TArray<FString>& AdditionalIncludes, const TArray<FString>& PropertyOverrides, const FString& AdditionalMemberDefinitions, FString& OutSyncLocation, const FModuleContextInfo& ModuleInfo, FText& OutFailReason)
{
FString Template;
if ( !ReadTemplateFile(ParentClassInfo.GetSourceTemplateFilename(), Template, OutFailReason) )
{
return false;
}
const FString ClassPrefix = ParentClassInfo.GetClassPrefixCPP();
const FString PrefixedClassName = ClassPrefix + UnPrefixedClassName;
const FString PrefixedBaseClassName = ClassPrefix + ParentClassInfo.GetClassNameCPP();
EClassLocation ClassPathLocation = EClassLocation::UserDefined;
if ( !GetClassLocation(NewCPPFileName, ModuleInfo, ClassPathLocation, &OutFailReason) )
{
return false;
}
FString AdditionalIncludesStr;
for (int32 IncludeIdx = 0; IncludeIdx < AdditionalIncludes.Num(); ++IncludeIdx)
{
if (IncludeIdx > 0)
{
AdditionalIncludesStr += LINE_TERMINATOR;
}
AdditionalIncludesStr += FString::Printf(TEXT("#include \"%s\""), *AdditionalIncludes[IncludeIdx]);
}
FString PropertyOverridesStr;
for ( int32 OverrideIdx = 0; OverrideIdx < PropertyOverrides.Num(); ++OverrideIdx )
{
if ( OverrideIdx > 0 )
{
PropertyOverridesStr += LINE_TERMINATOR;
}
PropertyOverridesStr += TEXT("\t");
PropertyOverridesStr += *PropertyOverrides[OverrideIdx];
}
// Calculate the correct include path for the module header
FString PchIncludeDirective;
if (IsUsingOldStylePch(ModuleInfo.ModuleSourcePath))
{
const FString ModuleIncludePath = DetermineModuleIncludePath(ModuleInfo, NewCPPFileName);
if (ModuleIncludePath.Len() > 0)
{
PchIncludeDirective = FString::Printf(TEXT("#include \"%s\""), *ModuleIncludePath);
}
}
FString EventualConstructorDefinition;
if (PropertyOverrides.Num() != 0)
{
if (!GenerateConstructorDefinition(EventualConstructorDefinition, PrefixedClassName, PropertyOverridesStr, OutFailReason))
{
return false;
}
}
// Not all of these will exist in every class template
FString FinalOutput = Template.Replace(TEXT("%COPYRIGHT_LINE%"), *MakeCopyrightLine(), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%UNPREFIXED_CLASS_NAME%"), *UnPrefixedClassName, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%MODULE_NAME%"), *ModuleInfo.ModuleName, ESearchCase::CaseSensitive);
if (PchIncludeDirective.Len() == 0)
{
FinalOutput = FinalOutput.Replace(TEXT("%PCH_INCLUDE_DIRECTIVE%") LINE_TERMINATOR, TEXT(""), ESearchCase::CaseSensitive);
}
FinalOutput = FinalOutput.Replace(TEXT("%PCH_INCLUDE_DIRECTIVE%"), *PchIncludeDirective, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%PREFIXED_CLASS_NAME%"), *PrefixedClassName, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%EVENTUAL_CONSTRUCTOR_DEFINITION%"), *EventualConstructorDefinition, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%ADDITIONAL_MEMBER_DEFINITIONS%"), *AdditionalMemberDefinitions, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%ADDITIONAL_INCLUDE_DIRECTIVES%"), *AdditionalIncludesStr, ESearchCase::CaseSensitive);
HarvestCursorSyncLocation( FinalOutput, OutSyncLocation );
return WriteOutputFile(NewCPPFileName, FinalOutput, OutFailReason);
}
bool GameProjectUtils::GenerateGameModuleBuildFile(const FString& NewBuildFileName, const FString& ModuleName, const TArray<FString>& PublicDependencyModuleNames, const TArray<FString>& PrivateDependencyModuleNames, FText& OutFailReason)
{
FString Template;
if (!ReadTemplateFile(TEXT("GameModule.Build.cs.template"), Template, OutFailReason))
{
return false;
}
FString FinalOutput = Template.Replace(TEXT("%COPYRIGHT_LINE%"), *MakeCopyrightLine(), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%PUBLIC_DEPENDENCY_MODULE_NAMES%"), *MakeCommaDelimitedList(PublicDependencyModuleNames), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%PRIVATE_DEPENDENCY_MODULE_NAMES%"), *MakeCommaDelimitedList(PrivateDependencyModuleNames), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%MODULE_NAME%"), *ModuleName, ESearchCase::CaseSensitive);
return WriteOutputFile(NewBuildFileName, FinalOutput, OutFailReason);
}
bool GameProjectUtils::GeneratePluginModuleBuildFile(const FString& NewBuildFileName, const FString& ModuleName, const TArray<FString>& PublicDependencyModuleNames, const TArray<FString>& PrivateDependencyModuleNames, FText& OutFailReason, bool bUseExplicitOrSharedPCHs/* = true*/)
{
FString Template;
if ( !ReadTemplateFile(TEXT("PluginModule.Build.cs.template"), Template, OutFailReason) )
{
return false;
}
FString FinalOutput = Template.Replace(TEXT("%COPYRIGHT_LINE%"), *MakeCopyrightLine(), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%PUBLIC_DEPENDENCY_MODULE_NAMES%"), *MakeCommaDelimitedList(PublicDependencyModuleNames), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%PRIVATE_DEPENDENCY_MODULE_NAMES%"), *MakeCommaDelimitedList(PrivateDependencyModuleNames), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%MODULE_NAME%"), *ModuleName, ESearchCase::CaseSensitive);
const FString PCHUsage = bUseExplicitOrSharedPCHs ? TEXT("UseExplicitOrSharedPCHs") : TEXT("UseSharedPCHs");
FinalOutput = FinalOutput.Replace(TEXT("%PCH_USAGE%"), *PCHUsage, ESearchCase::CaseSensitive);
return WriteOutputFile(NewBuildFileName, FinalOutput, OutFailReason);
}
bool GameProjectUtils::GenerateGameModuleTargetFile(const FString& NewBuildFileName, const FString& ModuleName, const TArray<FString>& ExtraModuleNames, FText& OutFailReason)
{
FString Template;
if ( !ReadTemplateFile(TEXT("Stub.Target.cs.template"), Template, OutFailReason) )
{
return false;
}
FString FinalOutput = Template.Replace(TEXT("%COPYRIGHT_LINE%"), *MakeCopyrightLine(), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%EXTRA_MODULE_NAMES%"), *MakeCommaDelimitedList(ExtraModuleNames), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%MODULE_NAME%"), *ModuleName, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%TARGET_TYPE%"), TEXT("Game"), ESearchCase::CaseSensitive);
return WriteOutputFile(NewBuildFileName, FinalOutput, OutFailReason);
}
bool GameProjectUtils::GenerateEditorModuleBuildFile(const FString& NewBuildFileName, const FString& ModuleName, const TArray<FString>& PublicDependencyModuleNames, const TArray<FString>& PrivateDependencyModuleNames, FText& OutFailReason)
{
FString Template;
if ( !ReadTemplateFile(TEXT("EditorModule.Build.cs.template"), Template, OutFailReason) )
{
return false;
}
FString FinalOutput = Template.Replace(TEXT("%COPYRIGHT_LINE%"), *MakeCopyrightLine(), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%PUBLIC_DEPENDENCY_MODULE_NAMES%"), *MakeCommaDelimitedList(PublicDependencyModuleNames), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%PRIVATE_DEPENDENCY_MODULE_NAMES%"), *MakeCommaDelimitedList(PrivateDependencyModuleNames), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%MODULE_NAME%"), *ModuleName, ESearchCase::CaseSensitive);
return WriteOutputFile(NewBuildFileName, FinalOutput, OutFailReason);
}
bool GameProjectUtils::GenerateEditorModuleTargetFile(const FString& NewBuildFileName, const FString& ModuleName, const TArray<FString>& ExtraModuleNames, FText& OutFailReason)
{
FString Template;
if ( !ReadTemplateFile(TEXT("Stub.Target.cs.template"), Template, OutFailReason) )
{
return false;
}
FString FinalOutput = Template.Replace(TEXT("%COPYRIGHT_LINE%"), *MakeCopyrightLine(), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%EXTRA_MODULE_NAMES%"), *MakeCommaDelimitedList(ExtraModuleNames), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%MODULE_NAME%"), *ModuleName, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%TARGET_TYPE%"), TEXT("Editor"), ESearchCase::CaseSensitive);
return WriteOutputFile(NewBuildFileName, FinalOutput, OutFailReason);
}
bool GameProjectUtils::GenerateGameModuleCPPFile(const FString& NewBuildFileName, const FString& ModuleName, const FString& GameName, FText& OutFailReason)
{
FString Template;
if ( !ReadTemplateFile(TEXT("GameModule.cpp.template"), Template, OutFailReason) )
{
return false;
}
FString FinalOutput = Template.Replace(TEXT("%COPYRIGHT_LINE%"), *MakeCopyrightLine(), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%MODULE_NAME%"), *ModuleName, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%GAME_NAME%"), *GameName, ESearchCase::CaseSensitive);
return WriteOutputFile(NewBuildFileName, FinalOutput, OutFailReason);
}
bool GameProjectUtils::GenerateGameModuleHeaderFile(const FString& NewBuildFileName, const TArray<FString>& PublicHeaderIncludes, FText& OutFailReason)
{
FString Template;
if ( !ReadTemplateFile(TEXT("GameModule.h.template"), Template, OutFailReason) )
{
return false;
}
FString FinalOutput = Template.Replace(TEXT("%COPYRIGHT_LINE%"), *MakeCopyrightLine(), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%PUBLIC_HEADER_INCLUDES%"), *MakeIncludeList(PublicHeaderIncludes), ESearchCase::CaseSensitive);
return WriteOutputFile(NewBuildFileName, FinalOutput, OutFailReason);
}
bool GameProjectUtils::GeneratePluginModuleCPPFile(const FString& CPPFileName, const FString& ModuleName, const FString& StartupSourceCode, FText& OutFailReason)
{
FString Template;
if (!ReadTemplateFile(TEXT("PluginModule.cpp.template"), Template, OutFailReason))
{
return false;
}
FString FinalOutput = Template.Replace(TEXT("%COPYRIGHT_LINE%"), *MakeCopyrightLine(), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%MODULE_NAME%"), *ModuleName, ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%MODULE_STARTUP_CODE%"), *StartupSourceCode, ESearchCase::CaseSensitive);
return WriteOutputFile(CPPFileName, FinalOutput, OutFailReason);
}
bool GameProjectUtils::GeneratePluginModuleHeaderFile(const FString& HeaderFileName, const TArray<FString>& PublicHeaderIncludes, FText& OutFailReason)
{
FString Template;
if (!ReadTemplateFile(TEXT("PluginModule.h.template"), Template, OutFailReason))
{
return false;
}
FString FinalOutput = Template.Replace(TEXT("%COPYRIGHT_LINE%"), *MakeCopyrightLine(), ESearchCase::CaseSensitive);
FinalOutput = FinalOutput.Replace(TEXT("%PUBLIC_HEADER_INCLUDES%"), *MakeIncludeList(PublicHeaderIncludes), ESearchCase::CaseSensitive);
return WriteOutputFile(HeaderFileName, FinalOutput, OutFailReason);
}
void GameProjectUtils::OnUpdateProjectConfirm()
{
UpdateProject();
}
void GameProjectUtils::UpdateProject(const FProjectDescriptorModifier& Modifier)
{
UpdateProject_Impl(&Modifier);
}
void GameProjectUtils::UpdateProject()
{
UpdateProject_Impl(nullptr);
}
void GameProjectUtils::UpdateProject_Impl(const FProjectDescriptorModifier* Modifier)
{
const FString& ProjectFilename = FPaths::GetProjectFilePath();
const FString& ShortFilename = FPaths::GetCleanFilename(ProjectFilename);
FText FailReason;
FText UpdateMessage;
SNotificationItem::ECompletionState NewCompletionState;
if (UpdateGameProjectFile_Impl(ProjectFilename, FDesktopPlatformModule::Get()->GetCurrentEngineIdentifier(), Modifier, FailReason))
{
// The project was updated successfully.
FFormatNamedArguments Args;
Args.Add( TEXT("ShortFilename"), FText::FromString( ShortFilename ) );
UpdateMessage = FText::Format( LOCTEXT("ProjectFileUpdateComplete", "{ShortFilename} was successfully updated."), Args );
NewCompletionState = SNotificationItem::CS_Success;
}
else
{
// The user chose to update, but the update failed. Notify the user.
FFormatNamedArguments Args;
Args.Add( TEXT("ShortFilename"), FText::FromString( ShortFilename ) );
Args.Add( TEXT("FailReason"), FailReason );
UpdateMessage = FText::Format( LOCTEXT("ProjectFileUpdateFailed", "{ShortFilename} failed to update. {FailReason}"), Args );
NewCompletionState = SNotificationItem::CS_Fail;
}
if ( UpdateGameProjectNotification.IsValid() )
{
UpdateGameProjectNotification.Pin()->SetCompletionState(NewCompletionState);
UpdateGameProjectNotification.Pin()->SetText(UpdateMessage);
UpdateGameProjectNotification.Pin()->ExpireAndFadeout();
UpdateGameProjectNotification.Reset();
}
}
void GameProjectUtils::UpdateProject(const TArray<FString>* StartupModuleNames)
{
UpdateProject(
FProjectDescriptorModifier::CreateLambda(
[StartupModuleNames](FProjectDescriptor& Desc)
{
if (StartupModuleNames != nullptr)
{
return UpdateStartupModuleNames(Desc, StartupModuleNames);
}
return false;
}));
}
void GameProjectUtils::OnUpdateProjectCancel()
{
if ( UpdateGameProjectNotification.IsValid() )
{
UpdateGameProjectNotification.Pin()->SetCompletionState(SNotificationItem::CS_None);
UpdateGameProjectNotification.Pin()->ExpireAndFadeout();
UpdateGameProjectNotification.Reset();
}
}
void GameProjectUtils::TryMakeProjectFileWriteable(const FString& ProjectFile)
{
// First attempt to check out the file if SCC is enabled
if ( ISourceControlModule::Get().IsEnabled() )
{
FText FailReason;
GameProjectUtils::CheckoutGameProjectFile(ProjectFile, FailReason);
}
// Check if it's writable
if(FPlatformFileManager::Get().GetPlatformFile().IsReadOnly(*ProjectFile))
{
FText ShouldMakeProjectWriteable = LOCTEXT("ShouldMakeProjectWriteable_Message", "'{ProjectFilename}' is read-only and cannot be updated. Would you like to make it writeable?");
FFormatNamedArguments Arguments;
Arguments.Add( TEXT("ProjectFilename"), FText::FromString(ProjectFile));
if(FMessageDialog::Open(EAppMsgType::YesNo, FText::Format(ShouldMakeProjectWriteable, Arguments)) == EAppReturnType::Yes)
{
FPlatformFileManager::Get().GetPlatformFile().SetReadOnly(*ProjectFile, false);
}
}
}
bool GameProjectUtils::UpdateGameProjectFile(const FString& ProjectFile, const FString& EngineIdentifier, const FProjectDescriptorModifier& Modifier, FText& OutFailReason)
{
return UpdateGameProjectFile_Impl(ProjectFile, EngineIdentifier, &Modifier, OutFailReason);
}
bool GameProjectUtils::UpdateGameProjectFile(const FString& ProjectFile, const FString& EngineIdentifier, FText& OutFailReason)
{
return UpdateGameProjectFile_Impl(ProjectFile, EngineIdentifier, nullptr, OutFailReason);
}
bool GameProjectUtils::UpdateGameProjectFile_Impl(const FString& ProjectFile, const FString& EngineIdentifier, const FProjectDescriptorModifier* Modifier, FText& OutFailReason)
{
// Make sure we can write to the project file
TryMakeProjectFileWriteable(ProjectFile);
// Load the descriptor
FProjectDescriptor Descriptor;
if(Descriptor.Load(ProjectFile, OutFailReason))
{
if (Modifier && Modifier->IsBound() && !Modifier->Execute(Descriptor))
{
// If modifier returns false it means that we want to drop changes.
return true;
}
// Update file on disk
return Descriptor.Save(ProjectFile, OutFailReason) && FDesktopPlatformModule::Get()->SetEngineIdentifierForProject(ProjectFile, EngineIdentifier);
}
return false;
}
bool GameProjectUtils::UpdateGameProjectFile(const FString& ProjectFilename, const FString& EngineIdentifier, const TArray<FString>* StartupModuleNames, FText& OutFailReason)
{
return UpdateGameProjectFile(ProjectFilename, EngineIdentifier,
FProjectDescriptorModifier::CreateLambda(
[StartupModuleNames](FProjectDescriptor& Desc)
{
if (StartupModuleNames != nullptr)
{
return UpdateStartupModuleNames(Desc, StartupModuleNames);
}
return false;
}
), OutFailReason);
}
bool GameProjectUtils::CheckoutGameProjectFile(const FString& ProjectFilename, FText& OutFailReason)
{
if ( !ensure(ProjectFilename.Len()) )
{
OutFailReason = LOCTEXT("NoProjectFilename", "The project filename was not specified.");
return false;
}
if ( !ISourceControlModule::Get().IsEnabled() )
{
OutFailReason = LOCTEXT("SCCDisabled", "Source control is not enabled. Enable source control in the preferences menu.");
return false;
}
FString AbsoluteFilename = FPaths::ConvertRelativePathToFull(ProjectFilename);
ISourceControlProvider& SourceControlProvider = ISourceControlModule::Get().GetProvider();
FSourceControlStatePtr SourceControlState = SourceControlProvider.GetState(AbsoluteFilename, EStateCacheUsage::ForceUpdate);
TArray<FString> FilesToBeCheckedOut;
FilesToBeCheckedOut.Add(AbsoluteFilename);
bool bSuccessfullyCheckedOut = false;
OutFailReason = LOCTEXT("SCCStateInvalid", "Could not determine source control state.");
if(SourceControlState.IsValid())
{
if(SourceControlState->IsCheckedOut() || SourceControlState->IsAdded() || !SourceControlState->IsSourceControlled())
{
// Already checked out or opened for add... or not in the depot at all
bSuccessfullyCheckedOut = true;
}
else if(SourceControlState->CanCheckout() || SourceControlState->IsCheckedOutOther())
{
bSuccessfullyCheckedOut = (SourceControlProvider.Execute(ISourceControlOperation::Create<FCheckOut>(), FilesToBeCheckedOut) == ECommandResult::Succeeded);
if (!bSuccessfullyCheckedOut)
{
OutFailReason = LOCTEXT("SCCCheckoutFailed", "Failed to check out the project file.");
}
}
else if(!SourceControlState->IsCurrent())
{
OutFailReason = LOCTEXT("SCCNotCurrent", "The project file is not at head revision.");
}
}
return bSuccessfullyCheckedOut;
}
FString GameProjectUtils::GetDefaultProjectTemplateFilename()
{
return TEXT("");
}
void GameProjectUtils::GetProjectCodeFilenames(TArray<FString>& OutProjectCodeFilenames)
{
IFileManager::Get().FindFilesRecursive(OutProjectCodeFilenames, *FPaths::GameSourceDir(), TEXT("*.h"), true, false, false);
IFileManager::Get().FindFilesRecursive(OutProjectCodeFilenames, *FPaths::GameSourceDir(), TEXT("*.cpp"), true, false, false);
}
int32 GameProjectUtils::GetProjectCodeFileCount()
{
TArray<FString> Filenames;
GetProjectCodeFilenames(Filenames);
return Filenames.Num();
}
void GameProjectUtils::GetProjectSourceDirectoryInfo(int32& OutNumCodeFiles, int64& OutDirectorySize)
{
TArray<FString> Filenames;
GetProjectCodeFilenames(Filenames);
OutNumCodeFiles = Filenames.Num();
OutDirectorySize = 0;
for (const auto& filename : Filenames)
{
OutDirectorySize += IFileManager::Get().FileSize(*filename);
}
}
bool GameProjectUtils::ProjectHasCodeFiles()
{
return GameProjectUtils::GetProjectCodeFileCount() > 0;
}
bool GameProjectUtils::ProjectRequiresBuild(const FName InPlatformInfoName)
{
// early out on projects with code files
if (ProjectHasCodeFiles())
{
return true;
}
bool bRequiresBuild = false;
if (!FApp::IsEngineInstalled())
{
// check to see if the default build settings have changed
bRequiresBuild |= !HasDefaultBuildSettings(InPlatformInfoName);
}
// check to see if any plugins beyond the defaults have been enabled
bRequiresBuild |= IProjectManager::Get().IsNonDefaultPluginEnabled();
return bRequiresBuild;
}
bool GameProjectUtils::DoProjectSettingsMatchDefault(const FString& InPlatformName, const FString& InSection, const TArray<FString>* InBoolKeys, const TArray<FString>* InIntKeys, const TArray<FString>* InStringKeys)
{
FConfigFile ProjIni;
FConfigFile DefaultIni;
FConfigCacheIni::LoadLocalIniFile(ProjIni, TEXT("Engine"), true, *InPlatformName, true);
FConfigCacheIni::LoadExternalIniFile(DefaultIni, TEXT("Engine"), *FPaths::EngineConfigDir(), *FPaths::EngineConfigDir(), true, NULL, true);
if (InBoolKeys != NULL)
{
for (int Index = 0; Index < InBoolKeys->Num(); ++Index)
{
FString Default(TEXT("False")), Project(TEXT("False"));
DefaultIni.GetString(*InSection, *((*InBoolKeys)[Index]), Default);
ProjIni.GetString(*InSection, *((*InBoolKeys)[Index]), Project);
if (Default.Compare(Project, ESearchCase::IgnoreCase))
{
return false;
}
}
}
if (InIntKeys != NULL)
{
for (int Index = 0; Index < InIntKeys->Num(); ++Index)
{
int64 Default(0), Project(0);
DefaultIni.GetInt64(*InSection, *((*InIntKeys)[Index]), Default);
ProjIni.GetInt64(*InSection, *((*InIntKeys)[Index]), Project);
if (Default != Project)
{
return false;
}
}
}
if (InStringKeys != NULL)
{
for (int Index = 0; Index < InStringKeys->Num(); ++Index)
{
FString Default(TEXT("False")), Project(TEXT("False"));
DefaultIni.GetString(*InSection, *((*InStringKeys)[Index]), Default);
ProjIni.GetString(*InSection, *((*InStringKeys)[Index]), Project);
if (Default.Compare(Project, ESearchCase::IgnoreCase))
{
return false;
}
}
}
return true;
}
bool GameProjectUtils::HasDefaultBuildSettings(const FName InPlatformInfoName)
{
// first check default build settings for all platforms
TArray<FString> BoolKeys, IntKeys, StringKeys, BuildKeys;
BuildKeys.Add(TEXT("bCompileApex")); BuildKeys.Add(TEXT("bCompileBox2D")); BuildKeys.Add(TEXT("bCompileICU"));
BuildKeys.Add(TEXT("bCompileSimplygon")); BuildKeys.Add(TEXT("bCompileSimplygonSSF")); BuildKeys.Add(TEXT("bCompileLeanAndMeanUE"));
BuildKeys.Add(TEXT("bIncludeADO")); BuildKeys.Add(TEXT("bCompileRecast")); BuildKeys.Add(TEXT("bCompileSpeedTree"));
BuildKeys.Add(TEXT("bCompileWithPluginSupport")); BuildKeys.Add(TEXT("bCompilePhysXVehicle")); BuildKeys.Add(TEXT("bCompileFreeType"));
BuildKeys.Add(TEXT("bCompileForSize")); BuildKeys.Add(TEXT("bCompileCEF3"));
const PlatformInfo::FPlatformInfo* const PlatInfo = PlatformInfo::FindPlatformInfo(InPlatformInfoName);
check(PlatInfo);
if (!DoProjectSettingsMatchDefault(PlatInfo->TargetPlatformName.ToString(), TEXT("/Script/BuildSettings.BuildSettings"), &BuildKeys))
{
return false;
}
if (PlatInfo->SDKStatus == PlatformInfo::EPlatformSDKStatus::Installed)
{
const ITargetPlatform* const Platform = GetTargetPlatformManager()->FindTargetPlatform(PlatInfo->TargetPlatformName.ToString());
if (Platform)
{
FString PlatformSection;
Platform->GetBuildProjectSettingKeys(PlatformSection, BoolKeys, IntKeys, StringKeys);
return DoProjectSettingsMatchDefault(PlatInfo->TargetPlatformName.ToString(), PlatformSection, &BoolKeys, &IntKeys, &StringKeys);
}
}
return true;
}
TArray<FString> GameProjectUtils::GetRequiredAdditionalDependencies(const FNewClassInfo& ClassInfo)
{
TArray<FString> Out;
switch (ClassInfo.ClassType)
{
case FNewClassInfo::EClassType::SlateWidget:
case FNewClassInfo::EClassType::SlateWidgetStyle:
Out.Reserve(2);
Out.Add(TEXT("Slate"));
Out.Add(TEXT("SlateCore"));
break;
case FNewClassInfo::EClassType::UObject:
auto ClassPackageName = ClassInfo.BaseClass->GetOutermost()->GetFName().ToString();
checkf(ClassPackageName.StartsWith(TEXT("/Script/")), TEXT("Class outermost should start with /Script/"));
Out.Add(ClassPackageName.Mid(8)); // Skip the /Script/ prefix.
break;
}
return Out;
}
GameProjectUtils::EAddCodeToProjectResult GameProjectUtils::AddCodeToProject_Internal(const FString& NewClassName, const FString& NewClassPath, const FModuleContextInfo& ModuleInfo, const FNewClassInfo ParentClassInfo, const TSet<FString>& DisallowedHeaderNames, FString& OutHeaderFilePath, FString& OutCppFilePath, FText& OutFailReason)
{
if ( !ParentClassInfo.IsSet() )
{
OutFailReason = LOCTEXT("MissingParentClass", "You must specify a parent class");
return EAddCodeToProjectResult::InvalidInput;
}
const FString CleanClassName = ParentClassInfo.GetCleanClassName(NewClassName);
const FString FinalClassName = ParentClassInfo.GetFinalClassName(NewClassName);
if (!IsValidClassNameForCreation(FinalClassName, ModuleInfo, DisallowedHeaderNames, OutFailReason))
{
return EAddCodeToProjectResult::InvalidInput;
}
if ( !FApp::HasGameName() )
{
OutFailReason = LOCTEXT("AddCodeToProject_NoGameName", "You can not add code because you have not loaded a project.");
return EAddCodeToProjectResult::FailedToAddCode;
}
FString NewHeaderPath;
FString NewCppPath;
if ( !CalculateSourcePaths(NewClassPath, ModuleInfo, NewHeaderPath, NewCppPath, &OutFailReason) )
{
return EAddCodeToProjectResult::FailedToAddCode;
}
FScopedSlowTask SlowTask( 7, LOCTEXT( "AddingCodeToProject", "Adding code to project..." ) );
SlowTask.MakeDialog();
SlowTask.EnterProgressFrame();
auto RequiredDependencies = GetRequiredAdditionalDependencies(ParentClassInfo);
RequiredDependencies.Remove(ModuleInfo.ModuleName);
// Update project file if needed.
auto bUpdateProjectModules = false;
// If the project does not already contain code, add the primary game module
TArray<FString> CreatedFiles;
TArray<FString> StartupModuleNames;
const bool bProjectHadCodeFiles = ProjectHasCodeFiles();
if (!bProjectHadCodeFiles)
{
// We always add the basic source code to the root directory, not the potential sub-directory provided by NewClassPath
const FString SourceDir = FPaths::GameSourceDir().LeftChop(1); // Trim the trailing /
// Assuming the game name is the same as the primary game module name
const FString GameModuleName = FApp::GetGameName();
if ( GenerateBasicSourceCode(SourceDir, GameModuleName, FPaths::GameDir(), StartupModuleNames, CreatedFiles, OutFailReason) )
{
bUpdateProjectModules = true;
}
else
{
DeleteCreatedFiles(SourceDir, CreatedFiles);
return EAddCodeToProjectResult::FailedToAddCode;
}
}
if (RequiredDependencies.Num() > 0 || bUpdateProjectModules)
{
UpdateProject(
FProjectDescriptorModifier::CreateLambda(
[&StartupModuleNames, &RequiredDependencies, &ModuleInfo, bUpdateProjectModules](FProjectDescriptor& Descriptor)
{
bool bNeedsUpdate = false;
bNeedsUpdate |= UpdateStartupModuleNames(Descriptor, bUpdateProjectModules ? &StartupModuleNames : nullptr);
bNeedsUpdate |= UpdateRequiredAdditionalDependencies(Descriptor, RequiredDependencies, ModuleInfo.ModuleName);
return bNeedsUpdate;
}));
}
SlowTask.EnterProgressFrame();
// Class Header File
const FString NewHeaderFilename = NewHeaderPath / ParentClassInfo.GetHeaderFilename(NewClassName);
{
FString UnusedSyncLocation;
TArray<FString> ClassSpecifiers;
// Set UCLASS() specifiers based on parent class type. Currently, only UInterface uses this.
if (ParentClassInfo.ClassType == FNewClassInfo::EClassType::UInterface)
{
ClassSpecifiers.Add(TEXT("MinimalAPI"));
}
if ( GenerateClassHeaderFile(NewHeaderFilename, CleanClassName, ParentClassInfo, ClassSpecifiers, TEXT(""), TEXT(""), UnusedSyncLocation, ModuleInfo, false, OutFailReason) )
{
CreatedFiles.Add(NewHeaderFilename);
}
else
{
DeleteCreatedFiles(NewHeaderPath, CreatedFiles);
return EAddCodeToProjectResult::FailedToAddCode;
}
}
SlowTask.EnterProgressFrame();
// Class CPP file
const FString NewCppFilename = NewCppPath / ParentClassInfo.GetSourceFilename(NewClassName);
{
FString UnusedSyncLocation;
if ( GenerateClassCPPFile(NewCppFilename, CleanClassName, ParentClassInfo, TArray<FString>(), TArray<FString>(), TEXT(""), UnusedSyncLocation, ModuleInfo, OutFailReason) )
{
CreatedFiles.Add(NewCppFilename);
}
else
{
DeleteCreatedFiles(NewCppPath, CreatedFiles);
return EAddCodeToProjectResult::FailedToAddCode;
}
}
SlowTask.EnterProgressFrame();
TArray<FString> CreatedFilesForExternalAppRead;
CreatedFilesForExternalAppRead.Reserve(CreatedFiles.Num());
for (const FString& CreatedFile : CreatedFiles)
{
CreatedFilesForExternalAppRead.Add( IFileManager::Get().ConvertToAbsolutePathForExternalAppForRead(*CreatedFile) );
}
bool bGenerateProjectFiles = true;
// First see if we can avoid a full generation by adding the new files to an already open project
if ( bProjectHadCodeFiles && FSourceCodeNavigation::AddSourceFiles(CreatedFilesForExternalAppRead) )
{
// We successfully added the new files to the solution, but we still need to run UBT with -gather to update any UBT makefiles
if ( FDesktopPlatformModule::Get()->InvalidateMakefiles(FPaths::RootDir(), FPaths::GetProjectFilePath(), GWarn) )
{
// We managed the gather, so we can skip running the full generate
bGenerateProjectFiles = false;
}
}
if ( bGenerateProjectFiles )
{
// Generate project files if we happen to be using a project file.
if ( !FDesktopPlatformModule::Get()->GenerateProjectFiles(FPaths::RootDir(), FPaths::GetProjectFilePath(), GWarn) )
{
OutFailReason = LOCTEXT("FailedToGenerateProjectFiles", "Failed to generate project files.");
return EAddCodeToProjectResult::FailedToHotReload;
}
}
SlowTask.EnterProgressFrame();
// Mark the files for add in SCC
ISourceControlProvider& SourceControlProvider = ISourceControlModule::Get().GetProvider();
if ( ISourceControlModule::Get().IsEnabled() && SourceControlProvider.IsAvailable() )
{
SourceControlProvider.Execute(ISourceControlOperation::Create<FMarkForAdd>(), CreatedFilesForExternalAppRead);
}
SlowTask.EnterProgressFrame( 1.0f, LOCTEXT("CompilingCPlusPlusCode", "Compiling new C++ code. Please wait..."));
OutHeaderFilePath = NewHeaderFilename;
OutCppFilePath = NewCppFilename;
if (!bProjectHadCodeFiles)
{
// This is the first time we add code to this project so compile its game DLL
const FString GameModuleName = FApp::GetGameName();
check(ModuleInfo.ModuleName == GameModuleName);
IHotReloadInterface& HotReloadSupport = FModuleManager::LoadModuleChecked<IHotReloadInterface>("HotReload");
const bool bReloadAfterCompiling = true;
const bool bForceCodeProject = true;
const bool bFailIfGeneratedCodeChanges = false;
if (!HotReloadSupport.RecompileModule(*GameModuleName, bReloadAfterCompiling, *GWarn, bFailIfGeneratedCodeChanges, bForceCodeProject))
{
OutFailReason = LOCTEXT("FailedToCompileNewGameModule", "Failed to compile newly created game module.");
return EAddCodeToProjectResult::FailedToHotReload;
}
// Notify that we've created a brand new module
FSourceCodeNavigation::AccessOnNewModuleAdded().Broadcast(*GameModuleName);
}
else if (GetDefault<UEditorPerProjectUserSettings>()->bAutomaticallyHotReloadNewClasses)
{
FModuleStatus ModuleStatus;
const FName ModuleFName = *ModuleInfo.ModuleName;
if (ensure(FModuleManager::Get().QueryModule(ModuleFName, ModuleStatus)))
{
// Compile the module that the class was added to so that the newly added class with appear in the Content Browser
TArray<UPackage*> PackagesToRebind;
if (ModuleStatus.bIsLoaded)
{
const bool bIsHotReloadable = FModuleManager::Get().DoesLoadedModuleHaveUObjects(ModuleFName);
if (bIsHotReloadable)
{
// Is there a UPackage with the same name as this module?
const FString PotentialPackageName = FString(TEXT("/Script/")) + ModuleInfo.ModuleName;
UPackage* Package = FindPackage(nullptr, *PotentialPackageName);
if (Package)
{
PackagesToRebind.Add(Package);
}
}
}
IHotReloadInterface& HotReloadSupport = FModuleManager::LoadModuleChecked<IHotReloadInterface>("HotReload");
if (PackagesToRebind.Num() > 0)
{
// Perform a hot reload
const bool bWaitForCompletion = true;
ECompilationResult::Type CompilationResult = HotReloadSupport.RebindPackages( PackagesToRebind, TArray<FName>(), bWaitForCompletion, *GWarn );
if( CompilationResult != ECompilationResult::Succeeded && CompilationResult != ECompilationResult::UpToDate )
{
OutFailReason = FText::Format(LOCTEXT("FailedToHotReloadModuleFmt", "Failed to automatically hot reload the '{0}' module."), FText::FromString(ModuleInfo.ModuleName));
return EAddCodeToProjectResult::FailedToHotReload;
}
}
else
{
// Perform a regular unload, then reload
const bool bReloadAfterRecompile = true;
const bool bForceCodeProject = false;
const bool bFailIfGeneratedCodeChanges = true;
if (!HotReloadSupport.RecompileModule(ModuleFName, bReloadAfterRecompile, *GWarn, bFailIfGeneratedCodeChanges, bForceCodeProject))
{
OutFailReason = FText::Format(LOCTEXT("FailedToCompileModuleFmt", "Failed to automatically compile the '{0}' module."), FText::FromString(ModuleInfo.ModuleName));
return EAddCodeToProjectResult::FailedToHotReload;
}
}
}
}
return EAddCodeToProjectResult::Succeeded;
}
bool GameProjectUtils::FindSourceFileInProject(const FString& InFilename, const FString& InSearchPath, FString& OutPath)
{
TArray<FString> Filenames;
IFileManager::Get().FindFilesRecursive(Filenames, *InSearchPath, *InFilename, true, false, false);
if(Filenames.Num())
{
// Assume it's the first match (we should really only find a single file with a given name within a project anyway)
OutPath = Filenames[0];
return true;
}
return false;
}
void GameProjectUtils::HarvestCursorSyncLocation( FString& FinalOutput, FString& OutSyncLocation )
{
OutSyncLocation.Empty();
// Determine the cursor focus location if this file will by synced after creation
TArray<FString> Lines;
FinalOutput.ParseIntoArray( Lines, TEXT( "\n" ), false );
for( int32 LineIdx = 0; LineIdx < Lines.Num(); ++LineIdx )
{
const FString& Line = Lines[ LineIdx ];
int32 CharLoc = Line.Find( TEXT( "%CURSORFOCUSLOCATION%" ) );
if( CharLoc != INDEX_NONE )
{
// Found the sync marker
OutSyncLocation = FString::Printf( TEXT( "%d:%d" ), LineIdx + 1, CharLoc + 1 );
break;
}
}
// If we did not find the sync location, just sync to the top of the file
if( OutSyncLocation.IsEmpty() )
{
OutSyncLocation = TEXT( "1:1" );
}
// Now remove the cursor focus marker
FinalOutput = FinalOutput.Replace(TEXT("%CURSORFOCUSLOCATION%"), TEXT(""), ESearchCase::CaseSensitive);
}
bool GameProjectUtils::InsertFeaturePacksIntoINIFile(const FProjectInformation& InProjectInfo, FText& OutFailReason)
{
const FString ProjectName = FPaths::GetBaseFilename(InProjectInfo.ProjectFilename);
const FString TemplateName = FPaths::GetBaseFilename(InProjectInfo.TemplateFile);
const FString SrcFolder = FPaths::GetPath(InProjectInfo.TemplateFile);
const FString DestFolder = FPaths::GetPath(InProjectInfo.ProjectFilename);
const FString ProjectConfigPath = DestFolder / TEXT("Config");
const FString IniFilename = ProjectConfigPath / TEXT("DefaultGame.ini");
TArray<FString> PackList;
// First the starter content
if (InProjectInfo.bCopyStarterContent)
{
FString StarterPack;
if (InProjectInfo.TargetedHardware == EHardwareClass::Mobile)
{
StarterPack = TEXT("InsertPack=(PackSource=\"MobileStarterContent") + DefaultFeaturePackExtension + TEXT(",PackName=\"StarterContent\")");
}
else
{
StarterPack = TEXT("InsertPack=(PackSource=\"StarterContent") + DefaultFeaturePackExtension + TEXT(",PackName=\"StarterContent\")");
}
PackList.Add(StarterPack);
}
if (PackList.Num() != 0)
{
FString FileOutput;
if(FPaths::FileExists(IniFilename) && !FFileHelper::LoadFileToString(FileOutput, *IniFilename))
{
OutFailReason = LOCTEXT("FailedToReadIni", "Could not read INI file to insert feature packs");
return false;
}
FileOutput += LINE_TERMINATOR;
FileOutput += TEXT("[StartupActions]");
FileOutput += LINE_TERMINATOR;
FileOutput += TEXT("bAddPacks=True");
FileOutput += LINE_TERMINATOR;
for (int32 iLine = 0; iLine < PackList.Num(); ++iLine)
{
FileOutput += PackList[iLine] + LINE_TERMINATOR;
}
if (!FFileHelper::SaveStringToFile(FileOutput, *IniFilename))
{
OutFailReason = LOCTEXT("FailedToWriteIni", "Could not write INI file to insert feature packs");
return false;
}
}
return true;
}
bool GameProjectUtils::AddSharedContentToProject(const FProjectInformation &InProjectInfo, TArray<FString> &CreatedFiles, FText& OutFailReason)
{
//const FString TemplateName = FPaths::GetBaseFilename(InProjectInfo.TemplateFile);
const FString SrcFolder = FPaths::GetPath(InProjectInfo.TemplateFile);
const FString DestFolder = FPaths::GetPath(InProjectInfo.ProjectFilename);
const FString ProjectConfigPath = DestFolder / TEXT("Config");
const FString IniFilename = ProjectConfigPath / TEXT("DefaultGame.ini");
// Now any packs specified in the template def.
UTemplateProjectDefs* TemplateDefs = LoadTemplateDefs(SrcFolder);
if (TemplateDefs != NULL)
{
EFeaturePackDetailLevel RequiredDetail = EFeaturePackDetailLevel::High;
if (InProjectInfo.TargetedHardware == EHardwareClass::Mobile)
{
RequiredDetail = EFeaturePackDetailLevel::Standard;
}
TUniquePtr<FFeaturePackContentSource> TempFeaturePack = MakeUnique<FFeaturePackContentSource>();
bool bCopied = TempFeaturePack->InsertAdditionalResources(TemplateDefs->SharedContentPacks,RequiredDetail, DestFolder,CreatedFiles);
if( bCopied == false )
{
FFormatNamedArguments Args;
Args.Add(TEXT("TemplateName"), FText::FromString(SrcFolder));
OutFailReason = FText::Format(LOCTEXT("SharedResourceError", "Error adding shared resources for '{TemplateName}'."), Args);
return false;
}
}
return true;
}
#undef LOCTEXT_NAMESPACE