Files
UnrealEngineUWP/Engine/Source/Programs/AutomationTool/IOS/IOSPlatform.Automation.cs
Ben Marsh 5275490168 Copying //UE4/Dev-Build to //UE4/Dev-Main (Source: //UE4/Dev-Build @ 3277940)
#lockdown Nick.Penwarden
#rb none

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

Change 3233612 on 2016/12/13 by Ben.Marsh

	UGS: Fix cases where precompiled binaries are submitted for a content change.

Change 3235584 on 2016/12/14 by Ben.Marsh

	UBT: Deprecate the overridable TargetRules.ShouldUseSharedBuildEnvironment() function; targets should specify which build environment to use by setting the BuildEnvironment field in their constructor instead.

Change 3235741 on 2016/12/14 by Ben.Marsh

	UBT: Deprecate the SetupBinaries() callback on the TargetRules class. Instead of overriding this, targets may override their launch module through the "LaunchModuleName" property in their constructor, and add extra modules to the "ExtraModuleNames" field on the TargetRules object itself.

Change 3238176 on 2016/12/16 by Ben.Marsh

	UBT: New XML config file parser. Now reads once at startup and can be applied to instanced objects rather than global fields, and caches parsed output in a binary form for quicker initialization on subsequent runs.

Change 3238249 on 2016/12/16 by Ben.Marsh

	UBT: Add attribute-driven command line parser.

Change 3238462 on 2016/12/16 by Ben.Marsh

	UBT: Include the Platform, Configuration and Architecture on the TargetRules. Add a constructor which takes the TargetInfo object and deprecate the parameterless one; these fields are currently initialized before invoking the constructor in RulesAssembly.

Change 3238564 on 2016/12/16 by Ben.Marsh

	UBT: Deprecate the ModuleRules constructor which takes a TargetInfo argument. Replace it with a read-only wrapper around the target rules instead, so target-specific configuration options can be read without needing to access global static variables. Also require that it's passed to the base class constructor.

Change 3239919 on 2016/12/19 by Ben.Marsh

	UBT: Remove the "PreferredSubPlatform" property. This is only used for Windows XP support, which is being retired anyway. Having the target define its own architecture is an awkward contractiction to maintain support for, since the target rules are constructed after the architecture already has been determined.

Change 3240061 on 2016/12/19 by Ben.Marsh

	UBT: Remove ThirdPartyHeaderFinder. I don't think anything is using this any more.

Change 3240175 on 2016/12/19 by Ben.Marsh

	UBT: Add the target name and project file location to the target rules.

Change 3240490 on 2016/12/19 by Ben.Marsh

	UAT: Remove Mac staging code that requires UAT to compile and construct .target.cs files when packaging, to check bUseSteam and bUseCEF3 flags. libsteam_api.dylib is now staged at build time by adding it as a bundle resource, CEF3 is already marked as a runtime dependency by CEF3.build.cs, and UnrealCEFSubProcess.app is already marked as a runtime dependency from WebBrowser.build.cs.

Change 3240717 on 2016/12/20 by Ben.Marsh

	UAT: Allow configuring UAT to run as if on a build machine by passing the -buildmachine argument on the command line.

Change 3240718 on 2016/12/20 by Ben.Marsh

	UAT: Remove target-specific properties that are no longer used by staging (bUsesSlate, bUsesCEF3, etc...). This stuff should all be handled inside UBT.

Change 3241002 on 2016/12/20 by Ben.Marsh

	UBT: Move most target configuration settings from UEBuildConfiguration to TargetRules. This encapsulates target specific settings that will allow instancing multiple targets in the future. To facilitate migration of settings to their new location, "UEBuildConfiguration" is now a property that returns the current target rules instance.

Change 3241027 on 2016/12/20 by Ben.Marsh

	Only copy the Steamworks dylib into the app bundle for monolithic builds. For all other times, just add it as a runtime dependency.

Change 3241055 on 2016/12/20 by Ben.Marsh

	UBT: Only store a ReadOnlyTargetRules object on the instanced build target; finalize the configuration before it's instantiated.

Change 3241156 on 2016/12/20 by Ben.Marsh

	Update SwarmInterface.csproj to .NET framework 4.5, to match what all other C# tools are using.

Change 3241205 on 2016/12/20 by Ben.Marsh

	Replace all uses of TargetRules.TargetType with TargetType.

Change 3241881 on 2016/12/21 by Ben.Marsh

	UBT: Remove project file information from UEBuildContext base class. As configurable properties are moved on to the TargetRules object, it will no longer be a dependency to instantiate the platform with this path.

Change 3241895 on 2016/12/21 by Ben.Marsh

	UBT: Remove toolchain support for Windows XP.

Change 3241908 on 2016/12/21 by Ben.Marsh

	UBT: Move settings for windows targets into a WindowsTargetRules class, which is exposed for targets to modify via the TargetRules.WindowsPlatform field.

Change 3242835 on 2016/12/22 by Ben.Marsh

	UBT: Fix multiple binaries being created if plugins specify module names more than once. MfMedia.uplugin has MfMediaFactory listed twice.

Change 3242837 on 2016/12/22 by Ben.Marsh

	Change UE4EditorServices to include MacSystemIncludes rather than Cocoa.h directly; causes FVector to be defined incorrectly in non-unity builds.

Change 3242923 on 2016/12/22 by Ben.Marsh

	Build: Fixes for conforming incremental workspaces:

	* P4 have table is now reset before deleting all the files. This prevents Perforce being out of sync if the delete fails for some reason.
	* Incremental workspaces are skipped when running a clean operation, because they do not have a workspace capture file (causing a full re-sync, always). The "P4 Clean" option is still effective for cleaning these workspaces.

Change 3242961 on 2016/12/22 by Ben.Marsh

	UBT: Move entry points from PreBuildSync() and PostBuildSync() from UEToolChain to UEBuildPlatform, and make the original toolchain versions static. These functions are already at odds with the rest of the data flow within UBT because they rely on global state cached outside the toolchain instance, making assumptions that UBT is only ever going to be invoked with one target that's constructed in the same run and that nothing is being cached (eg. UBT makefiles). Moving them onto UEBuildPlatform simplifies the toolchain lifecycle for other platforms without leaving Mac and IOS any more limited than they were before.

Change 3242981 on 2016/12/22 by Ben.Marsh

	UBT: Remove symbol server handling code into UAT's platform library, since it's never needed from inside UBT.

Change 3242999 on 2016/12/22 by Ben.Marsh

	UBT: Remove the StripSymbols() function from the UEToolChain base class. This functionality is only required by UAT, so it's better suited to being exposed through UAT's modular platform classes.

Change 3243022 on 2016/12/22 by Ben.Marsh

	UBT: Require an instance of the target rules to be able to construct a toolchain in UBT. This will allow configuring toolchain-specific options from the target, using reflection from config files, and the command line.

Change 3243083 on 2016/12/22 by Ben.Marsh

	UBT: Move settings for the Windows compiler version to use onto the Windows-specific target rules.

Change 3243090 on 2016/12/22 by Ben.Marsh

	UBT: Change the third party paths in UEBuildConfiguration to constants. Changing these would not work.

Change 3243423 on 2016/12/23 by Ben.Marsh

	UBT: Move a lot of settings from BuildConfiguration to TargetRules. This allows different targets to have different settings, naturally, and moves converts argument parsing and config to be driven by attributes.

Change 3243516 on 2016/12/23 by Ben.Marsh

	UBT: Remove the ValidateUEBuildConfiguration callback, which is no longer used. (XGE settings validation occurs in XGE.cs)

Change 3244020 on 2016/12/28 by Ben.Marsh

	UBT: Remove the BaseIntermediatePath static property. Precursor to removing RelativeEnginePath and IntermediateFolder properties.

Change 3244074 on 2016/12/28 by Ben.Marsh

	UBT: Remove the RelativeEnginePath variable from BuildConfiguration. UnrealBuildTool.EngineDirectory gives the absolute path, and can be used to construct a relative path when necessary.

Change 3244076 on 2016/12/28 by Ben.Marsh

	UBT: Remove BuildConfiguration.BaseIntermediateFolder; just use a fixed directory everywhere instead.

Change 3244083 on 2016/12/28 by Ben.Marsh

	UBT: Replace FileReference and DirectoryReference instance methods for manipulating files and directories with static methods, to mirror the System.IO.File and System.IO.Directory classes.

Change 3244441 on 2016/12/31 by Ben.Marsh

	UBT: Remove code to force PDBs when building with no debug info under XGE. Verified described symptoms (that it causes PCH generation to be serialized) no longer occur.

Change 3244687 on 2017/01/03 by Matthew.Griffin

	Changed Exception to use FirstInclude.IncludeName as PrecompiledHeaderIncludeFilename can be null when this occurs

Change 3246112 on 2017/01/04 by Ben.Marsh

	UBT: Fix UHT failures building some targets with the -useprecompiled option, due to differences in the order that circularly dependent modules are parsed. Precompiled binaries are now kept in the regular AppBinaries list, but are excluded from the build at the last minute. Also change some checks from IsEngineInstalled() to bUsePrecompiled, to prevent headers being overwritten when running in a non-installed precompiled build.

Change 3246223 on 2017/01/04 by Ben.Marsh

	UBT: Prevent version manifests being overridden if a file is not being built as part of the target.

Change 3246387 on 2017/01/04 by Ben.Marsh

	UBT: Remove BuildConfiguration settings for UnrealCodeAnalyzer. This tool isn't used at the moment, but it's configured using global variables accessed from all over the UBT codebase, making it difficult to refactor the build options into an instanced object. If we bring this tool back from the dead in the future, it should be possible to implement it using the exported JSON target definition or the XGE manifest, similarly to how IncludeTool uses it.

Change 3247004 on 2017/01/04 by Ben.Marsh

	UBT: Simplify the logic for cleaning targets in UBT. Now uses FileReference/DirectoryReference objects everywhere, doesn't require the compile/link environment, and does all the checking to avoid deleting precompiled binaries in one place.

Change 3247250 on 2017/01/04 by Ben.Marsh

	UBT: Prevent precompiled binaries being added to the list of app binaries twice.

Change 3247594 on 2017/01/05 by Ben.Marsh

	Build: Run sample and template editors on the same agents as the other incremental builds. Remove ProtoStar, which does not have any non-precompiled editor target to build.

