Add folder drag&drop for configuring game directory

This commit is contained in:
LongerWarrior 2026-03-23 17:50:31 +02:00
parent a714a28ed1
commit 9c60080d3e
11 changed files with 276 additions and 147 deletions

View File

@ -27,6 +27,7 @@ public enum SettingsOut
public enum EStatusKind
{
Ready, // ready
Configuring, // waiting for user input
Loading, // doing stuff
Stopping, // trying to stop
Stopped, // stopped

View File

@ -1,4 +1,5 @@
using System;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
@ -62,7 +63,7 @@ public static class Helper
GetOpenedWindow<T>(windowName).Close();
}
private static bool IsWindowOpen<T>(string name = "") where T : Window
public static bool IsWindowOpen<T>(string name = "") where T : Window
{
return string.IsNullOrEmpty(name)
? Application.Current.Windows.OfType<T>().Any()
@ -111,4 +112,24 @@ public static class Helper
const float ratio = 180f / MathF.PI;
return radians * ratio;
}
public static string GetGameName(string path)
{
// install_folder/
// ├─ Engine/
// ├─ GameName/
// │ ├─ Binaries/
// │ ├─ Content/
// │ │ ├─ Paks/
// our goal is to get the GameName folder
var dir = new DirectoryInfo(path);
if (dir.Name.Equals("Paks", StringComparison.InvariantCulture) && dir.Parent is { Parent: not null } &&
dir.Parent.Name.Equals("Content", StringComparison.InvariantCulture) &&
dir.Parent.Parent.GetDirectories().Any(x => x.Name == "Binaries"))
{
return dir.Parent.Parent.Name;
}
return dir.Name;
}
}

View File

@ -629,6 +629,10 @@
<Setter Property="Background" Value="{DynamicResource {x:Static adonisUi:Brushes.AlertBrush}}" />
<Setter Property="Foreground" Value="White" />
</DataTrigger>
<DataTrigger Binding="{Binding Status.Kind}" Value="{x:Static local:EStatusKind.Configuring}">
<Setter Property="Background" Value="{DynamicResource {x:Static adonisUi:Brushes.AlertBrush}}" />
<Setter Property="Foreground" Value="White" />
</DataTrigger>
<DataTrigger Binding="{Binding Status.Kind}" Value="{x:Static local:EStatusKind.Stopped}">
<Setter Property="Background" Value="{DynamicResource {x:Static adonisUi:Brushes.ErrorBrush}}" />
<Setter Property="Foreground" Value="White" />
@ -710,7 +714,7 @@
</StackPanel>
</StatusBarItem>
</StatusBar>
<controls:UsmapDropOverlay Grid.RowSpan="99"
Panel.ZIndex="1000" />
<controls:DropOverlay Grid.RowSpan="99"
Panel.ZIndex="1000" />
</Grid>
</adonisControls:AdonisWindow>

View File

