using System;
using System.Threading;
using Cysharp.Threading.Tasks;
using HotPatch;
using UnityEngine;
using UnityEngine.SceneManagement;
public sealed class LaunchApp
{
readonly Scene launchScene;
readonly ILaunchView view;
readonly ILaunchResources resources;
readonly CancellationToken cancellationToken;
public bool IsRunning { get; private set; }
public bool IsResourcesReady { get; private set; }
public bool IsCompleted { get; private set; }
public LaunchApp(Scene launchScene, ILaunchView view, ILaunchResources resources, CancellationToken cancellationToken)
{
this.launchScene = launchScene;
this.view = view ?? throw new ArgumentNullException(nameof(view));
this.resources = resources ?? throw new ArgumentNullException(nameof(resources));
this.cancellationToken = cancellationToken;
}
bool CanRun => !cancellationToken.IsCancellationRequested && view.IsAvailable;
/// Updates resources, then invokes onUpdated or opens the game scene when no callback is supplied.
public async UniTask RunAsync(Action onUpdated = null)
{
if (IsRunning || IsCompleted || !CanRun) return;
IsRunning = true;
bool showRetryDialog = false;
try
{
HotPatchLog.Info("launch_start scene=" + resources.GameSceneName);
if (!IsResourcesReady)
{
view.ResetProgress();
Report("Checking version", 0);
await resources.LoadAsync(Report, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
IsResourcesReady = true;
}
if (onUpdated != null) Report("Update complete", 1);
}
catch (Exception exception)
{
showRetryDialog = HandleFailure(exception);
if (!showRetryDialog) return;
}
finally
{
IsRunning = false;
}
if (showRetryDialog)
{
ShowRetryDialog(() => RunAsync(onUpdated).Forget(Debug.LogException));
return;
}
if (!CanRun) return;
// Release the update guard before invoking user code so the callback can open the scene.
if (onUpdated != null) onUpdated();
else await OpenSceneAsync();
}
/// Opens the game scene using resources prepared by a successful RunAsync callback.
public async UniTask OpenSceneAsync()
{
if (IsRunning || IsCompleted || !CanRun) return;
if (!IsResourcesReady)
throw new InvalidOperationException("Resources are not ready. Wait for RunAsync to finish updating before opening the game scene.");
IsRunning = true;
bool showRetryDialog = false;
Scene gameScene = default;
try
{
var sceneName = resources.GameSceneName;
if (SceneManager.GetSceneByName(sceneName).isLoaded)
throw new InvalidOperationException(sceneName + " is already open. Restart the app.");
HotPatchLog.Info("scene_load_start scene=" + sceneName + " version=" + resources.LoadedVersion);
Report("Loading resources", .95f);
var scenePath = resources.LoadedScenePath;
AsyncOperation operation;
#if UNITY_EDITOR
if (resources.UseEditorSceneLoading)
operation = UnityEditor.SceneManagement.EditorSceneManager.LoadSceneAsyncInPlayMode(scenePath, new LoadSceneParameters(LoadSceneMode.Additive));
else
#endif
operation = SceneManager.LoadSceneAsync(scenePath, LoadSceneMode.Additive);
if (operation == null) throw new InvalidOperationException("Unable to open game scene: " + sceneName);
await operation.ToUniTask(progress: Progress.Create(value => Report("Loading resources", .95f + .04f * value)));
gameScene = SceneManager.GetSceneByPath(scenePath);
cancellationToken.ThrowIfCancellationRequested();
if (!gameScene.isLoaded || !SceneManager.SetActiveScene(gameScene))
throw new InvalidOperationException("Failed to activate game scene: " + sceneName);
HotPatchLog.Info("scene_load_complete scene=" + sceneName + " version=" + resources.LoadedVersion);
Report("Loading resources", 1);
await UniTask.Yield();
cancellationToken.ThrowIfCancellationRequested();
LaunchSceneInput.Transfer(launchScene, gameScene);
#if UNITY_EDITOR
await UniTask.NextFrame(cancellationToken: cancellationToken);
HotPatchLog.Info("editor_initialization_start scene=" + gameScene.name);
resources.InitializeEditor();
HotPatchLog.Info("editor_initialization_complete scene=" + gameScene.name);
#endif
await SceneManager.UnloadSceneAsync(launchScene);
IsCompleted = true;
}
catch (Exception exception)
{
showRetryDialog = HandleFailure(exception);
if (gameScene.IsValid() && gameScene.isLoaded) await SceneManager.UnloadSceneAsync(gameScene);
}
finally
{
IsRunning = false;
}
if (showRetryDialog) ShowRetryDialog(() => RunAsync().Forget(Debug.LogException));
}
bool HandleFailure(Exception exception)
{
IsResourcesReady = false;
HotPatchLog.Warning("launch_failed type=" + exception.GetType().Name + " message=" + exception.Message);
if (cancellationToken.IsCancellationRequested || exception is OperationCanceledException) return false;
if (resources.HasLoadedAssembly) resources.MarkEntryFailed();
Debug.LogException(exception);
return true;
}
void ShowRetryDialog(Action retry)
{
if (!CanRun) return;
HotPatchLog.Info("retry_dialog_open requiresRestart=" + resources.RequiresRestart);
view.ShowError(NativeDialog.NetworkErrorMessage, () =>
{
if (!CanRun) return;
HotPatchLog.Info("retry_dialog_confirmed");
retry();
});
}
void Report(string stage, float progress)
{
if (CanRun) view.ReportProgress(stage, progress);
}
}