Editor/UnityPackageWindow.cs

Editor UI window for importing Unity .unitypackage files into an s&box project. It reads and scans packages, shows package contents in a tree, allows selecting which assets to convert, configures import options, runs the import (with progress, conflict review and resource preparation), and shows/export a completion report.

File Access
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Editor;
using Sandbox;

namespace ImportUnityPackage;

public sealed class UnityPackageWindow : Widget
{
	UnityArchive archive;
	ImportCatalog catalog;
	ImportPlan plan;
	HashSet<UnityAssetKind> placementKinds = new();
	UnityAsset describedAsset;
	CancellationTokenSource cancellation;
	Task<UnityArchive> readTask;
	Task<ImportResult> importTask;
	ImportPreparationResult preparation;
	long preparationMilliseconds;
	ImportCompletion completion;
	string reportJson;
	string[] completionInformation = Array.Empty<string>();
	readonly Button exportReport;
	readonly Button showReport;
	volatile ImportProgress latestProgress;
	bool closeWhenCancelled;
	readonly Button browse;
	readonly Button confirm;
	readonly Button cancel;
	readonly Button reimport;
	readonly Button done;
	readonly Label packageLabel;
	readonly Label status;
	readonly Label stageLabel;
	readonly Label selection;
	readonly Checkbox additionalTerrain;
	readonly Checkbox createModel;
	readonly Checkbox createMaterial;
	readonly Checkbox createTerrain;
	readonly Checkbox createTexture;
	readonly Checkbox createSound;
	readonly Checkbox createPrefab;
	readonly Checkbox createScene;
	readonly Checkbox createTerrainData;
	bool advancedExpanded;
	readonly Checkbox importToAssets;
	readonly Label destination;
	readonly Button selectAll;
	readonly Button selectNone;
	readonly Button expandAll;
	readonly Button collapseAll;
	readonly IconButton expandLayer;
	readonly IconButton collapseLayer;
	readonly Button advancedToggle;
	readonly Widget advanced;
	readonly Label details;
	readonly UnityAssetTree tree;
	readonly Widget progressBar;
	bool Busy => readTask != null || importTask != null;
	ImportOptions Options => ImportOptions.Auto( additionalTerrain.Value && createMaterial.Value && createTerrain.Value ) with
	{
		ImportToAssets = importToAssets.Value,
		Vmdl = createModel.Value, Vmat = createMaterial.Value, TerrainDefinitions = createTerrain.Value,
		Vtex = createTexture.Value, Sound = createSound.Value, Prefabs = createPrefab.Value, Scenes = createScene.Value,
		Terrains = createTerrainData.Value
	};