Change 3247763 on 2017/01/05 by Ben.Marsh

	UBT: Allow the toolchain to update the list of build products for each module linked into a binary. Allows Mac to add dylibs and bundle resources specified per-module without having to construct a link environment and try to link them.

Change 3247775 on 2017/01/05 by Ben.Marsh

	UBT: Instance the target compile and link environments when they are required during building, and don't persist them on the UEBuildTarget instance.

Change 3247811 on 2017/01/05 by Ben.Marsh

	EC: Add a batch file for testing postp filters.

Change 3247839 on 2017/01/05 by Ben.Marsh

	EC: Include the name of the file being compiled when parsing MSVC errors and warnings.

Change 3248101 on 2017/01/05 by Ben.Marsh

	UBT: Fix Android support for force included headers.

Change 3248533 on 2017/01/05 by Ben.Marsh

	PR #3097: UBT project supports optional platforms (Contributed by PrimalJohnScott)

Change 3249205 on 2017/01/06 by Ben.Marsh

	UAT: Fix ParseTaggedP4Output throwing an exception if the same key name is specified more than once. This can happen when parsing the output from "P4 INFO", where multiple brokers are present.

Change 3249249 on 2017/01/06 by Ben.Marsh

	UBT: Check for the existance of AndroidManifest.xml within extracted AAR directories, rather than just checking for the existance of the directory itself. Perforce does not remove empty directories when cleaning a workspace unless the rmdir option is on the workspace, so this can cause incremental build failures to fail on build machines.

Change 3249486 on 2017/01/06 by Ben.Marsh

	UBT: Use relative paths in unity files when compiling for Mac/IOS, rather than generating a separate local/remote version of the file for gathering include dependencies. Absolute paths are only used to work around the way that MSVC concatenates paths internally; we don't hit the same problems when checking dependencies.

Change 3249736 on 2017/01/06 by Ben.Marsh

	UBT: Rename CPPEnvironment to CppCompileEnvironment, and remove the separate CPPEnvironmentConfiguration object. All settings are now stored directly on the CppCompileEnvironment object.

Change 3250179 on 2017/01/07 by Ben.Marsh

	Fix creating installed build when root directory contains a space in the name.

Change 3250181 on 2017/01/07 by Ben.Marsh

	UBT: Remove some esoteric (and unused, AFAIK) options for orthogonally building different platforms.

Change 3250223 on 2017/01/07 by Ben.Marsh

	UBT: Merge the LinkEnvironment and LinkEnvironmentConfiguration classes together.

Change 3250233 on 2017/01/07 by Ben.Marsh

	UGS: Allow specifying a workspace-specific sync filter, which is applied on top of the standard filter. Also fix filter being cleared if the cancel button is pressed, and help text being stripped out.

Change 3250241 on 2017/01/07 by Ben.Marsh

	UBT: Move the options for specifying additional Android architectures to target onto an Android-specific object on the TargetRules.

Change 3250400 on 2017/01/08 by Ben.Marsh

	UBT: Move executor config settings onto the executor instances.

Change 3257708 on 2017/01/13 by Ben.Marsh

	UBT: Remove the ThirdPartySourceDirectory constant; there are many places which hard-code or assume this location anyway, and it's not going to change.

Change 3260535 on 2017/01/17 by Ben.Marsh

	Add an optional "RequiredSubmittedChange" setting to EC settings files. Allows a scheduled job to run even if there have been no code changes submitted. Test with the utilization capture job.

Change 3260875 on 2017/01/17 by Ben.Marsh

	EC: Fix workspaces getting out of sync wrt. newly added files when jobs are aborted during a sync. In such cases, the P4 have table indicates the new files have been synced locally, but the workspace is forced back to a state before it had them due to the capture file. When a following sync tries to add them again, P4 believes the workspace already has them synced.

	To work around this, we now write an additional file to the root folder of a workspace containing the last CL that was captured, and sync back to it before doing the reconcile.

Change 3261724 on 2017/01/18 by Ben.Marsh

	Allow filtering job types from the list view in EC. Hide the utilization capture job by default. Also set up notifications for the utilization capture job.

Change 3261756 on 2017/01/18 by Ben.Marsh

	IncludeTool: Prevent matching a full enum declaration as a forward declaration.

Change 3261932 on 2017/01/18 by Ben.Marsh

	EC: Add support for specifying days of the week in schedules. The following syntaxes are supported:

	"Monday, Tuesday and Wednesday at 10:30"
	"Daily except Sunday and Wednesday at 14:30"

	 Also tweak display of dates relative to now to handle dates/times in the future, and include the date when specifying a day name.

	#jira UEB-729

