Flow.Launcher/Plugins/Flow.Launcher.Plugin.Explorer/Views/RenameFile.xaml.cs

98 lines
2.8 KiB
C#
Raw Normal View History

2025-09-21 14:00:58 +00:00
using System;
using System.IO;
using System.Windows;
2025-06-22 20:45:42 +00:00
using System.Windows.Controls;
using System.Windows.Input;
2025-06-24 01:57:41 +00:00
using System.Windows.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
2025-06-22 19:41:52 +00:00
using Flow.Launcher.Plugin.Explorer.Helper;
namespace Flow.Launcher.Plugin.Explorer.Views
{
[INotifyPropertyChanged]
public partial class RenameFile : Window
{
public string NewFileName
{
2025-06-22 19:41:52 +00:00
get => _newFileName;
set
{
2025-06-22 19:41:52 +00:00
_ = SetProperty(ref _newFileName, value);
}
}
2025-06-22 19:41:52 +00:00
private string _newFileName;
2025-06-22 19:41:52 +00:00
private readonly string _oldFilePath;
2025-06-22 19:41:52 +00:00
private readonly FileSystemInfo _info;
2025-09-21 05:21:39 +00:00
public RenameFile(FileSystemInfo info)
{
2025-06-24 01:57:41 +00:00
_info = info;
_oldFilePath = _info.FullName;
NewFileName = _info.Name;
InitializeComponent();
ShowInTaskbar = false;
2025-06-24 01:57:41 +00:00
RenameTb.Focus();
2025-09-21 14:00:58 +00:00
KeyDown += (s, e) =>
2025-06-25 17:37:01 +00:00
{
if (e.Key == Key.Escape)
{
Close();
}
};
}
2025-06-25 14:04:40 +00:00
2025-06-24 01:57:41 +00:00
/// <summary>
/// https://stackoverflow.com/a/59560352/24045055
/// </summary>
private async void SelectAll_OnTextBoxGotFocus(object sender, RoutedEventArgs e)
{
2025-06-25 14:04:40 +00:00
if (sender is not TextBox textBox) return;
2025-06-24 01:57:41 +00:00
if (_info is DirectoryInfo)
{
await textBox.Dispatcher.InvokeAsync(textBox.SelectAll, DispatcherPriority.Background);
return;
2025-06-24 01:57:41 +00:00
}
// select everything but the extension
if (_info is FileInfo info)
2025-06-24 01:57:41 +00:00
{
string properName = Path.GetFileNameWithoutExtension(info.Name);
int start = textBox.Text.LastIndexOf(properName, StringComparison.OrdinalIgnoreCase);
if (start < 0)
{
await textBox.Dispatcher.InvokeAsync(textBox.SelectAll, DispatcherPriority.Background);
return;
}
await textBox.Dispatcher.InvokeAsync(() => textBox.Select(start, properName.Length), DispatcherPriority.Background);
2025-06-24 01:57:41 +00:00
}
}
2025-06-25 14:04:40 +00:00
2025-06-25 17:37:01 +00:00
private void OnDoneButtonClick(object sender, RoutedEventArgs e)
{
2025-09-21 05:21:39 +00:00
RenameThing.Rename(NewFileName, _info);
// Close the dialog no matter if it worked or not because error messages are popped up in RenameThing
2025-06-22 19:41:52 +00:00
Close();
}
private void BtnCancel(object sender, RoutedEventArgs e)
{
Close();
}
2025-06-22 19:41:52 +00:00
private void RenameTb_OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
btnDone.Focus();
OnDoneButtonClick(sender, e);
e.Handled = true;
}
}
}
}