	public UnityPackageWindow() : base( null, true )
	{
		WindowTitle = "Import Unity Package";
		var assetsDirectory = Project.Current?.GetAssetsPath();
		if ( !string.IsNullOrEmpty( assetsDirectory ) )
			foreach ( var warning in ImportWorkspace.CleanupAbandoned( assetsDirectory ) ) Log.Warning( warning );
		SetWindowIcon( "move_to_inbox" );
		Size = new Vector2( 760, 680 );
		MinimumSize = new Vector2( 580, 500 );
		Layout = Layout.Column();
		Layout.Margin = 16;
		Layout.Spacing = 10;
		var fileRow = Layout.AddRow();
		fileRow.Spacing = 8;
		packageLabel = fileRow.Add( new Label( "Choose a .unitypackage file" ), 1 );
		browse = fileRow.Add( new Button( "Browse…" ) );
		browse.Clicked = Browse;
		var contents = Layout.AddRow();
		contents.Spacing = 8;
		contents.Add( new Label( "Package contents" ), 1 );
		expandAll = contents.Add( new Button( "Expand all" ) );
		collapseAll = contents.Add( new Button( "Collapse all" ) );
		expandAll.Clicked = () => tree.SetExpanded( true );
		collapseAll.Clicked = () => tree.SetExpanded( false );
		collapseLayer = contents.Add( new IconButton( "remove", () => tree.ChangeExpandedLayer( false ) ) { ToolTip = "Collapse one layer" } );
		expandLayer = contents.Add( new IconButton( "add", () => tree.ChangeExpandedLayer( true ) ) { ToolTip = "Expand one layer" } );
		var shortcuts = Layout.AddRow();
		shortcuts.Spacing = 8;
		selectAll = shortcuts.Add( new Button( "Select all" ) );
		selectNone = shortcuts.Add( new Button( "Clear" ) );
		shortcuts.AddStretchCell();
		selectAll.Clicked = () => SetSelection( a => a.Kind != UnityAssetKind.Unsupported );
		selectNone.Clicked = () => SetSelection( _ => false );
		tree = Layout.Add( new UnityAssetTree( this, () => plan, RefreshSelection, DescribeAsset ), 1 );
		tree.MinimumHeight = 200;
		details = Layout.Add( new Label( "" ) { Visible = false } );
		details.WordWrap = true;
		advancedToggle = Layout.Add( new Button( "Advanced ▸" ) );
		advanced = Layout.Add( new Widget( this ) );
		advanced.Layout = Layout.Column();
		var destinationRow = advanced.Layout.AddRow();
		destinationRow.Spacing = 12;
		importToAssets = destinationRow.Add( new Checkbox( "Import to assets" ) { Value = true } );
		importToAssets.ToolTip = "*/Assets/ are automatically published with your game. It's recommended to manually add each individually.";
		destination = destinationRow.Add( new Label( "" ) { WordWrap = true }, 1 );
		importToAssets.StateChanged += _ => RefreshSelection();
		Checkbox Definition( string text, string tooltip )
		{
			var checkbox = advanced.Layout.Add( new Checkbox( text ) { Value = true, ToolTip = tooltip } );
			checkbox.StateChanged += _ => RefreshSelection();
			return checkbox;
		}
		createModel = Definition( "Create model definition (VMDL)", "Create model definitions from selected models. Original model sources are always kept." );
		createMaterial = Definition( "Create material definition (VMAT)", "Create material definitions from included Unity materials. Original materials and texture sources are always kept." );
		createTerrain = Definition( "Create terrain material definition (TMAT)", "Create terrain materials from Unity terrain layers, or from other materials using the option below." );
		createTexture = Definition( "Create texture definition (VTEX)", "Create texture definitions for EXR, PSD and TIFF sources. Original images are always kept." );
		createSound = Definition( "Create sound definition (SOUND)", "Create sound events from included audio files. Original audio sources are always kept." );
		createPrefab = Definition( "Create prefabs (PREFAB)", "Convert selected Unity prefabs into s&box prefabs placing the imported models, nested prefabs, colliders, lights, cameras, reflection probes and audio sources. Scripts and effects are not converted." );
		createScene = Definition( "Create scenes (SCENE)", "Convert selected Unity scenes into s&box scenes: placed models and prefabs, terrains, lights, cameras, reflection probes, audio sources, sky, ambient light and fog. Scripts, particle effects and baked lighting are not converted." );
		createTerrainData = Definition( "Create terrains (TERRAIN)", "Convert Unity terrain data into s&box terrains: heightmap, holes and painted layers. Scenes and prefabs place them with their painted trees; grass and detail meshes are not converted." );
		additionalTerrain = advanced.Layout.Add( new Checkbox( "Generate terrain materials (TMAT) for every material (VMAT)" ) );
		additionalTerrain.ToolTip = "Also create terrain materials from the materials being converted to VMAT. This does not recreate Unity terrain.";
		additionalTerrain.StateChanged += _ => RefreshSelection();
		advanced.Visible = false;
		advancedToggle.Clicked = () => { advancedExpanded = !advancedExpanded; RefreshSelection(); };
		stageLabel = Layout.Add( new Label( "" ) { Visible = false } );
		stageLabel.SetStyles( "color: #7fce83; font-weight: bold;" );
		progressBar = Layout.Add( new Widget( this ) { FixedHeight = 16, Visible = false } );
		progressBar.OnPaintOverride = PaintProgress;
		status = Layout.Add( new Label( "" ) { Visible = false } );
		status.WordWrap = true;
		selection = Layout.Add( new Label( "" ) { WordWrap = true } );
		var buttons = Layout.AddRow();
		buttons.Spacing = 8;
		showReport = buttons.Add( new Button( "Details" ) { Visible = false } );
		showReport.Clicked = ShowDetails;
		exportReport = buttons.Add( new Button( "Export report" ) { Visible = false } );
		exportReport.Clicked = ExportReport;
		// Not keyboard-focusable: the Enter or Space that closes the completion dialog must not start a reimport (which
		// re-reads the package) through the focused button.
		reimport = buttons.Add( new Button( "Reimport" ) { Visible = false, FocusMode = FocusMode.None } );
		reimport.Clicked = Import;
		buttons.AddStretchCell();
		cancel = buttons.Add( new Button( "Cancel" ) );
		cancel.Clicked = Cancel;
		confirm = buttons.Add( new Button.Primary( "Confirm import" ) );
		confirm.Clicked = Import;
		done = buttons.Add( new Button.Primary( "Done" ) { Visible = false } );
		done.Clicked = () => Close();
		RefreshSelection();
	}