Change 3262676 on 2017/01/18 by Ben.Marsh

	UBT: Split UBTMakefile into its own file. (From PR #3106)

Change 3263893 on 2017/01/19 by Ben.Marsh

	UBT: Stop exporting platform classes from UBT, as well as all the referenced classes that have to be made public as a result. Any platform-specific functionality that needs to be shared with UAT is now exposed through wrappers in separate public classes, eg. WindowsExports.cs, IOSExports.cs, etc...

Change 3264291 on 2017/01/19 by Ben.Marsh

	UBT: Fix errors generating documentation in UBT, and enable it by default. Will catch more errors with new code being added. Originally in PR #3106, but redone due to conflicts.

Change 3264534 on 2017/01/19 by Ben.Marsh

	UBT: Include plugin config files in generated projects.

Change 3264571 on 2017/01/19 by Ben.Marsh

	UBT: Prevent overwriting .modules files if nothing has changed. On builders, it's common to build multiple editors in the same workspace, and changing the last modified timestamp causes BuildGraph to fail due to tampered files.

Change 3265745 on 2017/01/20 by Ben.Marsh

	UGS: Automatically open UGS when running the launcher for a second time, rather than prompting to close the original instance.

Change 3265777 on 2017/01/20 by Ben.Marsh

	UGS: Automatically close and reopen when UGS is re-ran with the shift key held down to switch into unstable mode.

Change 3268314 on 2017/01/23 by Ben.Marsh

	UBT: Make sure version manifests are stable by sorting the list of build products, so they are only touched if the contents have really changed.

Change 3269601 on 2017/01/24 by Ben.Marsh

	UBT: Fix symbol files being added to manifest for some platforms even though debug info is disabled.

Change 3269607 on 2017/01/24 by Ben.Marsh

	UBT: Fix bug where UBT would need to be invoked when switching between two editors sharing the same engine binaries on Mac. The location of the .modules file cannot be guessed on Mac by looking in the same directory as the primary output executable because it's an .app bundle, and the actual modules are nested several directories below that.

Change 3269608 on 2017/01/24 by Ben.Marsh

	UBT: Fix additional files copied into the app bundle always being updated on Mac. Now uses rsync --checksum to make sure only modified files are updated.

Change 3271062 on 2017/01/24 by Ben.Marsh

	UBT: Fixes for bugs detected by PVS Studio (PR #3161)

Change 3272421 on 2017/01/25 by Ben.Marsh

	Fix commends regarding DDC in BaseEngine.ini

	#jira UE-41076

Change 3272810 on 2017/01/25 by Ben.Marsh

	Fix VS2017 being displayed as 'Visual Studio 15' in the Windows target settings panel.

Change 3272935 on 2017/01/25 by Ben.Marsh

	Fix Metal errors launching on Mac due to use of OSX environment settings before they are initialized. Toolchain settings are now constructed on demand in a separate class, for Mac, iOS and TVOS.

Change 3274167 on 2017/01/26 by Ben.Marsh

	Fix resource files not being compiled in installed builds on Windows. Was causing metadata not to be embedded into executables.

	#jira UE-36457

Change 3275557 on 2017/01/27 by Ben.Marsh

	Expand checks for propagation of restricted folder names to include source files, and to ensure that each restricted folder is represented in the output. Also improve messaging to show the dependency chain leading to a restricted folder being referenced, and which folder it is.

Change 3275628 on 2017/01/27 by Ben.Marsh

	UBT: Splitting configuration files into one class per-file.

Change 3276784 on 2017/01/29 by Ben.Marsh

	Add an authoritative list of confidential folder names, and expose it through global BuildGraph properties ($(RestrictedFolderNames) and $(RestrictedFolderFilter)). Also switch existing scripts to use it.

Change 3276792 on 2017/01/29 by Ben.Marsh

	UBT: Use UE4CSharp.prog files to indicate which projects should be included in the solution without having to hard-code a list of them in UBT.

Change 3277263 on 2017/01/30 by Ben.Marsh

	IncludeTool: Merging various fixes.

	* Fix warnings about #include directives after first code block from parsing monolithic headers.
	* Fix exception on startup if the intermediate directory does not already exist.
	* Add a special case for ignoring missing header guards from MonolithicHeaderBoilerplate.h, rather than marking it as an inline header. Marking it as inline prevents parsing include directives, which results in including CoreTypes.h from the wrong location.
	* Create job objects for spawned compiler instances to prevent them trying allocating more memory than the system can spare.
	* Remove (unused) code which makes assumptions about files ending with "Classes.h".
	* Add a verbose per-file output log to aid with debugging.
	* Negate the MakeStandalone command line option, which was added to allow tweaking forward declarations in already optimized files, so the optimized output does not have missing headers by default.
	* Fix missing headers when creating standalone files, due to incorrect list of previous files being passed in to the OutputFile constructor. Now passes the original list of included files, not the output list.
	* Fix initial header for a cpp file sometimes being removed. Forcibly including a header at the start of the file does not use the normal pathway for spidering through includes, so a second include of the same file was being generated. Any includes of that header were being forced into output, and the earlier include was then removed due to being redundant.
	* Prevent forward declaring enums which have to be parsed by UHT. UHT relies on includes to determine a parse order, and will fail if the enum definition has not been parsed first.
	* Use a relative path for private includes in the same module if there are any. Fixes some incorrect paths, and makes it clearer that we're doing something we shouldn't.

Change 3277307 on 2017/01/30 by Ben.Marsh

	UBT: Fix private PCHs not using correct header. Causes custom definitions to be excluded from the command line.

[CL 3278101 by Ben Marsh in Main branch]
2017-01-30 16:52:08 -05:00

1553 lines
56 KiB
C#

// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using AutomationTool;
using UnrealBuildTool;
using System.Text.RegularExpressions;
using Ionic.Zip;
using Ionic.Zlib;
using System.Security.Principal;
using System.Threading;
using System.Diagnostics;
//using Manzana;
static class IOSEnvVarNames
{
// Should we code sign when staging? (defaults to 1 if not present)
static public readonly string CodeSignWhenStaging = "uebp_CodeSignWhenStaging";
}
class IOSClientProcess : IProcessResult
{
private IProcessResult childProcess;
private Thread consoleLogWorker;
//private bool processConsoleLogs;
public IOSClientProcess(IProcessResult inChildProcess, string inDeviceID)
{
childProcess = inChildProcess;
// Startup another thread that collect device console logs
//processConsoleLogs = true;
consoleLogWorker = new Thread(() => ProcessConsoleOutput(inDeviceID));
consoleLogWorker.Start();
}
public void StopProcess(bool KillDescendants = true)
{
childProcess.StopProcess(KillDescendants);
StopConsoleOutput();
}
public bool HasExited
{
get
{
bool result = childProcess.HasExited;
if(result)
{
StopConsoleOutput();
}
return result;
}
}
public string GetProcessName()
{
return childProcess.GetProcessName();
}
public void OnProcessExited()
{
childProcess.OnProcessExited();
StopConsoleOutput();
}
public void DisposeProcess()
{
childProcess.DisposeProcess();
}
public void StdOut(object sender, DataReceivedEventArgs e)
{
childProcess.StdOut(sender, e);
}
public void StdErr(object sender, DataReceivedEventArgs e)
{
childProcess.StdErr(sender, e);
}
public int ExitCode
{
get { return childProcess.ExitCode; }
set { childProcess.ExitCode = value; }
}
public string Output
{
get { return childProcess.Output; }
}
public Process ProcessObject
{
get { return childProcess.ProcessObject; }
}
public new string ToString()
{
return childProcess.ToString();
}
public void WaitForExit()
{
childProcess.WaitForExit();
}
private void StopConsoleOutput()
{
//processConsoleLogs = false;
consoleLogWorker.Join();
}
public void ProcessConsoleOutput(string inDeviceID)
{
// MobileDeviceInstance targetDevice = null;
// foreach(MobileDeviceInstance curDevice in MobileDeviceInstanceManager.GetSnapshotInstanceList())
// {
// if(curDevice.DeviceId == inDeviceID)
// {
// targetDevice = curDevice;
// break;
// }
// }
//
// if(targetDevice == null)
// {
// return;
// }
//
// targetDevice.StartSyslogService();
//
// while(processConsoleLogs)
// {
// string logData = targetDevice.GetSyslogData();
//
// Console.WriteLine("DeviceLog: " + logData);
// }
//
// targetDevice.StopSyslogService();
}
};
public class IOSPlatform : Platform
{
bool bCreatedIPA = false;
private string PlatformName = null;
private string SDKName = null;
public IOSPlatform()
:this(UnrealTargetPlatform.IOS)
{
}
public IOSPlatform(UnrealTargetPlatform TargetPlatform)
:base(TargetPlatform)
{
PlatformName = TargetPlatform.ToString();
SDKName = (TargetPlatform == UnrealTargetPlatform.TVOS) ? "appletvos" : "iphoneos";
}
// Run the integrated IPP code
// @todo ipp: How to log the output in a nice UAT way?
protected static int RunIPP(string IPPArguments)
{
List<string> Args = new List<string>();
StringBuilder Token = null;
int Index = 0;
bool bInQuote = false;
while (Index < IPPArguments.Length)
{
if (IPPArguments[Index] == '\"')
{
bInQuote = !bInQuote;
}
else if (IPPArguments[Index] == ' ' && !bInQuote)
{
if (Token != null)
{
Args.Add(Token.ToString());
Token = null;
}
}
else
{
if (Token == null)
{
Token = new StringBuilder();
}
Token.Append(IPPArguments[Index]);
}
Index++;
}
if (Token != null)
{
Args.Add(Token.ToString());
}
return RunIPP(Args.ToArray());
}
protected static int RunIPP(string[] Args)
{
return 5;//@TODO: Reintegrate IPP to IOS.Automation iPhonePackager.Program.RealMain(Args);
}
public override int RunCommand(string Command)
{
// run generic IPP commands through the interface
if (Command.StartsWith("IPP:"))
{
return RunIPP(Command.Substring(4));
}
// non-zero error code
return 4;
}
public virtual bool PrepForUATPackageOrDeploy(UnrealTargetConfiguration Config, FileReference ProjectFile, string InProjectName, string InProjectDirectory, string InExecutablePath, string InEngineDir, bool bForDistribution, string CookFlavor, bool bIsDataDeploy, bool bCreateStubIPA)
{
return IOSExports.PrepForUATPackageOrDeploy(Config, ProjectFile, InProjectName, InProjectDirectory, InExecutablePath, InEngineDir, bForDistribution, CookFlavor, bIsDataDeploy, bCreateStubIPA);
}
public virtual void GetProvisioningData(FileReference InProject, bool bDistribution, out string MobileProvision, out string SigningCertificate)
{
IOSExports.GetProvisioningData(InProject, bDistribution, out MobileProvision, out SigningCertificate);
}
public virtual bool DeployGeneratePList(FileReference ProjectFile, UnrealTargetConfiguration Config, string ProjectDirectory, bool bIsUE4Game, string GameName, string ProjectName, string InEngineDir, string AppDirectory)
{
return IOSExports.GeneratePList(ProjectFile, Config, ProjectDirectory, bIsUE4Game, GameName, ProjectName, InEngineDir, AppDirectory);
}
protected string MakeIPAFileName( UnrealTargetConfiguration TargetConfiguration, ProjectParams Params )
{
string ProjectIPA = Path.Combine(Path.GetDirectoryName(Params.RawProjectPath.FullName), "Binaries", PlatformName, (Params.Distribution ? "Distro_" : "") + Params.ShortProjectName);
if (TargetConfiguration != UnrealTargetConfiguration.Development)
{
ProjectIPA += "-" + PlatformType.ToString() + "-" + TargetConfiguration.ToString();
}
ProjectIPA += ".ipa";
return ProjectIPA;
}
protected string MakeExeFileName( UnrealTargetConfiguration TargetConfiguration, ProjectParams Params )
{
string ProjectIPA = Path.Combine(Path.GetDirectoryName(Params.RawProjectPath.FullName), "Binaries", PlatformName, Params.ShortProjectName);
if (TargetConfiguration != UnrealTargetConfiguration.Development)
{
ProjectIPA += "-" + PlatformType.ToString() + "-" + TargetConfiguration.ToString();
}
ProjectIPA += ".ipa";
return ProjectIPA;
}
// Determine if we should code sign
protected bool GetCodeSignDesirability(ProjectParams Params)
{
//@TODO: Would like to make this true, as it's the common case for everyone else
bool bDefaultNeedsSign = true;
bool bNeedsSign = false;
string EnvVar = InternalUtils.GetEnvironmentVariable(IOSEnvVarNames.CodeSignWhenStaging, bDefaultNeedsSign ? "1" : "0", /*bQuiet=*/ false);
if (!bool.TryParse(EnvVar, out bNeedsSign))
{
int BoolAsInt;
if (int.TryParse(EnvVar, out BoolAsInt))
{
bNeedsSign = BoolAsInt != 0;
}
else
{
bNeedsSign = bDefaultNeedsSign;
}
}
if (!String.IsNullOrEmpty(Params.BundleName))
{
// Have to sign when a bundle name is specified
bNeedsSign = true;
}
return bNeedsSign;
}
public override void Package(ProjectParams Params, DeploymentContext SC, int WorkingCL)
{
Log("Package {0}", Params.RawProjectPath);
// ensure the ue4game binary exists, if applicable
string FullExePath = CombinePaths(Path.GetDirectoryName(Params.ProjectGameExeFilename), SC.StageExecutables[0] + (UnrealBuildTool.BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac ? ".stub" : ""));
if (!SC.IsCodeBasedProject && !FileExists_NoExceptions(FullExePath))
{
LogError("Failed to find game binary " + FullExePath);
throw new AutomationException(ExitCode.Error_MissingExecutable, "Stage Failed. Could not find binary {0}. You may need to build the UE4 project with your target configuration and platform.", FullExePath);
}
if (SC.StageTargetConfigurations.Count != 1)
{
throw new AutomationException("iOS is currently only able to package one target configuration at a time, but StageTargetConfigurations contained {0} configurations", SC.StageTargetConfigurations.Count);
}
var TargetConfiguration = SC.StageTargetConfigurations[0];
string MobileProvision;
string SigningCertificate;
GetProvisioningData(Params.RawProjectPath, Params.Distribution, out MobileProvision, out SigningCertificate);
//@TODO: We should be able to use this code on both platforms, when the following issues are sorted:
// - Raw executable is unsigned & unstripped (need to investigate adding stripping to IPP)
// - IPP needs to be able to codesign a raw directory
// - IPP needs to be able to take a .app directory instead of a Payload directory when doing RepackageFromStage (which would probably be renamed)
// - Some discrepancy in the loading screen pngs that are getting packaged, which needs to be investigated
// - Code here probably needs to be updated to write 0 byte files as 1 byte (difference with IPP, was required at one point when using Ionic.Zip to prevent issues on device, maybe not needed anymore?)
if (UnrealBuildTool.BuildHostPlatform.Current.Platform == UnrealTargetPlatform.Mac)
{
// copy in all of the artwork and plist
PrepForUATPackageOrDeploy(TargetConfiguration, Params.RawProjectPath,
Params.ShortProjectName,
Path.GetDirectoryName(Params.RawProjectPath.FullName),
CombinePaths(Path.GetDirectoryName(Params.ProjectGameExeFilename), SC.StageExecutables[0]),
CombinePaths(SC.LocalRoot, "Engine"),
Params.Distribution,
"",
false,
true);
// figure out where to pop in the staged files
string AppDirectory = string.Format("{0}/Payload/{1}.app",
Path.GetDirectoryName(Params.ProjectGameExeFilename),
Path.GetFileNameWithoutExtension(Params.ProjectGameExeFilename));
// delete the old cookeddata
InternalUtils.SafeDeleteDirectory(AppDirectory + "/cookeddata", true);
InternalUtils.SafeDeleteFile(AppDirectory + "/ue4commandline.txt", true);
if (!Params.IterativeDeploy)
{
// copy the Staged files to the AppDirectory
string[] StagedFiles = Directory.GetFiles (SC.StageDirectory, "*", SearchOption.AllDirectories);
foreach (string Filename in StagedFiles)
{
string DestFilename = Filename.Replace (SC.StageDirectory, AppDirectory);
Directory.CreateDirectory (Path.GetDirectoryName (DestFilename));
InternalUtils.SafeCopyFile (Filename, DestFilename, true);
}
}
else
{
// copy just the root stage directory files
string[] StagedFiles = Directory.GetFiles (SC.StageDirectory, "*", SearchOption.TopDirectoryOnly);
foreach (string Filename in StagedFiles)
{
string DestFilename = Filename.Replace (SC.StageDirectory, AppDirectory);
Directory.CreateDirectory (Path.GetDirectoryName (DestFilename));
InternalUtils.SafeCopyFile (Filename, DestFilename, true);
}
}
}
bCreatedIPA = false;
bool bNeedsIPA = false;
if (Params.IterativeDeploy)
{
if (Params.Devices.Count != 1)
{
throw new AutomationException("Can only interatively deploy to a single device, but {0} were specified", Params.Devices.Count);
}
String NonUFSManifestPath = SC.GetNonUFSDeploymentDeltaPath(Params.DeviceNames[0]);
// check to determine if we need to update the IPA
if (File.Exists(NonUFSManifestPath))
{
string NonUFSFiles = File.ReadAllText(NonUFSManifestPath);
string[] Lines = NonUFSFiles.Split('\n');
bNeedsIPA = Lines.Length > 0 && !string.IsNullOrWhiteSpace(Lines[0]);
}
}
if (String.IsNullOrEmpty(Params.Provision))
{
Params.Provision = MobileProvision;
}
if (String.IsNullOrEmpty(Params.Certificate))
{
Params.Certificate = SigningCertificate;
}
// Scheme name and configuration for code signing with Xcode project
string SchemeName = Params.IsCodeBasedProject ? Params.RawProjectPath.GetFileNameWithoutExtension() : "UE4";
string SchemeConfiguration = TargetConfiguration.ToString();
if (Params.Client)
{
SchemeConfiguration += " Client";
}
if (UnrealBuildTool.BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac)
{
var ProjectIPA = MakeIPAFileName(TargetConfiguration, Params);
var ProjectStub = Path.GetFullPath(Params.ProjectGameExeFilename);
// package a .ipa from the now staged directory
var IPPExe = CombinePaths(CmdEnv.LocalRoot, "Engine/Binaries/DotNET/IOS/IPhonePackager.exe");
LogLog("ProjectName={0}", Params.ShortProjectName);
LogLog("ProjectStub={0}", ProjectStub);
LogLog("ProjectIPA={0}", ProjectIPA);
LogLog("IPPExe={0}", IPPExe);
bool cookonthefly = Params.CookOnTheFly || Params.SkipCookOnTheFly;
// if we are incremental check to see if we need to even update the IPA
if (!Params.IterativeDeploy || !File.Exists(ProjectIPA) || bNeedsIPA)
{
// delete the .ipa to make sure it was made
DeleteFile(ProjectIPA);
bCreatedIPA = true;
if (IOSExports.UseRPCUtil())
{
string IPPArguments = "RepackageFromStage \"" + (Params.IsCodeBasedProject ? Params.RawProjectPath.FullName : "Engine") + "\"";
IPPArguments += " -config " + TargetConfiguration.ToString();
IPPArguments += " -schemename " + SchemeName + " -schemeconfig \"" + SchemeConfiguration + "\"";
if (TargetConfiguration == UnrealTargetConfiguration.Shipping)
{
IPPArguments += " -compress=best";
}
// Determine if we should sign
bool bNeedToSign = GetCodeSignDesirability(Params);
if (!String.IsNullOrEmpty(Params.BundleName))
{
// Have to sign when a bundle name is specified
bNeedToSign = true;
IPPArguments += " -bundlename " + Params.BundleName;
}
if (bNeedToSign)
{
IPPArguments += " -sign";
if (Params.Distribution)
{
IPPArguments += " -distribution";
}
}
IPPArguments += (cookonthefly ? " -cookonthefly" : "");
IPPArguments += " -stagedir \"" + CombinePaths(Params.BaseStageDirectory, PlatformName) + "\"";
IPPArguments += " -project \"" + Params.RawProjectPath + "\"";
if (Params.IterativeDeploy)
{
IPPArguments += " -iterate";
}
if (!string.IsNullOrEmpty(Params.Provision))
{
IPPArguments += " -provision \"" + Params.Provision + "\"";
}
if (!string.IsNullOrEmpty(Params.Certificate))
{
IPPArguments += " -certificate \"" + Params.Certificate + "\"";
}
if (PlatformName == "TVOS")
{
IPPArguments += " -tvos";
}
RunAndLog(CmdEnv, IPPExe, IPPArguments);
}
else
{
List<string> IPPArguments = new List<string>();
IPPArguments.Add("RepackageFromStage");
IPPArguments.Add(Params.IsCodeBasedProject ? Params.RawProjectPath.FullName : "Engine");
IPPArguments.Add("-config");
IPPArguments.Add(TargetConfiguration.ToString());
IPPArguments.Add("-schemename");
IPPArguments.Add(SchemeName);
IPPArguments.Add("-schemeconfig");
IPPArguments.Add("\"" + SchemeConfiguration + "\"");
if (TargetConfiguration == UnrealTargetConfiguration.Shipping)
{
IPPArguments.Add("-compress=best");
}
// Determine if we should sign
bool bNeedToSign = GetCodeSignDesirability(Params);
if (!String.IsNullOrEmpty(Params.BundleName))
{
// Have to sign when a bundle name is specified
bNeedToSign = true;
IPPArguments.Add("-bundlename");
IPPArguments.Add(Params.BundleName);
}
if (bNeedToSign)
{
IPPArguments.Add("-sign");
}
if (cookonthefly)
{
IPPArguments.Add(" -cookonthefly");
}
IPPArguments.Add(" -stagedir");
IPPArguments.Add(CombinePaths(Params.BaseStageDirectory, "IOS"));
IPPArguments.Add(" -project");
IPPArguments.Add(Params.RawProjectPath.FullName);
if (Params.IterativeDeploy)
{
IPPArguments.Add(" -iterate");
}
if (!string.IsNullOrEmpty(Params.Provision))
{
IPPArguments.Add(" -provision");
IPPArguments.Add(Params.Provision);
}
if (!string.IsNullOrEmpty(Params.Certificate))
{
IPPArguments.Add(" -certificate");
IPPArguments.Add(Params.Certificate);
}
if (RunIPP(IPPArguments.ToArray()) != 0)
{
throw new AutomationException("IPP Failed");
}
}
}
// verify the .ipa exists
if (!FileExists(ProjectIPA))
{
throw new AutomationException(ExitCode.Error_FailedToCreateIPA, "PACKAGE FAILED - {0} was not created", ProjectIPA);
}
if (WorkingCL > 0)
{
// Open files for add or edit
var ExtraFilesToCheckin = new List<string>
{
ProjectIPA
};
// check in the .ipa along with everything else
UE4Build.AddBuildProductsToChangelist(WorkingCL, ExtraFilesToCheckin);
}
//@TODO: This automatically deploys after packaging, useful for testing on PC when iterating on IPP
//Deploy(Params, SC);
}
else
{
// create the ipa
string IPAName = CombinePaths(Path.GetDirectoryName(Params.RawProjectPath.FullName), "Binaries", PlatformName, (Params.Distribution ? "Distro_" : "") + Params.ShortProjectName + (SC.StageTargetConfigurations[0] != UnrealTargetConfiguration.Development ? ("-" + PlatformName + "-" + SC.StageTargetConfigurations[0].ToString()) : "") + ".ipa");
if (!Params.IterativeDeploy || !File.Exists(IPAName) || bNeedsIPA)
{
bCreatedIPA = true;
// code sign the app
CodeSign(Path.GetDirectoryName(Params.ProjectGameExeFilename), Params.IsCodeBasedProject ? Params.ShortProjectName : Path.GetFileNameWithoutExtension(Params.ProjectGameExeFilename), Params.RawProjectPath, SC.StageTargetConfigurations[0], SC.LocalRoot, Params.ShortProjectName, Path.GetDirectoryName(Params.RawProjectPath.FullName), SC.IsCodeBasedProject, Params.Distribution, Params.Provision, Params.Certificate, SchemeName, SchemeConfiguration);
// now generate the ipa
PackageIPA(Path.GetDirectoryName(Params.ProjectGameExeFilename), Params.IsCodeBasedProject ? Params.ShortProjectName : Path.GetFileNameWithoutExtension(Params.ProjectGameExeFilename), Params.ShortProjectName, Path.GetDirectoryName(Params.RawProjectPath.FullName), SC.StageTargetConfigurations[0], Params.Distribution);
}
}
PrintRunTime();
}
private string EnsureXcodeProjectExists(FileReference RawProjectPath, string LocalRoot, string ShortProjectName, string ProjectRoot, bool IsCodeBasedProject, out bool bWasGenerated)
{
// first check for ue4.xcodeproj
bWasGenerated = false;
string RawProjectDir = RawProjectPath.Directory.FullName;
string XcodeProj = RawProjectPath.FullName.Replace(".uproject", "_" + PlatformName + ".xcworkspace");
if (!Directory.Exists(RawProjectDir + "/Source") && !Directory.Exists(RawProjectDir + "/Intermediate/Source"))
{
XcodeProj = CombinePaths(CmdEnv.LocalRoot, "Engine", Path.GetFileName(XcodeProj));
}
Console.WriteLine ("Project: " + XcodeProj);
{
// project.xcodeproj doesn't exist, so generate temp project
string Arguments = "-project=\"" + RawProjectPath + "\"";
Arguments += " -platforms=" + PlatformName + " -game -nointellisense -" + PlatformName + "deployonly -ignorejunk";
// If engine is installed then UBT doesn't need to be built
if (Automation.IsEngineInstalled())
{
// Get the path to UBT
string InstalledUBT = CombinePaths(CmdEnv.LocalRoot, "Engine/Binaries/DotNET/UnrealBuildTool.exe");
Arguments = "-XcodeProjectFile " + Arguments;
RunUBT(CmdEnv, InstalledUBT, Arguments);
}
else
{
string Script = CombinePaths(CmdEnv.LocalRoot, "Engine/Build/BatchFiles/Mac/GenerateProjectFiles.sh");
string CWD = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(Path.GetDirectoryName(Script));
Run(Script, Arguments, null, ERunOptions.Default);
Directory.SetCurrentDirectory(CWD);
}
bWasGenerated = true;
if (!Directory.Exists (XcodeProj))
{
// something very bad happened
throw new AutomationException("iOS couldn't find the appropriate Xcode Project " + XcodeProj);
}
}
return XcodeProj;
}
private void CodeSign(string BaseDirectory, string GameName, FileReference RawProjectPath, UnrealTargetConfiguration TargetConfig, string LocalRoot, string ProjectName, string ProjectDirectory, bool IsCode, bool Distribution = false, string Provision = null, string Certificate = null, string SchemeName = null, string SchemeConfiguration = null)
{
// check for the proper xcodeproject
bool bWasGenerated = false;
string XcodeProj = EnsureXcodeProjectExists (RawProjectPath, LocalRoot, ProjectName, ProjectDirectory, IsCode, out bWasGenerated);
string Arguments = "UBT_NO_POST_DEPLOY=true";
Arguments += " /usr/bin/xcrun xcodebuild build -workspace \"" + XcodeProj + "\"";
Arguments += " -scheme '";
Arguments += SchemeName != null ? SchemeName : GameName;
Arguments += "'";
Arguments += " -configuration \"" + (SchemeConfiguration != null ? SchemeConfiguration : TargetConfig.ToString()) + "\"";
Arguments += " -destination generic/platform=" + (PlatformName == "TVOS" ? "tvOS" : "iOS");
Arguments += " -sdk " + SDKName;
if (!string.IsNullOrEmpty(Certificate))
{
Arguments += " CODE_SIGN_IDENTITY=\"" + Certificate + "\"";
}
else
{
Arguments += " CODE_SIGN_IDENTITY=" + (Distribution ? "\"iPhone Distribution\"" : "\"iPhone Developer\"");
}
if (!string.IsNullOrEmpty(Provision))
{
// read the provision to get the UUID
if (File.Exists(Environment.GetEnvironmentVariable("HOME") + "/Library/MobileDevice/Provisioning Profiles/" + Provision))
{
string UUID = "";
string AllText = File.ReadAllText(Environment.GetEnvironmentVariable("HOME") + "/Library/MobileDevice/Provisioning Profiles/" + Provision);
int idx = AllText.IndexOf("<key>UUID</key>");
if (idx > 0)
{
idx = AllText.IndexOf("<string>", idx);
if (idx > 0)
{
idx += "<string>".Length;
UUID = AllText.Substring(idx, AllText.IndexOf("</string>", idx) - idx);
Arguments += " PROVISIONING_PROFILE_SPECIFIER=" + UUID;
}
}
}
}
IProcessResult Result = Run ("/usr/bin/env", Arguments, null, ERunOptions.Default);
if (bWasGenerated)
{
InternalUtils.SafeDeleteDirectory( XcodeProj, true);
}
if (Result.ExitCode != 0)
{
throw new AutomationException(ExitCode.Error_FailedToCodeSign, "CodeSign Failed");
}
}
private void PackageIPA(string BaseDirectory, string GameName, string ProjectName, string ProjectDirectory, UnrealTargetConfiguration TargetConfig, bool Distribution = false)
{
// create the ipa
string IPAName = CombinePaths(ProjectDirectory, "Binaries", PlatformName, (Distribution ? "Distro_" : "") + ProjectName + (TargetConfig != UnrealTargetConfiguration.Development ? ("-" + PlatformName + "-" + TargetConfig.ToString()) : "") + ".ipa");
// delete the old one
if (File.Exists(IPAName))
{
File.Delete(IPAName);
}
// make the subdirectory if needed
string DestSubdir = Path.GetDirectoryName(IPAName);
if (!Directory.Exists(DestSubdir))
{
Directory.CreateDirectory(DestSubdir);
}
// set up the directories
string ZipWorkingDir = String.Format("Payload/{0}.app/", GameName);
string ZipSourceDir = string.Format("{0}/Payload/{1}.app", BaseDirectory, GameName);
// create the file
using (ZipFile Zip = new ZipFile())
{
// Set encoding to support unicode filenames
Zip.AlternateEncodingUsage = ZipOption.Always;
Zip.AlternateEncoding = Encoding.UTF8;
// set the compression level
if (Distribution)
{
Zip.CompressionLevel = CompressionLevel.BestCompression;
}
// add the entire directory
Zip.AddDirectory(ZipSourceDir, ZipWorkingDir);
// Update permissions to be UNIX-style
// Modify the file attributes of any added file to unix format
foreach (ZipEntry E in Zip.Entries)
{
const byte FileAttributePlatform_NTFS = 0x0A;
const byte FileAttributePlatform_UNIX = 0x03;
const byte FileAttributePlatform_FAT = 0x00;
const int UNIX_FILETYPE_NORMAL_FILE = 0x8000;
//const int UNIX_FILETYPE_SOCKET = 0xC000;
//const int UNIX_FILETYPE_SYMLINK = 0xA000;
//const int UNIX_FILETYPE_BLOCKSPECIAL = 0x6000;
const int UNIX_FILETYPE_DIRECTORY = 0x4000;
//const int UNIX_FILETYPE_CHARSPECIAL = 0x2000;
//const int UNIX_FILETYPE_FIFO = 0x1000;
const int UNIX_EXEC = 1;
const int UNIX_WRITE = 2;
const int UNIX_READ = 4;
int MyPermissions = UNIX_READ | UNIX_WRITE;
int OtherPermissions = UNIX_READ;
int PlatformEncodedBy = (E.VersionMadeBy >> 8) & 0xFF;
int LowerBits = 0;
// Try to preserve read-only if it was set
bool bIsDirectory = E.IsDirectory;
// Check to see if this
bool bIsExecutable = false;
if (Path.GetFileNameWithoutExtension(E.FileName).Equals(GameName, StringComparison.InvariantCultureIgnoreCase))
{
bIsExecutable = true;
}
if (bIsExecutable)
{
// The executable will be encrypted in the final distribution IPA and will compress very poorly, so keeping it
// uncompressed gives a better indicator of IPA size for our distro builds
E.CompressionLevel = CompressionLevel.None;
}
if ((PlatformEncodedBy == FileAttributePlatform_NTFS) || (PlatformEncodedBy == FileAttributePlatform_FAT))
{
FileAttributes OldAttributes = E.Attributes;
//LowerBits = ((int)E.Attributes) & 0xFFFF;
if ((OldAttributes & FileAttributes.Directory) != 0)
{
bIsDirectory = true;
}
// Permissions
if ((OldAttributes & FileAttributes.ReadOnly) != 0)
{
MyPermissions &= ~UNIX_WRITE;
OtherPermissions &= ~UNIX_WRITE;
}
}
if (bIsDirectory || bIsExecutable)
{
MyPermissions |= UNIX_EXEC;
OtherPermissions |= UNIX_EXEC;
}
// Re-jigger the external file attributes to UNIX style if they're not already that way
if (PlatformEncodedBy != FileAttributePlatform_UNIX)
{
int NewAttributes = bIsDirectory ? UNIX_FILETYPE_DIRECTORY : UNIX_FILETYPE_NORMAL_FILE;
NewAttributes |= (MyPermissions << 6);
NewAttributes |= (OtherPermissions << 3);
NewAttributes |= (OtherPermissions << 0);
// Now modify the properties
E.AdjustExternalFileAttributes(FileAttributePlatform_UNIX, (NewAttributes << 16) | LowerBits);
}
}
// Save it out
Zip.Save(IPAName);
}
}
public override void GetFilesToDeployOrStage(ProjectParams Params, DeploymentContext SC)
{
// if (UnrealBuildTool.BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac)
{
// copy the icons/launch screens from the engine
{
string SourcePath = CombinePaths(SC.LocalRoot, "Engine", "Build", "IOS", "Resources", "Graphics");
SC.StageFiles(StagedFileType.NonUFS, SourcePath, "*.png", false, null, "", true, false);
}
// copy any additional framework assets that will be needed at runtime
{
string SourcePath = CombinePaths( ( SC.IsCodeBasedProject ? SC.ProjectRoot : SC.LocalRoot + "\\Engine" ), "Intermediate", "IOS", "FrameworkAssets" );
if ( Directory.Exists( SourcePath ) )
{
SC.StageFiles( StagedFileType.NonUFS, SourcePath, "*.*", true, null, "", true, false );
}
}
// copy the icons/launch screens from the game (may stomp the engine copies)
{
string SourcePath = CombinePaths(SC.ProjectRoot, "Build", "IOS", "Resources", "Graphics");
SC.StageFiles(StagedFileType.NonUFS, SourcePath, "*.png", false, null, "", true, false);
}
// copy the plist (only if code signing, as it's protected by the code sign blob in the executable and can't be modified independently)
if (GetCodeSignDesirability(Params))
{
string SourcePath = CombinePaths((SC.IsCodeBasedProject ? SC.ProjectRoot : SC.LocalRoot + "/Engine"), "Intermediate", PlatformName);
string TargetPListFile = Path.Combine(SourcePath, (SC.IsCodeBasedProject ? SC.ShortProjectName : "UE4Game") + "-Info.plist");
// if (!File.Exists(TargetPListFile))
{
// ensure the plist, entitlements, and provision files are properly copied
Console.WriteLine("CookPlat {0}, this {1}", GetCookPlatform(false, false), ToString());
if (!SC.IsCodeBasedProject)
{
UnrealBuildTool.PlatformExports.SetRemoteIniPath(SC.ProjectRoot);
}
if (SC.StageTargetConfigurations.Count != 1)
{
throw new AutomationException("iOS is currently only able to package one target configuration at a time, but StageTargetConfigurations contained {0} configurations", SC.StageTargetConfigurations.Count);
}
var TargetConfiguration = SC.StageTargetConfigurations[0];
DeployGeneratePList(
SC.RawProjectPath,
TargetConfiguration,
(SC.IsCodeBasedProject ? SC.ProjectRoot : SC.LocalRoot + "/Engine"),
!SC.IsCodeBasedProject,
(SC.IsCodeBasedProject ? SC.ShortProjectName : "UE4Game"),
SC.ShortProjectName, SC.LocalRoot + "/Engine",
(SC.IsCodeBasedProject ? SC.ProjectRoot : SC.LocalRoot + "/Engine") + "/Binaries/" + PlatformName + "/Payload/" + (SC.IsCodeBasedProject ? SC.ShortProjectName : "UE4Game") + ".app");
}
SC.StageFiles(StagedFileType.NonUFS, SourcePath, Path.GetFileName(TargetPListFile), false, null, "", false, false, "Info.plist");
}
}
{
SC.StageFiles(StagedFileType.NonUFS, CombinePaths(SC.LocalRoot, "Engine/Content/Movies"), "*", true, new string[] { "*.uasset", "*.umap" }, CombinePaths(SC.RelativeProjectRootForStage, "Engine/Content/Movies"), true, true, null, true, true, SC.StageTargetPlatform.DeployLowerCaseFilenames(true));
SC.StageFiles(StagedFileType.NonUFS, CombinePaths(SC.ProjectRoot, "Content/Movies"), "*", true, new string[] { "*.uasset", "*.umap" }, CombinePaths(SC.RelativeProjectRootForStage, "Content/Movies"), true, true, null, true, true, SC.StageTargetPlatform.DeployLowerCaseFilenames(true));
}
}
public override void GetFilesToArchive(ProjectParams Params, DeploymentContext SC)
{
if (SC.StageTargetConfigurations.Count != 1)
{
throw new AutomationException("iOS is currently only able to package one target configuration at a time, but StageTargetConfigurations contained {0} configurations", SC.StageTargetConfigurations.Count);
}
var TargetConfiguration = SC.StageTargetConfigurations[0];
var ProjectIPA = MakeIPAFileName( TargetConfiguration, Params );
// verify the .ipa exists
if (!FileExists(ProjectIPA))
{
throw new AutomationException("ARCHIVE FAILED - {0} was not found", ProjectIPA);
}
ConfigHierarchy PlatformGameConfig;
bool bXCArchive = false;
if (Params.EngineConfigs.TryGetValue(SC.StageTargetPlatform.PlatformType, out PlatformGameConfig))
{
PlatformGameConfig.GetBool("/Script/IOSRuntimeSettings.IOSRuntimeSettings", "bGenerateXCArchive", out bXCArchive);
}
if (bXCArchive && Utils.IsRunningOnMono)
{
// Always put the archive in the current user's Library/Developer/Xcode/Archives path
WindowsIdentity id = WindowsIdentity.GetCurrent();
string ArchivePath = "/Users/" + id.Name + "/Library/Developer/Xcode/Archives";
if (!DirectoryExists(ArchivePath))
{
CreateDirectory(ArchivePath);
}
Console.WriteLine("Generating xc archive package in " + ArchivePath);
string ArchiveName = Path.Combine(ArchivePath, Path.GetFileNameWithoutExtension(ProjectIPA) + ".xcarchive");
if (!DirectoryExists(ArchiveName))
{
CreateDirectory(ArchiveName);
}
DeleteDirectoryContents(ArchiveName);
// create the Products archive folder
CreateDirectory(Path.Combine(ArchiveName, "Products", "Applications"));
// copy in the application
string AppName = Path.GetFileNameWithoutExtension(ProjectIPA) + ".app";
using (ZipFile Zip = new ZipFile(ProjectIPA))
{
Zip.ExtractAll(ArchivePath, ExtractExistingFileAction.OverwriteSilently);
List<string> Dirs = new List<string>(Directory.EnumerateDirectories(Path.Combine(ArchivePath, "Payload"), "*.app"));
AppName = Dirs[0].Substring(Dirs[0].LastIndexOf(UnrealBuildTool.BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac ? "\\" : "/") + 1);
CopyDirectory_NoExceptions(Path.Combine(ArchivePath, "Payload", AppName), Path.Combine(ArchiveName, "Products", "Applications", AppName));
}
// copy in the dSYM if found
var ProjectExe = MakeExeFileName( TargetConfiguration, Params );
string dSYMName = (SC.IsCodeBasedProject ? Path.GetFileNameWithoutExtension(ProjectExe) : "UE4Game") + ".dSYM";
string dSYMSrcPath = Path.Combine(SC.ProjectBinariesFolder, dSYMName);
if(DirectoryExists(new string[] { dSYMSrcPath } ))
{
// Create the dsyms archive folder
CreateDirectory(Path.Combine(ArchiveName, "dSYMs"));
string dSYMDstPath = Path.Combine(ArchiveName, "dSYMs", dSYMName);
// /Volumes/MacOSDrive1/pfEpicWorkspace/Dev-Platform/Samples/Sandbox/PlatformShowcase/Binaries/IOS/PlatformShowcase.dSYM/Contents/Resources/DWARF/PlatformShowcase
CopyFile_NoExceptions(Path.Combine(dSYMSrcPath, "Contents", "Resources", "DWARF", SC.IsCodeBasedProject ? Path.GetFileNameWithoutExtension(ProjectExe) : "UE4Game"), dSYMDstPath);
}
else if (File.Exists(dSYMSrcPath))
{
// Create the dsyms archive folder
CreateDirectory(Path.Combine(ArchiveName, "dSYMs"));
string dSYMDstPath = Path.Combine(ArchiveName, "dSYMs", dSYMName);
CopyFile_NoExceptions(dSYMSrcPath, dSYMDstPath);
}
// copy in the bitcode symbol maps if found
string[] bcmapfiles = Directory.GetFiles(SC.ProjectBinariesFolder, "*.bcsymbolmap");
if(bcmapfiles.Length > 0)
{
// Create the dsyms archive folder
CreateDirectory(Path.Combine(ArchiveName, "BCSymbolMaps"));
foreach (string symbolSrcFilePath in bcmapfiles)
{
string symbolLeafFileName = Path.GetFileName(symbolSrcFilePath);
string bcDstFilePath = Path.Combine(ArchiveName, "BCSymbolMaps", symbolLeafFileName);
CopyFile_NoExceptions(symbolSrcFilePath, bcDstFilePath);
}
}
// get the settings from the app plist file
string AppPlist = Path.Combine(ArchiveName, "Products", "Applications", AppName, "Info.plist");
string OldPListData = File.Exists(AppPlist) ? File.ReadAllText(AppPlist) : "";
// bundle identifier
int index = OldPListData.IndexOf("CFBundleIdentifier");
index = OldPListData.IndexOf("<string>", index) + 8;
int length = OldPListData.IndexOf("</string>", index) - index;
string BundleIdentifier = OldPListData.Substring(index, length);
// short version
index = OldPListData.IndexOf("CFBundleShortVersionString");
index = OldPListData.IndexOf("<string>", index) + 8;
length = OldPListData.IndexOf("</string>", index) - index;
string BundleShortVersion = OldPListData.Substring(index, length);
// bundle version
index = OldPListData.IndexOf("CFBundleVersion");
index = OldPListData.IndexOf("<string>", index) + 8;
length = OldPListData.IndexOf("</string>", index) - index;
string BundleVersion = OldPListData.Substring(index, length);
// date we made this
const string Iso8601DateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ";
string TimeStamp = DateTime.UtcNow.ToString(Iso8601DateTimeFormat);
// create the archive plist
StringBuilder Text = new StringBuilder();
Text.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
Text.AppendLine("<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">");
Text.AppendLine("<plist version=\"1.0\">");
Text.AppendLine("<dict>");
Text.AppendLine("\t<key>ApplicationProperties</key>");
Text.AppendLine("\t<dict>");
Text.AppendLine("\t\t<key>ApplicationPath</key>");
Text.AppendLine("\t\t<string>Applications/" + AppName + "</string>");
Text.AppendLine("\t\t<key>CFBundleIdentifier</key>");
Text.AppendLine(string.Format("\t\t<string>{0}</string>", BundleIdentifier));
Text.AppendLine("\t\t<key>CFBundleShortVersionString</key>");
Text.AppendLine(string.Format("\t\t<string>{0}</string>", BundleShortVersion));
Text.AppendLine("\t\t<key>CFBundleVersion</key>");
Text.AppendLine(string.Format("\t\t<string>{0}</string>", BundleVersion));
Text.AppendLine("\t\t<key>SigningIdentity</key>");
Text.AppendLine(string.Format("\t\t<string>{0}</string>", Params.Certificate));
Text.AppendLine("\t</dict>");
Text.AppendLine("\t<key>ArchiveVersion</key>");
Text.AppendLine("\t<integer>2</integer>");
Text.AppendLine("\t<key>CreationDate</key>");
Text.AppendLine(string.Format("\t<date>{0}</date>", TimeStamp));
Text.AppendLine("\t<key>DefaultToolchainInfo</key>");
Text.AppendLine("\t<dict>");
Text.AppendLine("\t\t<key>DisplayName</key>");
Text.AppendLine("\t\t<string>Xcode 7.3 Default</string>");
Text.AppendLine("\t\t<key>Identifier</key>");
Text.AppendLine("\t\t<string>com.apple.dt.toolchain.XcodeDefault</string>");
Text.AppendLine("\t</dict>");
Text.AppendLine("\t<key>Name</key>");
Text.AppendLine(string.Format("\t<string>{0}</string>", SC.ShortProjectName));
Text.AppendLine("\t<key>SchemeName</key>");
Text.AppendLine(string.Format("\t<string>{0}</string>", SC.ShortProjectName));
Text.AppendLine("</dict>");
Text.AppendLine("</plist>");
File.WriteAllText(Path.Combine(ArchiveName, "Info.plist"), Text.ToString());
}
else if (bXCArchive && !Utils.IsRunningOnMono)
{
LogWarning("Can not produce an XCArchive on windows");
}
SC.ArchiveFiles(Path.GetDirectoryName(ProjectIPA), Path.GetFileName(ProjectIPA));
}
public override bool RetrieveDeployedManifests(ProjectParams Params, DeploymentContext SC, string DeviceName, out List<string> UFSManifests, out List<string> NonUFSManifests)
{
if (Params.Devices.Count != 1)
{
throw new AutomationException("Can only retrieve deployed manifests from a single device, but {0} were specified", Params.Devices.Count);
}
bool Result = true;
UFSManifests = new List<string>();
NonUFSManifests = new List<string>();
var DeployServer = CombinePaths(CmdEnv.LocalRoot, "Engine/Binaries/DotNET/IOS/DeploymentServer.exe");
try
{
var TargetConfiguration = SC.StageTargetConfigurations[0];
string BundleIdentifier = "";
if (File.Exists(Params.BaseStageDirectory + "/" + PlatformName + "/Info.plist"))
{
string Contents = File.ReadAllText(SC.StageDirectory + "/Info.plist");
int Pos = Contents.IndexOf("CFBundleIdentifier");
Pos = Contents.IndexOf("<string>", Pos) + 8;
int EndPos = Contents.IndexOf("</string>", Pos);
BundleIdentifier = Contents.Substring(Pos, EndPos - Pos);
}
RunAndLog(CmdEnv, DeployServer, "Backup -file \"" + CombinePaths(Params.BaseStageDirectory, PlatformName, SC.UFSDeployedManifestFileName) + "\" -file \"" + CombinePaths(Params.BaseStageDirectory, PlatformName, SC.NonUFSDeployedManifestFileName) + "\"" + (String.IsNullOrEmpty(Params.DeviceNames[0]) ? "" : " -device " + Params.DeviceNames[0]) + " -bundle " + BundleIdentifier);
string[] ManifestFiles = Directory.GetFiles(CombinePaths(Params.BaseStageDirectory, PlatformName), "*_Manifest_UFS*.txt");
UFSManifests.AddRange(ManifestFiles);
ManifestFiles = Directory.GetFiles(CombinePaths(Params.BaseStageDirectory, PlatformName), "*_Manifest_NonUFS*.txt");
NonUFSManifests.AddRange(ManifestFiles);
}
catch (System.Exception)
{
// delete any files that did get copied
string[] Manifests = Directory.GetFiles(CombinePaths(Params.BaseStageDirectory, PlatformName), "*_Manifest_*.txt");
foreach (string Manifest in Manifests)
{
File.Delete(Manifest);
}
Result = false;
}
return Result;
}
public override void Deploy(ProjectParams Params, DeploymentContext SC)
{
if (Params.Devices.Count != 1)
{
throw new AutomationException("Can only deploy to a single specified device, but {0} were specified", Params.Devices.Count);
}
if (SC.StageTargetConfigurations.Count != 1)
{
throw new AutomationException ("iOS is currently only able to package one target configuration at a time, but StageTargetConfigurations contained {0} configurations", SC.StageTargetConfigurations.Count);
}
if (Params.Distribution)
{
throw new AutomationException("iOS cannot deploy a package made for distribution.");
}
var TargetConfiguration = SC.StageTargetConfigurations[0];
var ProjectIPA = MakeIPAFileName(TargetConfiguration, Params);
var StagedIPA = SC.StageDirectory + "\\" + Path.GetFileName(ProjectIPA);
// verify the .ipa exists
if (!FileExists(StagedIPA))
{
StagedIPA = ProjectIPA;
if(!FileExists(StagedIPA))
{
throw new AutomationException("DEPLOY FAILED - {0} was not found", ProjectIPA);
}
}
// if iterative deploy, determine the file delta
string BundleIdentifier = "";
bool bNeedsIPA = true;
if (Params.IterativeDeploy)
{
if (File.Exists(Params.BaseStageDirectory + "/" + PlatformName + "/Info.plist"))
{
string Contents = File.ReadAllText(SC.StageDirectory + "/Info.plist");
int Pos = Contents.IndexOf("CFBundleIdentifier");
Pos = Contents.IndexOf("<string>", Pos) + 8;
int EndPos = Contents.IndexOf("</string>", Pos);
BundleIdentifier = Contents.Substring(Pos, EndPos - Pos);
}
// check to determine if we need to update the IPA
String NonUFSManifestPath = SC.GetNonUFSDeploymentDeltaPath(Params.DeviceNames[0]);
if (File.Exists(NonUFSManifestPath))
{
string NonUFSFiles = File.ReadAllText(NonUFSManifestPath);
string[] Lines = NonUFSFiles.Split('\n');
bNeedsIPA = Lines.Length > 0 && !string.IsNullOrWhiteSpace(Lines[0]);
}
}
// Add a commandline for this deploy, if the config allows it.
string AdditionalCommandline = (Params.FileServer || Params.CookOnTheFly) ? "" : (" -additionalcommandline " + "\"" + Params.RunCommandline + "\"");
// deploy the .ipa
var DeployServer = CombinePaths(CmdEnv.LocalRoot, "Engine/Binaries/DotNET/IOS/DeploymentServer.exe");
// check for it in the stage directory
string CurrentDir = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(CombinePaths(CmdEnv.LocalRoot, "Engine/Binaries/DotNET/IOS/"));
if (!Params.IterativeDeploy || bCreatedIPA || bNeedsIPA)
{
RunAndLog(CmdEnv, DeployServer, "Install -ipa \"" + Path.GetFullPath(StagedIPA) + "\"" + (String.IsNullOrEmpty(Params.DeviceNames[0]) ? "" : " -device " + Params.DeviceNames[0]) + AdditionalCommandline);
}
if (Params.IterativeDeploy)
{
// push over the changed files
RunAndLog(CmdEnv, DeployServer, "Deploy -manifest \"" + CombinePaths(Params.BaseStageDirectory, PlatformName, DeploymentContext.UFSDeployDeltaFileName + (Params.Devices.Count == 0 ? "" : Params.DeviceNames[0])) + "\"" + (Params.Devices.Count == 0 ? "" : " -device " + Params.DeviceNames[0]) + AdditionalCommandline + " -bundle " + BundleIdentifier);
}
Directory.SetCurrentDirectory (CurrentDir);
PrintRunTime();
}
public override string GetCookPlatform(bool bDedicatedServer, bool bIsClientOnly)
{
return "IOS";
}
public override bool DeployPakInternalLowerCaseFilenames()
{
return false;
}
public override bool DeployLowerCaseFilenames(bool bUFSFile)
{
// we shouldn't modify the case on files like Info.plist or the icons
return bUFSFile;
}
public override string LocalPathToTargetPath(string LocalPath, string LocalRoot)
{
return LocalPath.Replace("\\", "/").Replace(LocalRoot, "../../..");
}
public override bool IsSupported { get { return true; } }
public override bool LaunchViaUFE { get { return UnrealBuildTool.BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac; } }
public override bool UseAbsLog
{
get
{
return !LaunchViaUFE;
}
}
public override string Remap(string Dest)
{
return "cookeddata/" + Dest;
}
public override List<string> GetDebugFileExtentions()
{
return new List<string> { ".dsym" };
}
// void MobileDeviceConnected(object sender, ConnectEventArgs args)
// {
// }
//
// void MobileDeviceDisconnected(object sender, ConnectEventArgs args)
// {
// }
public override IProcessResult RunClient(ERunOptions ClientRunFlags, string ClientApp, string ClientCmdLine, ProjectParams Params)
{
if (UnrealBuildTool.BuildHostPlatform.Current.Platform == UnrealTargetPlatform.Mac)
{
if (Params.Devices.Count != 1)
{
throw new AutomationException("Can only run on a single specified device, but {0} were specified", Params.Devices.Count);
}
// This code only cares about connected devices so just call the run loop a few times to get the existing connected devices
// MobileDeviceInstanceManager.Initialize(MobileDeviceConnected, MobileDeviceDisconnected);
// for(int i = 0; i < 4; ++i)
// {
// System.Threading.Thread.Sleep(1);
// CoreFoundationRunLoop.RunLoopRunInMode(CoreFoundationRunLoop.kCFRunLoopDefaultMode(), 0.25, 0);
// }
//
/* string AppDirectory = string.Format("{0}/Payload/{1}.app",
Path.GetDirectoryName(Params.ProjectGameExeFilename),
Path.GetFileNameWithoutExtension(Params.ProjectGameExeFilename));
string GameName = Path.GetFileNameWithoutExtension (ClientApp);
if (GameName.Contains ("-IOS-"))
{
GameName = GameName.Substring (0, GameName.IndexOf ("-IOS-"));
}
string GameApp = AppDirectory + "/" + GameName;
bWasGenerated = false;
XcodeProj = EnsureXcodeProjectExists (Params.RawProjectPath, CmdEnv.LocalRoot, Params.ShortProjectName, GetDirectoryName(Params.RawProjectPath), Params.IsCodeBasedProject, out bWasGenerated);
string Arguments = "UBT_NO_POST_DEPLOY=true /usr/bin/xcrun xcodebuild test -project \"" + XcodeProj + "\"";
Arguments += " -scheme '";
Arguments += GameName;
Arguments += " - iOS'";
Arguments += " -configuration " + Params.ClientConfigsToBuild [0].ToString();
Arguments += " -destination 'platform=iOS,id=" + Params.Device.Substring(Params.Device.IndexOf("@")+1) + "'";
Arguments += " TEST_HOST=\"";
Arguments += GameApp;
Arguments += "\" BUNDLE_LOADER=\"";
Arguments += GameApp + "\"";*/
string BundleIdentifier = "";
if (File.Exists(Params.BaseStageDirectory + "/"+ PlatformName + "/Info.plist"))
{
string Contents = File.ReadAllText(Params.BaseStageDirectory + "/" + PlatformName + "/Info.plist");
int Pos = Contents.IndexOf("CFBundleIdentifier");
Pos = Contents.IndexOf("<string>", Pos) + 8;
int EndPos = Contents.IndexOf("</string>", Pos);
BundleIdentifier = Contents.Substring(Pos, EndPos - Pos);
}
string Arguments = "/usr/bin/instruments";
Arguments += " -w '" + Params.DeviceNames[0] + "'";
Arguments += " -t 'Activity Monitor'";
Arguments += " -D \"" + Params.BaseStageDirectory + "/" + PlatformName + "/launch.trace\"";
Arguments += " '" + BundleIdentifier + "'";
IProcessResult ClientProcess = Run ("/usr/bin/env", Arguments, null, ClientRunFlags | ERunOptions.NoWaitForExit);
return new IOSClientProcess(ClientProcess, Params.DeviceNames[0]);
}
else
{
IProcessResult Result = new ProcessResult("DummyApp", null, false, null);
Result.ExitCode = 0;
return Result;
}
}
public override void PostRunClient(IProcessResult Result, ProjectParams Params)
{
if (UnrealBuildTool.BuildHostPlatform.Current.Platform == UnrealTargetPlatform.Mac)
{
string LaunchTracePath = Params.BaseStageDirectory + "/" + PlatformName + "/launch.trace";
Console.WriteLine ("Deleting " + LaunchTracePath);
if (Directory.Exists(LaunchTracePath))
{
Directory.Delete (LaunchTracePath, true);
}
switch (Result.ExitCode)
{
case 253:
throw new AutomationException(ExitCode.Error_DeviceNotSetupForDevelopment, "Launch Failure");
case 255:
throw new AutomationException(ExitCode.Error_DeviceOSNewerThanSDK, "Launch Failure");
}
}
}
private static int GetChunkCount(ProjectParams Params, DeploymentContext SC)
{
var ChunkListFilename = GetChunkPakManifestListFilename(Params, SC);
var ChunkArray = ReadAllLines(ChunkListFilename);
return ChunkArray.Length;
}
private static string GetChunkPakManifestListFilename(ProjectParams Params, DeploymentContext SC)
{
return CombinePaths(GetTmpPackagingPath(Params, SC), "pakchunklist.txt");
}
private static string GetTmpPackagingPath(ProjectParams Params, DeploymentContext SC)
{
return CombinePaths(Path.GetDirectoryName(Params.RawProjectPath.FullName), "Saved", "TmpPackaging", SC.StageTargetPlatform.GetCookPlatform(SC.DedicatedServer, false));
}
private static StringBuilder AppendKeyValue(StringBuilder Text, string Key, object Value, int Level)
{
// create indent level
string Indent = "";
for (int i = 0; i < Level; ++i)
{
Indent += "\t";
}
// output key if we have one
if (Key != null)
{
Text.AppendLine (Indent + "<key>" + Key + "</key>");
}
// output value
if (Value is Array)
{
Text.AppendLine (Indent + "<array>");
Array ValArray = Value as Array;
foreach (var Item in ValArray)
{
AppendKeyValue (Text, null, Item, Level + 1);
}
Text.AppendLine (Indent + "</array>");
}
else if (Value is Dictionary<string, object>)
{
Text.AppendLine (Indent + "<dict>");
Dictionary<string,object> ValDict = Value as Dictionary<string, object>;
foreach (var Item in ValDict)
{
AppendKeyValue (Text, Item.Key, Item.Value, Level + 1);
}
Text.AppendLine (Indent + "</dict>");
}
else if (Value is string)
{
Text.AppendLine (Indent + "<string>" + Value + "</string>");
}
else if (Value is bool)
{
if ((bool)Value == true)
{
Text.AppendLine (Indent + "<true/>");
}
else
{
Text.AppendLine (Indent + "<false/>");
}
}
else
{
Console.WriteLine ("PLIST: Unknown array item type");
}
return Text;
}
private static void GeneratePlist(Dictionary<string, object> KeyValues, string PlistFile)
{
// generate the plist file
StringBuilder Text = new StringBuilder();
// boiler plate top
Text.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
Text.AppendLine("<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">");
Text.AppendLine("<plist version=\"1.0\">");
Text.AppendLine("<dict>");
foreach (var KeyValue in KeyValues)
{
AppendKeyValue(Text, KeyValue.Key, KeyValue.Value, 1);
}
Text.AppendLine("</dict>");
Text.AppendLine("</plist>");
// write the file out
if (!Directory.Exists(Path.GetDirectoryName(PlistFile)))
{
Directory.CreateDirectory(Path.GetDirectoryName(PlistFile));
}
File.WriteAllText(PlistFile, Text.ToString());
}
private static void GenerateAssetPlist(string BundleIdentifier, string[] Tags, string AssetDir)
{
Dictionary<string, object> KeyValues = new Dictionary<string, object> ();
KeyValues.Add ("CFBundleIdentifier", BundleIdentifier);
KeyValues.Add ("Tags", Tags);
GeneratePlist(KeyValues, CombinePaths(AssetDir, "Info.plist"));
}
private static void GenerateAssetPackManifestPlist(KeyValuePair<string, string>[] ChunkData, string AssetDir)
{
Dictionary<string, object>[] Resources = new Dictionary<string, object>[ChunkData.Length];
for (int i = 0; i < ChunkData.Length; ++i)
{
Dictionary<string, object> Data = new Dictionary<string, object> ();
Data.Add ("URL", CombinePaths ("OnDemandResources", ChunkData[i].Value));
Data.Add ("bundleKey", ChunkData [i].Key);
Data.Add ("isStreamable", false);
Resources [i] = Data;
}
Dictionary<string, object> KeyValues = new Dictionary<string, object> ();
KeyValues.Add ("resources", Resources);
GeneratePlist(KeyValues, CombinePaths(AssetDir, "AssetPackManifest.plist"));
}
private static void GenerateOnDemandResourcesPlist(KeyValuePair<string, string>[] ChunkData, string AssetDir)
{
Dictionary<string, object> RequestTags = new Dictionary<string, object> ();
Dictionary<string, object> AssetPacks = new Dictionary<string, object> ();
Dictionary<string, object> Requests = new Dictionary<string, object> ();
for (int i = 0; i < ChunkData.Length; ++i)
{
string ChunkName = "Chunk" + (i + 1).ToString ();
RequestTags.Add (ChunkName, new string[] { ChunkData [i].Key });
AssetPacks.Add (ChunkData [i].Key, new string[] { ("pak" + ChunkName + "-ios.pak").ToLowerInvariant () });
Dictionary<string, object> Packs = new Dictionary<string, object> ();
Packs.Add ("NSAssetPacks", new string[] { ChunkData [i].Key });
Requests.Add (ChunkName, Packs);
}
Dictionary<string, object> KeyValues = new Dictionary<string, object> ();
KeyValues.Add ("NSBundleRequestTags", RequestTags);
KeyValues.Add ("NSBundleResourceRequestAssetPacks", AssetPacks);
KeyValues.Add ("NSBundleResourceRequestTags", Requests);
GeneratePlist(KeyValues, CombinePaths(AssetDir, "OnDemandResources.plist"));
}
public override void PostStagingFileCopy(ProjectParams Params, DeploymentContext SC)
{
if (Params.CreateChunkInstall)
{
// get the bundle identifier
string BundleIdentifier = "";
if (File.Exists(Params.BaseStageDirectory + "/" + PlatformName + "/Info.plist"))
{
string Contents = File.ReadAllText(SC.StageDirectory + "/Info.plist");
int Pos = Contents.IndexOf("CFBundleIdentifier");
Pos = Contents.IndexOf("<string>", Pos) + 8;
int EndPos = Contents.IndexOf("</string>", Pos);
BundleIdentifier = Contents.Substring(Pos, EndPos - Pos);
}
// generate the ODR resources
// create the ODR directory
string DestSubdir = SC.StageDirectory + "/OnDemandResources";
if (!Directory.Exists(DestSubdir))
{
Directory.CreateDirectory(DestSubdir);
}
// read the chunk list and generate the data
var ChunkCount = GetChunkCount(Params, SC);
var ChunkData = new KeyValuePair<string, string>[ChunkCount - 1];
for (int i = 1; i < ChunkCount; ++i)
{
// chunk name
string ChunkName = "Chunk" + i.ToString ();
// asset name
string AssetPack = BundleIdentifier + ".Chunk" + i.ToString () + ".assetpack";
// bundle key
byte[] bytes = new byte[ChunkName.Length * sizeof(char)];
System.Buffer.BlockCopy(ChunkName.ToCharArray(), 0, bytes, 0, bytes.Length);
string BundleKey = BundleIdentifier + ".asset-pack-" + BitConverter.ToString(System.Security.Cryptography.MD5.Create().ComputeHash(bytes)).Replace("-", string.Empty);
// add to chunk data
ChunkData[i-1] = new KeyValuePair<string, string>(BundleKey, AssetPack);
// create the sub directory
string AssetDir = CombinePaths (DestSubdir, AssetPack);
if (!Directory.Exists(AssetDir))
{
Directory.CreateDirectory(AssetDir);
}
// generate the Info.plist for each ODR bundle (each chunk for install past 0)
GenerateAssetPlist (BundleKey, new string[] { ChunkName }, AssetDir);
// copy the files to the OnDemandResources directory
string PakName = "pakchunk" + i.ToString ();
string FileName = PakName + "-" + PlatformName.ToLower() + ".pak";
string P4Change = "UnknownCL";
string P4Branch = "UnknownBranch";
if (CommandUtils.P4Enabled)
{
P4Change = CommandUtils.P4Env.ChangelistString;
P4Branch = CommandUtils.P4Env.BuildRootEscaped;
}
string ChunkInstallBasePath = CombinePaths(SC.ProjectRoot, "ChunkInstall", SC.FinalCookPlatform);
string RawDataPath = CombinePaths(ChunkInstallBasePath, P4Branch + "-CL-" + P4Change, PakName);
string RawDataPakPath = CombinePaths(RawDataPath, PakName + "-" + SC.FinalCookPlatform + ".pak");
string DestFile = CombinePaths (AssetDir, FileName);
CopyFile (RawDataPakPath, DestFile);
}
// generate the AssetPackManifest.plist
GenerateAssetPackManifestPlist (ChunkData, SC.StageDirectory);
// generate the OnDemandResources.plist
GenerateOnDemandResourcesPlist (ChunkData, SC.StageDirectory);
}
}
public override bool StageMovies
{
get { return false; }
}
public override bool RequiresPackageToDeploy
{
get { return true; }
}
public override List<string> GetFilesForCRCCheck()
{
List<string> FileList = base.GetFilesForCRCCheck();
FileList.Add("Info.plist");
return FileList;
}
public override bool SupportsMultiDeviceDeploy
{
get
{
return true;
}
}
public override void StripSymbols(string SourceFileName, string TargetFileName)
{
IOSExports.StripSymbols(PlatformType, SourceFileName, TargetFileName);
}
#region Hooks
public override void PreBuildAgenda(UE4Build Build, UE4Build.BuildAgenda Agenda)
{
if (UnrealBuildTool.BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac && !Automation.IsEngineInstalled())
{
Agenda.DotNetProjects.Add(@"Engine\Source\Programs\IOS\MobileDeviceInterface\MobileDeviceInterface.csproj");
Agenda.DotNetProjects.Add(@"Engine\Source\Programs\IOS\iPhonePackager\iPhonePackager.csproj");
Agenda.DotNetProjects.Add(@"Engine\Source\Programs\IOS\DeploymentServer\DeploymentServer.csproj");
}
}
#endregion
}