Skip to content

Commit

Permalink
Merge pull request #2740 from cwensley/curtis/mac-fix-double-file-ext…
Browse files Browse the repository at this point in the history
…ension-in-savefiledialog

Mac: Fix double extension for unknown file types
  • Loading branch information
cwensley authored Feb 5, 2025
2 parents 1b425ff + 7c1075a commit cdd341d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
26 changes: 22 additions & 4 deletions src/Eto.Mac/Forms/SaveFileDialogHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ protected override void Initialize()

public override DialogResult ShowDialog(Window parent)
{
hasShown = true;
var result = base.ShowDialog(parent);
if (result == DialogResult.Ok)
{
selectedFileName = null;
hasShown = true;
}

return result;
Expand All @@ -54,12 +54,30 @@ public override DialogResult ShowDialog(Window parent)
protected override void OnFileTypeChanged()
{
base.OnFileTypeChanged();
var extension = Widget.CurrentFilter?.Extensions?.FirstOrDefault()?.TrimStart('*', '.');
if (!string.IsNullOrEmpty(extension))
var extensions = Widget.CurrentFilter?.Extensions;
if (extensions == null)
return;

var currentExtension = Path.GetExtension(Control.NameFieldStringValue);

// If the new file type supports the extension, don't change it
if (extensions.Select(r => r.TrimStart('*')).Any(r => r == currentExtension))
{
if (!hasShown)
{
// need to reset the value, otherwise for unknown file types it doubles up the extension
var name = Control.NameFieldStringValue;
Control.NameFieldStringValue = string.Empty;
Control.NameFieldStringValue = name;
}
return;
}
var newExtension = extensions.FirstOrDefault()?.TrimStart('*', '.');
if (!string.IsNullOrEmpty(newExtension))
{
var fileName = Control.NameFieldStringValue;
if (fileName != null)
Control.NameFieldStringValue = $"{Path.GetFileNameWithoutExtension(fileName)}.{extension}";
Control.NameFieldStringValue = $"{Path.GetFileNameWithoutExtension(fileName)}.{newExtension}";
}
}
}
Expand Down
13 changes: 13 additions & 0 deletions test/Eto.Test/UnitTests/Forms/FileDialogTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,19 @@ public class OpenFileDialogTests : FileDialogTests<OpenFileDialog>
[TestFixture]
public class SaveFileDialogTests : FileDialogTests<SaveFileDialog>
{
[Test, ManualTest, InvokeOnUI]
public void FileNameShouldNotHaveDoubleExtension()
{
// this can only be replicated on macOS when the extension is unknown
// and we set the filename first
var fd = new SaveFileDialog();
fd.FileName = "NoDoubleExt.eto";
fd.Directory = new Uri(EtoEnvironment.GetFolderPath(EtoSpecialFolder.Downloads));
fd.Filters.Clear();
fd.Filters.Add(new FileFilter("ETO Files", ".eto"));
fd.Filters.Add(new FileFilter("Text Files", ".txt"));
fd.ShowDialog(null);
}
}

public class FileDialogTests<T> : TestBase
Expand Down

0 comments on commit cdd341d

Please sign in to comment.