	static string lastBrowseDirectory;

	public void Browse()
	{
		if ( Busy ) return;
		var dialog = new FileDialog( this ) { Title = "Import Unity Package", DefaultSuffix = ".unitypackage" };
		dialog.SetFindFile();
		dialog.SetNameFilter( "Unity Package (*.unitypackage)" );
		// The last folder used, else Unity's Asset Store download cache, else the Unity folder.
		var appData = Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData );
		var start = new[] { lastBrowseDirectory, Path.Combine( appData, "Unity", "Asset Store-5.x" ), Path.Combine( appData, "Unity" ) }
			.FirstOrDefault( d => !string.IsNullOrEmpty( d ) && !string.IsNullOrEmpty( appData ) && Directory.Exists( d ) );
		if ( start != null ) dialog.Directory = start;
		if ( !dialog.Execute() ) return;
		lastBrowseDirectory = Path.GetDirectoryName( dialog.SelectedFile );
		LoadPackage( dialog.SelectedFile );
	}

	/// <summary>Load a package into the selection window, including from other editor tools.</summary>
	public void LoadPackage( string file )
	{
		if ( Busy ) return;
		var assetsDirectory = Project.Current?.GetAssetsPath();
		if ( string.IsNullOrEmpty( assetsDirectory ) )
		{
			EditorUtility.DisplayDialog( "Import unavailable", "Open a local s&box project before importing." );
			return;
		}
		ReleaseArchive();
		catalog = null;
		plan = null;
		describedAsset = null;
		tree.SetItems( Array.Empty<TreeNode>() );
		ClearCompletion();
		WindowTitle = "Import Unity Package";
		packageLabel.Text = Path.GetFileName( file );
		packageLabel.ToolTip = file;
		cancellation = new CancellationTokenSource();
		latestProgress = new( 0, "Reading package…", "Scanning package" );
		stageLabel.Text = latestProgress.Stage; stageLabel.Visible = true;
		readTask = Task.Run( () =>
		{
			var loaded = UnityArchive.Read( file, new ProgressSink( this, stage: "Scanning package" ), cancellation.Token, assetsDirectory );
			try
			{
				latestProgress = new( 1, "Resolving package dependencies…", "Finding dependencies" );
				catalog = ImportCatalog.Read( loaded, cancellation.Token );
				return loaded;
			}
			catch { DisposeAndReport( loaded ); throw; }
		} );
		RefreshSelection();
	}

	void Import()
	{
		if ( Busy || plan == null || plan.Assets.Count == 0 ) return;
		var assets = Project.Current?.GetAssetsPath();
		if ( string.IsNullOrEmpty( assets ) )
		{
			EditorUtility.DisplayDialog( "Import unavailable", "Open a local s&box project before importing." );
			return;
		}
		var confirmedPlan = plan;
		cancellation = new CancellationTokenSource();
		latestProgress = new( 0, "Preparing import…", "Preparing assets" );
		stageLabel.Text = latestProgress.Stage; stageLabel.Visible = true;
		ClearCompletion();
		WindowTitle = "Import Unity Package";
		importTask = ImportAndPrepare( confirmedPlan, assets, cancellation.Token );
		RefreshSelection();
	}

	async Task<ImportResult> ImportAndPrepare( ImportPlan confirmedPlan, string assets, CancellationToken token )
	{
		ImportMergePlan merge = null;
		ImportResult result = null;
		try
		{
			if ( !archive.HasExtractedFiles )
			{
				// The re-read package replaces the window's archive, catalog and tree together, only once it has fully loaded;
				// the selection carries over as it was, including assets an option currently leaves out.
				var selected = archive.Assets.Where( a => a.Selected ).Select( a => a.Path ).ToHashSet( StringComparer.OrdinalIgnoreCase );
				var options = confirmedPlan.Options;
				var fileName = archive.FileName;
				var fresh = await Task.Run( () => UnityArchive.Read( fileName, new ProgressSink( this, 0, 0.15, "Scanning package" ), token, assets ) );
				ImportCatalog freshCatalog;
				try
				{
					foreach ( var item in fresh.Assets ) item.Selected = selected.Contains( item.Path );
					latestProgress = new( 0.15, "Resolving package dependencies…", "Finding dependencies" );
					freshCatalog = await Task.Run( () => ImportCatalog.Read( fresh, token ) );
				}
				catch { fresh.Dispose(); throw; }
				(archive, catalog) = (fresh, freshCatalog); // The previous archive was already released.
				confirmedPlan = catalog.CreatePlan( options );
				tree.Load( archive.Assets );
			}
			merge = await Task.Run( () => ImportMergePlan.Create( confirmedPlan, assets, token ) );
			await Task.Run( () => merge.Prepare( new ProgressSink( this, 0.15, 0.55 ), token, extractChannels: TextureChannels.ExtractBatch ) );
			latestProgress = new( 0.7, "Review import files…", "Waiting for confirmation" );
			await ImportConflictWindow.Review( "Review import files", merge.Destination, merge.Outputs, token );
			result = await Task.Run( () => merge.Commit( new ProgressSink( this, 0.7, 0.1, "Writing files" ), token ) );
			latestProgress = result.RequiresResourcePreparation ? new( 0.8, "Preparing imported resources…", "Preparing s&box resources" ) : new( 0.98, "Files stored outside Assets", "Import complete" );
			var preparationTimer = System.Diagnostics.Stopwatch.StartNew();
			preparation = await ImportAssetPreparation.RunImport( result, new ProgressSink( this, 0.8, 0.18, "Preparing s&box resources" ), token );
			preparationMilliseconds = preparationTimer.ElapsedMilliseconds;
		}
		finally
		{
			latestProgress = new( latestProgress?.Fraction ?? 0, "Removing temporary files…", "Cleaning up" );
			await Task.Run( () => { merge?.Dispose(); archive?.Dispose(); } );
			if ( result == null )
				foreach ( var warning in (merge?.CleanupWarnings ?? Array.Empty<string>()).Concat( archive?.CleanupWarnings ?? Array.Empty<string>() ) ) Log.Warning( warning );
		}
		return result with { Warnings = result.Warnings.Concat( merge.CleanupWarnings ).Concat( archive.CleanupWarnings ).Distinct().ToArray() };
	}

	void Cancel()
	{
		if ( !Busy ) { Close(); return; }
		cancellation.Cancel();
		cancel.Enabled = false;
		status.Text = "Cancelling…";
	}

	[EditorEvent.Frame]
	void Tick()
	{
		if ( !IsValid ) return;
		if ( Busy && latestProgress != null )
		{
			status.Text = cancellation.IsCancellationRequested ? "Cancelling…" : $"{latestProgress.Fraction:P0} — {latestProgress.Message}";
			stageLabel.Text = cancellation.IsCancellationRequested ? "Cancelling / cleaning up" : latestProgress.Stage ?? "Preparing assets";
			progressBar.Update();
		}
		if ( readTask?.IsCompleted == true )
		{
			var task = readTask;
			readTask = null;
			FinishOperation( () =>
			{
				archive = task.GetAwaiter().GetResult();
				tree.Load( archive.Assets );
				stageLabel.Visible = false;
				status.Text = "";
			} );
		}
		if ( importTask?.IsCompleted == true )
		{
			var task = importTask;
			importTask = null;
			FinishOperation( () =>
			{
				var result = task.GetAwaiter().GetResult();
				SetCompletion( result );
				EditorUtility.DisplayDialog( completion.Title, completion.Message, icon: completion.Icon );
			} );
		}
	}

	void SetCompletion( ImportResult result )
	{
		completion = ImportCompletion.Create( result, preparation?.Warnings, preparation?.Errors, preparation?.Cancelled == true );
		foreach ( var error in completion.Errors ) Log.Error( error );
		// Detailed compatibility warnings belong in the report, not hundreds of console lines.
		Log.Info( $"{completion.Title}: {result.AssetCount} assets. {completion.Counts}." );
		reportJson = completion.AppendReport( result.ReportJson, preparation != null ? preparationMilliseconds : null );
		completionInformation = result.Information;
		showReport.Visible = exportReport.Visible = true;
		ApplyCompletion();
	}

	void ClearCompletion()
	{
		preparation = null;
		completion = null;
		reportJson = null;
		completionInformation = Array.Empty<string>();
		showReport.Visible = exportReport.Visible = false;
		status.Text = "";
	}

	static void DisposeAndReport( UnityArchive package )
	{
		if ( package == null || !package.HasExtractedFiles ) return;
		package.Dispose();
		foreach ( var warning in package.CleanupWarnings ) Log.Warning( warning );
	}

	void ReleaseArchive()
	{
		DisposeAndReport( archive );
		archive = null;
	}

	void ExportReport()
	{
		var dialog = new FileDialog( this ) { Title = "Export import report", DefaultSuffix = ".json" };
		dialog.SetFindFile(); dialog.SetModeSave(); dialog.SetNameFilter( "JSON report (*.json)" );
		if ( dialog.Execute() )
		{
			try { File.WriteAllText( dialog.SelectedFile, reportJson ); }
			catch ( Exception ex ) { EditorUtility.DisplayDialog( "Could not export report", ex.Message ); }
		}
	}

	void ShowDetails()
	{
		// A top-level window (no parent), like the conflict review; parented to this window it was drawn inside it, transparent.
		var window = new Widget( null, true ) { WindowTitle = $"Details — {completion.Title}", Size = new Vector2( 780, 560 ) };
		window.Layout = Layout.Column(); window.Layout.Margin = 16; window.Layout.Spacing = 8;
		// Problems first: errors and warnings are shown, information on request. Each kind can be switched on or off.
		var filters = window.Layout.AddRow(); filters.Spacing = 12;
		var showErrors = filters.Add( new Checkbox( $"Errors ({completion.Errors.Length})" ) { Value = true } );
		var showWarnings = filters.Add( new Checkbox( $"Warnings ({completion.Warnings.Length})" ) { Value = true } );
		var showInformation = filters.Add( new Checkbox( $"Information ({completionInformation.Length})" ) { Value = false } );
		filters.AddStretchCell();
		var copy = filters.Add( new Button( "Copy shown" ) { ToolTip = "Copy the entries shown below to the clipboard." } );
		var scroll = window.Layout.Add( new ScrollArea( window ), 1 );
		var shown = "";
		void Fill()
		{
			scroll.Canvas = new Widget( window ); scroll.Canvas.Layout = Layout.Column(); scroll.Canvas.Layout.Spacing = 2;
			var text = new System.Text.StringBuilder();
			// Entries read "asset: message"; they are grouped under their asset so many entries for one file stay together.
			void Section( string title, string[] items, bool visible )
			{
				if ( !visible || items.Length == 0 ) return;
				scroll.Canvas.Layout.Add( new Label( $"{title} ({items.Length})" ) );
				text.AppendLine( $"{title} ({items.Length})" );
				foreach ( var group in items.GroupBy( Subject ).OrderBy( g => g.Key == "" ? 1 : 0 ).ThenBy( g => g.Key, StringComparer.OrdinalIgnoreCase ) )
				{
					if ( group.Key != "" ) { scroll.Canvas.Layout.Add( new Label( "   " + group.Key ) ); text.AppendLine( "  " + group.Key ); }
					foreach ( var item in group )
					{
						var message = group.Key == "" ? item : item[(group.Key.Length + 1)..].Trim();
						scroll.Canvas.Layout.Add( new Label( "      • " + message ) { WordWrap = true } );
						text.AppendLine( "    - " + message );
					}
				}
				scroll.Canvas.Layout.AddSpacingCell( 8 );
				text.AppendLine();
			}
			Section( "Errors", completion.Errors, showErrors.Value );
			Section( "Warnings", completion.Warnings, showWarnings.Value );
			Section( "Information", completionInformation, showInformation.Value );
			if ( text.Length == 0 )
				scroll.Canvas.Layout.Add( new Label( completion.Errors.Length + completion.Warnings.Length + completionInformation.Length == 0
					? "Import completed without issues." : "Nothing to show: switch on errors, warnings or information above." ) );
			scroll.Canvas.Layout.AddStretchCell();
			shown = text.ToString();
		}
		showErrors.StateChanged += _ => Fill();
		showWarnings.StateChanged += _ => Fill();
		showInformation.StateChanged += _ => Fill();
		copy.Clicked = () => Sandbox.UI.Clipboard.SetText( shown );
		Fill();
		window.Layout.Add( new Button.Primary( "Done" ) ).Clicked = () => window.Close();
		window.Show();
	}

	/// <summary>The asset an entry ("asset: message") is about, or "" when it names none.</summary>
	static string Subject( string entry )
	{
		var colon = entry.IndexOf( ": ", StringComparison.Ordinal );
		if ( colon <= 0 ) return "";
		var subject = entry[..colon];
		return subject.Contains( '/' ) || subject.Contains( '.' ) ? subject : "";
	}

	void ApplyCompletion()
	{
		stageLabel.Text = completion.Title;
		stageLabel.Visible = !completion.Cancelled && completion.Errors.Length == 0;
		status.Text = completion.Status;
		WindowTitle = $"Import Unity Package — {completion.Title}";
		if ( !completion.Cancelled ) latestProgress = new( 1, completion.Title );
		progressBar.Update();
	}

	void FinishOperation( Action action )
	{
		try { action(); }
		catch ( OperationCanceledException ex )
		{
			stageLabel.Visible = false;
			status.Text = "Cancelled. Any files written before the cancel remain in the project.";
			if ( ex.Data["StagingCleanupError"] is string cleanup ) { status.Text += " Temporary files could not be removed; see the console."; Log.Warning( cleanup ); }
		}
		catch ( Exception ex )
		{
			stageLabel.Visible = false;
			status.Text = $"Import stopped: {ex.Message}\nAny files written before the stop remain in the project.";
			Log.Error( $"{status.Text}\n{ex}" );
			if ( ex.Data["StagingCleanupError"] is string cleanup ) Log.Warning( cleanup );
			EditorUtility.DisplayDialog( "Unity package import failed", ex.Message, icon: "❌" );
		}
		finally
		{
			cancellation.Dispose();
			cancellation = null;
			RefreshSelection();
			if ( closeWhenCancelled ) Close();
		}
	}

	void SetSelection( Func<UnityAsset, bool> select )
	{
		if ( Busy || archive == null ) return;
		foreach ( var asset in archive.Assets ) asset.Selected = select( asset );
		RefreshSelection();
	}

	void DescribeAsset( UnityAsset asset )
	{
		describedAsset = asset;
		details.Visible = asset != null;
		if ( asset == null ) { details.Text = ""; details.ToolTip = ""; return; }
		var entry = plan?.Find( asset );
		var reasons = entry?.RequiredBy.Select( d => $"{d.Asset.Path} ({d.Reason})" ).Distinct().ToArray() ?? Array.Empty<string>();
		var problems = plan?.Issues.Where( i => i.Asset == asset.Path ).Select( i => i.Message ).ToArray() ?? Array.Empty<string>();
		details.Text = asset.Path + "\n" + (entry?.OutputLabel ?? (asset.Kind == UnityAssetKind.Unsupported ? "Unsupported" : "Not included")) +
			(reasons.Length == 0 ? "" : " · Required by: " + string.Join( "; ", reasons.Take( 3 ) ) + (reasons.Length > 3 ? $"; +{reasons.Length - 3} more" : "")) +
			(problems.Length == 0 ? "" : "\n" + string.Join( " ", problems.Take( 2 ) ));
		details.ToolTip = string.Join( "\n", reasons.Concat( problems ) );
	}

	void RefreshSelection()
	{
		if ( confirm == null ) return;
		browse.Enabled = tree.Enabled = additionalTerrain.Enabled = importToAssets.Enabled = advancedToggle.Enabled = !Busy;
		createModel.Enabled = createMaterial.Enabled = createTerrain.Enabled = createTexture.Enabled = createSound.Enabled = createPrefab.Enabled = createScene.Enabled = createTerrainData.Enabled = !Busy;
		var assetsDirectory = Project.Current?.GetAssetsPath();
		var projectFolder = string.IsNullOrEmpty( assetsDirectory ) ? null : new DirectoryInfo( assetsDirectory ).Parent?.Name;
		destination.Text = "Destination: " + (string.IsNullOrEmpty( projectFolder ) ? "" : projectFolder + "/") + (importToAssets.Value ? "Assets/Imported" : "Imported");
		destination.ToolTip = string.IsNullOrEmpty( assetsDirectory ) ? "" : ImportMergePlan.GetDestination( assetsDirectory, importToAssets.Value );
		selectAll.Enabled = selectNone.Enabled = expandAll.Enabled = collapseAll.Enabled = !Busy && archive != null;
		expandLayer.Enabled = collapseLayer.Enabled = !Busy && archive != null;
		cancel.Enabled = !Busy || cancellation?.IsCancellationRequested != true;
		cancel.Text = Busy ? "Cancel operation" : "Cancel";
		cancel.Visible = confirm.Visible = completion == null || Busy;
		reimport.Visible = done.Visible = completion != null && !Busy;
		if ( !Busy ) plan = catalog?.CreatePlan( Options );
		confirm.Enabled = reimport.Enabled = !Busy && plan?.Assets.Count > 0;
		confirm.Text = "Review import";
		// Availability is based on source selection, so switching a definition off never hides its own control.
		var hasModels = plan?.Assets.Any( a => a.CanCreateVmdl ) == true;
		var hasMaterials = plan?.Assets.Any( a => a.CanCreateVmat ) == true;
		var hasTerrain = plan?.Assets.Any( a => a.IsTerrainLayer || a.CanCreateVmat && createMaterial.Value ) == true;
		var hasTextures = plan?.Assets.Any( a => a.CanCreateVtex ) == true;
		var hasSounds = plan?.Assets.Any( a => a.CanCreateSound ) == true;
		createModel.Visible = hasModels;
		createMaterial.Visible = hasMaterials;
		createTerrain.Visible = hasTerrain;
		createTexture.Visible = hasTextures;
		createSound.Visible = hasSounds;
		// Prefab, scene and terrain availability comes from the plan with those options on (switching one off removes its
		// assets from the plan), so dependencies of the selection count too.
		var placements = Busy ? null : catalog?.CreatePlan( Options with { Prefabs = true, Scenes = true, Terrains = true } );
		if ( placements != null ) placementKinds = placements.Assets.Select( a => a.Asset.Kind ).ToHashSet();
		createPrefab.Visible = placementKinds.Contains( UnityAssetKind.Prefab );
		createScene.Visible = placementKinds.Contains( UnityAssetKind.Scene );
		createTerrainData.Visible = placementKinds.Contains( UnityAssetKind.Terrain );
		additionalTerrain.Visible = hasMaterials && createMaterial.Value && createTerrain.Value;
		// The destination choice is always available, including for sources without definitions.
		advanced.Visible = advancedExpanded;
		advancedToggle.Text = advancedExpanded ? "Advanced ▾" : "Advanced ▸";
		var outputs = plan == null ? Array.Empty<string>() : new[]
		{
			(Count: plan.Assets.Count( a => a.Vmdl ), Name: "VMDL"),
			(Count: plan.Assets.Count( a => a.Vmat ), Name: "VMAT"),
			(Count: plan.Assets.Count( a => a.Tmat ), Name: "TMAT"),
			(Count: plan.Assets.Count( a => a.Vtex ), Name: "VTEX"),
			(Count: plan.Assets.Count( a => a.Sound ), Name: "SOUND"),
			(Count: plan.Assets.Count( a => a.Prefab ), Name: "PREFAB"),
			(Count: plan.Assets.Count( a => a.Scene ), Name: "SCENE"),
			(Count: plan.Assets.Count( a => a.Terrain ), Name: "TERRAIN")
		}.Where( o => o.Count > 0 ).Select( o => $"{o.Count:N0} {o.Name}" ).ToArray();
		selection.Text = plan == null ? "" : plan.Assets.Count == 0 ? "No files selected." :
			$"{plan.Assets.Count:N0} source files" + (outputs.Length == 0 ? "" : " · Outputs: " + string.Join( " · ", outputs ));
		selection.Visible = plan != null && !Busy;
		status.Visible = Busy || !string.IsNullOrEmpty( status.Text );
		progressBar.Visible = Busy;
		DescribeAsset( describedAsset );
		tree.Update();
	}

	bool PaintProgress()
	{
		Paint.ClearPen();
		Paint.SetBrush( Theme.ControlBackground );
		Paint.DrawRect( progressBar.LocalRect, 3 );
		var rect = progressBar.LocalRect;
		rect.Width *= (float)Math.Clamp( latestProgress?.Fraction ?? 0, 0, 1 );
		Paint.SetBrush( Theme.Blue );
		Paint.DrawRect( rect, 3 );
		return false;
	}

	protected override bool OnClose()
	{
		if ( Busy ) { closeWhenCancelled = true; Cancel(); return false; }
		ReleaseArchive();
		return true;
	}

	sealed class ProgressSink( UnityPackageWindow window, double start = 0, double scale = 1, string stage = null ) : IProgress<ImportProgress>
	{
		public void Report( ImportProgress value ) => window.latestProgress = new( start + scale * value.Fraction, value.Message, value.Stage ?? stage );
	}
}