thief-mission-viewer/project/code/TMV/UI/ModelSelector.cs

96 lines
2.4 KiB
C#

using System.IO;
using System.IO.Compression;
using System.Linq;
using Godot;
namespace KeepersCompound.TMV.UI;
public partial class ModelSelector : Control
{
[Signal]
public delegate void LoadModelEventHandler(string rootPath, string modelPath);
private InstallPaths _installPaths;
private FileDialog _FolderSelect;
private LineEdit _FolderPath;
private Button _BrowseButton;
private ItemList _Models;
private Button _LoadButton;
private Button _CancelButton;
private string _extractedObjectsPath = ProjectSettings.GlobalizePath($"user://objects/tmp");
public override void _Ready()
{
// TODO: Load initial folderpath from config and prefil everything
_FolderSelect = GetNode<FileDialog>("%FolderSelect");
_FolderPath = GetNode<LineEdit>("%FolderPath");
_BrowseButton = GetNode<Button>("%BrowseButton");
_Models = GetNode<ItemList>("%Models");
_LoadButton = GetNode<Button>("%LoadButton");
_CancelButton = GetNode<Button>("%CancelButton");
_BrowseButton.Pressed += () => _FolderSelect.Visible = true;
_FolderSelect.DirSelected += (string dir) => { _FolderPath.Text = dir; BuildModelList(dir); };
_FolderPath.TextSubmitted += BuildModelList;
_Models.ItemSelected += (long _) => _LoadButton.Disabled = false;
_LoadButton.Pressed += EmitLoadModel;
_CancelButton.Pressed += () => Visible = false;
}
public override void _Input(InputEvent @event)
{
if (@event is InputEventKey keyEvent && keyEvent.Pressed)
{
if (keyEvent.Keycode == Key.Escape)
{
Visible = !Visible;
}
}
}
private void BuildModelList(string path)
{
_installPaths = new InstallPaths(path);
ExtractObjFiles();
_Models.Clear();
_LoadButton.Disabled = true;
var paths = Directory.GetFiles(_extractedObjectsPath, "*.bin", SearchOption.AllDirectories);
foreach (var m in paths.OrderBy(s => s))
{
_Models.AddItem(m.TrimPrefix(_extractedObjectsPath));
}
}
// TODO: Move this to a resource manager
private void ExtractObjFiles()
{
var dir = new DirectoryInfo(_extractedObjectsPath);
if (dir.Exists)
{
dir.Delete(true);
}
var zip = ZipFile.OpenRead(_installPaths.objPath);
zip.ExtractToDirectory(_extractedObjectsPath);
}
private void EmitLoadModel()
{
var selected = _Models.GetSelectedItems();
if (selected.IsEmpty())
{
return;
}
var path = _extractedObjectsPath + _Models.GetItemText(selected[0]);
EmitSignal(SignalName.LoadModel, _installPaths.rootPath, path);
Visible = false;
}
}