@ -141,8 +141,10 @@ public class ApplicationViewModel : ViewModel
if (!bAlreadyLaunched && UserSettings.Default.PerDirectory.TryGetValue(gameDirectory, out var currentDir))
return currentDir;
Status.SetStatus(EStatusKind.Configuring);
var gameLauncherViewModel = new GameSelectorViewModel(gameDirectory);
var result = new DirectorySelector(gameLauncherViewModel).ShowDialog();
Status.SetStatus(EStatusKind.Ready);
if (!result.HasValue || !result.Value) return null;
UserSettings.Default.GameDirectory = gameLauncherViewModel.SelectedDirectory.GameDirectory;
@ -155,6 +157,35 @@ public class ApplicationViewModel : ViewModel
return null;
}
public DirectorySettings AddGameDirectory(string directory)
{
if (Status.Kind is EStatusKind.Configuring)
{
var directorySelector = Helper.GetWindow<DirectorySelector>("Directory Selector", null);
directorySelector.AddManualGame(directory);
return null;
}
else
{
Status.SetStatus(EStatusKind.Configuring);
var gameLauncherViewModel = new GameSelectorViewModel(UserSettings.Default.GameDirectory);
var directorySelector = new DirectorySelector(gameLauncherViewModel);
directorySelector.AddManualGame(directory);
var result = directorySelector.ShowDialog();
Status.SetStatus(EStatusKind.Ready);
if (!result.HasValue || !result.Value)
return null;
UserSettings.Default.GameDirectory = gameLauncherViewModel.SelectedDirectory.GameDirectory;
if (UserSettings.Default.CurrentDir.Equals(gameLauncherViewModel.SelectedDirectory))
return gameLauncherViewModel.SelectedDirectory;
UserSettings.Default.CurrentDir = gameLauncherViewModel.SelectedDirectory;
RestartWithWarning();
return null;
}
}
public void RestartWithWarning()
{
MessageBox.Show("It looks like you just changed something.\nFModel will restart to apply your changes.", "Uh oh, a restart is needed", MessageBoxButton.OK, MessageBoxImage.Warning);

View File

@ -1,4 +1,4 @@
<adonisControls:AdonisWindow x:Class="FModel.Views.DirectorySelector"
<adonisControls:AdonisWindow x:Class="FModel.Views.DirectorySelector"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:FModel.Views.Resources.Controls"
@ -8,7 +8,8 @@
xmlns:adonisExtensions="clr-namespace:AdonisUI.Extensions;assembly=AdonisUI"
WindowStartupLocation="CenterScreen" ResizeMode="NoResize" IconVisibility="Collapsed" SizeToContent="Height"
MinHeight="{Binding Source={x:Static SystemParameters.MaximizedPrimaryScreenHeight}, Converter={converters:RatioConverter}, ConverterParameter='0.20'}"
Width="{Binding Source={x:Static SystemParameters.MaximizedPrimaryScreenWidth}, Converter={converters:RatioConverter}, ConverterParameter='0.25'}">
Width="{Binding Source={x:Static SystemParameters.MaximizedPrimaryScreenWidth}, Converter={converters:RatioConverter}, ConverterParameter='0.25'}"
AllowDrop="True">
<adonisControls:AdonisWindow.Style>
<Style TargetType="adonisControls:AdonisWindow" BasedOn="{StaticResource {x:Type adonisControls:AdonisWindow}}" >
<Setter Property="Title" Value="Directory Selector" />
@ -83,9 +84,12 @@
</Button>
</Grid>
<Separator Style="{StaticResource CustomSeparator}" Tag="ADD UNDETECTED GAME" />
<Expander ExpandDirection="Down" IsExpanded="False">
<Separator Style="{StaticResource CustomSeparator}" Tag="ADD UNDETECTED GAME" Margin="0,0,0,0"/>
<TextBlock Text="Drag &amp; drop folder to quickly configure new game"
HorizontalAlignment="Center"
Foreground="{DynamicResource {x:Static adonisUi:Brushes.ForegroundBrush}}"
Margin="0,0,0,5" />
<Expander x:Name="ManualGameExpander" ExpandDirection="Down" IsExpanded="False">
<Grid MaxWidth="{Binding ActualWidth, ElementName=Hello}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@ -137,5 +141,8 @@
HorizontalAlignment="Right" VerticalAlignment="Bottom" Content="Cancel" />
</Grid>
</Border>
<controls:DropOverlay Grid.RowSpan="99"
Grid.ColumnSpan="99"
Panel.ZIndex="1000" />
</Grid>
</adonisControls:AdonisWindow>

View File

@ -1,10 +1,6 @@
using System;
using System.IO;
using System.Linq;
using FModel.ViewModels;
using Ookii.Dialogs.Wpf;
using System.Windows;
using CUE4Parse.Utils;
namespace FModel.Views;
@ -43,28 +39,7 @@ public partial class DirectorySelector
if (folderBrowser.ShowDialog() == true)
{
HelloGameMyNameIsDirectory.Text = folderBrowser.SelectedPath;
// install_folder/
// ├─ Engine/
// ├─ GameName/
// │ ├─ Binaries/
// │ ├─ Content/
// │ │ ├─ Paks/
// our goal is to get the GameName folder
var currentFolder = folderBrowser.SelectedPath.SubstringAfterLast('\\');
if (currentFolder.Equals("Paks", StringComparison.InvariantCulture))
{
var dir = new DirectoryInfo(folderBrowser.SelectedPath);
if (dir.Parent is { Parent: not null } &&
dir.Parent.Name.Equals("Content", StringComparison.InvariantCulture) &&
dir.Parent.Parent.GetDirectories().Any(x => x.Name == "Binaries"))
{
HelloMyNameIsGame.Text = dir.Parent.Parent.Name;
return;
}
}
HelloMyNameIsGame.Text = folderBrowser.SelectedPath.SubstringAfterLast('\\');
HelloMyNameIsGame.Text = Helper.GetGameName(folderBrowser.SelectedPath);
}
}
@ -87,4 +62,11 @@ public partial class DirectorySelector
gameLauncherViewModel.DeleteSelectedGame();
}
public void AddManualGame(string directory)
{
ManualGameExpander.IsExpanded = true;
HelloMyNameIsGame.Text = Helper.GetGameName(directory);
HelloGameMyNameIsDirectory.Text = directory;
}
}

View File

@ -1,4 +1,4 @@
<UserControl x:Class="FModel.Views.Resources.Controls.UsmapDropOverlay"
<UserControl x:Class="FModel.Views.Resources.Controls.DropOverlay"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
@ -12,7 +12,7 @@
VerticalAlignment="Stretch"
d:DesignHeight="450"
d:DesignWidth="800">
<Grid Background="#AA000000"
<Grid Background="#DD000000"
IsHitTestVisible="False"
Grid.Row="0"
Grid.RowSpan="99">
@ -42,12 +42,12 @@
<Path Fill="{DynamicResource {x:Static adonisUi:Brushes.AccentForegroundBrush}}"
Data="{StaticResource ImportIcon}" />
</Viewbox>
<TextBlock Text="Drop .usmap to import"
<TextBlock x:Name="TitleText" Text="Drop .usmap to import"
Foreground="White"
FontSize="24"
FontWeight="Bold"
HorizontalAlignment="Center" />
<TextBlock Text="Mapping file will be applied immediately"
<TextBlock x:Name="DescriptionText" Text="Mapping file will be applied immediately"
Foreground="LightGray"
FontSize="14"
HorizontalAlignment="Center"

View File

@ -0,0 +1,169 @@
using System;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using FModel.Services;
using FModel.Settings;
using FModel.ViewModels;
namespace FModel.Views.Resources.Controls;
public partial class DropOverlay : UserControl
{
enum DragStatus
{
None,
File,
Folder,
}
private ApplicationViewModel _applicationView => ApplicationService.ApplicationView;
private DragStatus _dragStatus = DragStatus.None;
private string _path = null;
public DropOverlay()
{
InitializeComponent();
Loaded += OnLoaded;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ResetState()
{
_dragStatus = DragStatus.None;
_path = null;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
var window = Window.GetWindow(this);
if (window is null)
return;
window.PreviewDragEnter += OnPreviewDragEnter;
window.PreviewDragOver += OnPreviewDragOver;
window.PreviewDragLeave += OnPreviewDragLeave;
window.Drop += OnDrop;
}
private void OnPreviewDragEnter(object sender, DragEventArgs e)
{
GetValidTarget(sender, e);
if (_dragStatus is DragStatus.None)
{
e.Effects = DragDropEffects.None;
}
else
{
Visibility = Visibility.Visible;
e.Effects = DragDropEffects.Copy;
if (_dragStatus is DragStatus.Folder)
{
TitleText.Text = "Drop folder to add new game";
DescriptionText.Text = "Folder will be added to the directory selector";
}
else if (_dragStatus is DragStatus.File)
{
TitleText.Text = "Drop .usmap to import";
DescriptionText.Text = "Mapping file will be applied immediately";
}
}
e.Handled = true;
}
private void OnPreviewDragOver(object sender, DragEventArgs e)
{
e.Effects = _dragStatus is DragStatus.None ? DragDropEffects.None : DragDropEffects.Copy;
e.Handled = true;
}
private void OnPreviewDragLeave(object sender, DragEventArgs e)
{
Visibility = Visibility.Collapsed;
ResetState();
}
private async void OnDrop(object sender, DragEventArgs e)
{
Visibility = Visibility.Collapsed;
e.Handled = true;
switch (_dragStatus)
{
case DragStatus.Folder:
await Dispatcher.InvokeAsync(() => _applicationView.AddGameDirectory(_path));
break;
case DragStatus.File:
UserSettings.IsEndpointValid(EEndpointType.Mapping, out var oldMappingsEndpoint);
try
{
var newMappingsEndpoint = new EndpointSettings() { Overwrite = true, FilePath = _path };
UserSettings.Default.CurrentDir.Endpoints[(int) EEndpointType.Mapping] = newMappingsEndpoint;
await _applicationView.CUE4Parse.InitMappings();
_applicationView.SettingsView.MappingEndpoint = newMappingsEndpoint;
}
catch (Exception ex)
{
UserSettings.Default.CurrentDir.Endpoints[(int) EEndpointType.Mapping] = oldMappingsEndpoint;
FLogger.Append(ELog.Error, () =>
{
FLogger.Text($"Failed to load mapping file: {ex.Message}", Constants.WHITE, true);
});
}
break;
default:
break;
}
ResetState();
}
private void GetValidTarget(object sender, DragEventArgs e)
{
if (!_applicationView.Status.IsReady || !e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetData(DataFormats.FileDrop) is not string[] files)
return;
bool directorySelectorIsVisible = _applicationView.Status.Kind is EStatusKind.Configuring;
if (!directorySelectorIsVisible && (Helper.IsWindowOpen<DictionaryEditor>() || Helper.IsWindowOpen<EndpointEditor>()))
{
_applicationView.Status.SetStatus(EStatusKind.Configuring);
ResetState();
return;
}
switch (sender)
{
case MainWindow or SettingsView when !directorySelectorIsVisible:
foreach (var path in files)
{
if (Directory.Exists(path))
{
_path = path;
_dragStatus = DragStatus.Folder;
return;
}
else if (File.Exists(path) && Path.GetExtension(path).Equals(".usmap", StringComparison.OrdinalIgnoreCase))
{
_path = path;
_dragStatus = DragStatus.File;
return;
}
}
break;
case DirectorySelector:
if (files.FirstOrDefault(f => Directory.Exists(f)) is { } folder)
{
_path = folder;
_dragStatus = DragStatus.Folder;
return;
}
break;
default:
break;
}
ResetState();
}
}

View File

@ -1,106 +0,0 @@
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using FModel.Services;
using FModel.Settings;
using FModel.ViewModels;
namespace FModel.Views.Resources.Controls;
public partial class UsmapDropOverlay : UserControl
{
private ApplicationViewModel _applicationView => ApplicationService.ApplicationView;
private bool _isDraggingUsmap = false;
public UsmapDropOverlay()
{
InitializeComponent();
Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
var window = Window.GetWindow(this);
if (window is null)
return;
window.PreviewDragEnter += OnPreviewDragEnter;
window.PreviewDragOver += OnPreviewDragOver;
window.PreviewDragLeave += OnPreviewDragLeave;
window.Drop += OnDrop;
}
private void OnPreviewDragEnter(object sender, DragEventArgs e)
{
_isDraggingUsmap = CheckIsUsmap(e);
if (_isDraggingUsmap)
{
Visibility = Visibility.Visible;
e.Effects = DragDropEffects.Copy;
}
else
{
e.Effects = DragDropEffects.None;
}
e.Handled = true;
}
private void OnPreviewDragOver(object sender, DragEventArgs e)
{
if (!_isDraggingUsmap)
{
e.Effects = DragDropEffects.None;
e.Handled = true;
}
else
{
e.Effects = DragDropEffects.Copy;
e.Handled = true;
return;
}
}
private void OnPreviewDragLeave(object sender, DragEventArgs e) =>
Visibility = Visibility.Collapsed;
private async void OnDrop(object sender, DragEventArgs e)
{
Visibility = Visibility.Collapsed;
if (!e.Data.GetDataPresent(DataFormats.FileDrop))
return;
var files = (string[]) e.Data.GetData(DataFormats.FileDrop);
var usmapFile = files.FirstOrDefault(file => Path.GetExtension(file).Equals(".usmap", StringComparison.OrdinalIgnoreCase));
if (usmapFile is null)
return;
UserSettings.IsEndpointValid(EEndpointType.Mapping, out var oldMappingsEndpoint);
try
{
var newMappingsEndpoint = new EndpointSettings() { Overwrite = true, FilePath = usmapFile };
UserSettings.Default.CurrentDir.Endpoints[(int) EEndpointType.Mapping] = newMappingsEndpoint;
await _applicationView.CUE4Parse.InitMappings();
_applicationView.SettingsView.MappingEndpoint = newMappingsEndpoint;
}
catch (Exception ex)
{
UserSettings.Default.CurrentDir.Endpoints[(int) EEndpointType.Mapping] = oldMappingsEndpoint;
FLogger.Append(ELog.Error, () =>
{
FLogger.Text($"Failed to load mapping file: {ex.Message}", Constants.WHITE, true);
});
}
}
private bool CheckIsUsmap(DragEventArgs e)
{
if (!e.Data.GetDataPresent(DataFormats.FileDrop))
return false;
var files = (string[]) e.Data.GetData(DataFormats.FileDrop);
return _applicationView.Status.IsReady && files.Any(f => Path.GetExtension(f).Equals(".usmap", StringComparison.OrdinalIgnoreCase));
}
}

View File

@ -702,8 +702,8 @@
HorizontalAlignment="Right" VerticalAlignment="Bottom" Content="OK" Click="OnClick" />
</Grid>
</Border>
<controls:UsmapDropOverlay Grid.RowSpan="99"
Grid.ColumnSpan="99"
Panel.ZIndex="1000" />
<controls:DropOverlay Grid.RowSpan="99"
Grid.ColumnSpan="99"
Panel.ZIndex="1000" />
</Grid>
</adonisControls:AdonisWindow>

View File

@ -155,7 +155,11 @@ public partial class SettingsView
private void OpenCustomVersions(object sender, RoutedEventArgs e)
{
var editor = new DictionaryEditor(_applicationView.SettingsView.SelectedCustomVersions, "Versioning Configuration (Custom Versions)");
if (_applicationView.Status.IsReady)
_applicationView.Status.SetStatus(EStatusKind.Configuring);
var result = editor.ShowDialog();
if (_applicationView.Status.IsReady)
_applicationView.Status.SetStatus(EStatusKind.Ready);
if (!result.HasValue || !result.Value)
return;
@ -165,7 +169,11 @@ public partial class SettingsView
private void OpenOptions(object sender, RoutedEventArgs e)
{
var editor = new DictionaryEditor(_applicationView.SettingsView.SelectedOptions, "Versioning Configuration (Options)");
if (_applicationView.Status.IsReady)
_applicationView.Status.SetStatus(EStatusKind.Configuring);
var result = editor.ShowDialog();
if (_applicationView.Status.IsReady)
_applicationView.Status.SetStatus(EStatusKind.Ready);
if (!result.HasValue || !result.Value)
return;
@ -175,7 +183,11 @@ public partial class SettingsView
private void OpenMapStructTypes(object sender, RoutedEventArgs e)
{
var editor = new DictionaryEditor(_applicationView.SettingsView.SelectedMapStructTypes, "Versioning Configuration (MapStructTypes)");
if (_applicationView.Status.IsReady)
_applicationView.Status.SetStatus(EStatusKind.Configuring);
var result = editor.ShowDialog();
if (_applicationView.Status.IsReady)
_applicationView.Status.SetStatus(EStatusKind.Ready);
if (!result.HasValue || !result.Value)
return;
@ -186,14 +198,22 @@ public partial class SettingsView
{
var editor = new EndpointEditor(
_applicationView.SettingsView.AesEndpoint, "Endpoint Configuration (AES)", EEndpointType.Aes);
if (_applicationView.Status.IsReady)
_applicationView.Status.SetStatus(EStatusKind.Configuring);
editor.ShowDialog();
if (_applicationView.Status.IsReady)
_applicationView.Status.SetStatus(EStatusKind.Ready);
}
private void OpenMappingEndpoint(object sender, RoutedEventArgs e)
{
var editor = new EndpointEditor(
_applicationView.SettingsView.MappingEndpoint, "Endpoint Configuration (Mapping)", EEndpointType.Mapping);
if (_applicationView.Status.IsReady)
_applicationView.Status.SetStatus(EStatusKind.Configuring);
editor.ShowDialog();
if (_applicationView.Status.IsReady)
_applicationView.Status.SetStatus(EStatusKind.Ready);
}
private void CriwareKeyBox_Loaded(object sender, RoutedEventArgs e)