-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileDialogService.cs
194 lines (180 loc) · 7.81 KB
/
FileDialogService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
using BannerlordImageTool.Win.Common;
using CommunityToolkit.WinUI.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Vanara.PInvoke;
using Windows.Storage;
using Windows.Storage.AccessCache;
using Windows.Storage.Pickers;
namespace BannerlordImageTool.Win.Services;
public interface IFileDialogService
{
Task<StorageFolder> OpenFolder(Guid stateGuid);
Task<StorageFile> OpenFile(Guid stateGuid, FileType[] fileTypes);
Task<StorageFile> OpenFile(Guid stateGuid, string suggestedPath, FileType[] fileTypes);
Task<IReadOnlyList<StorageFile>> OpenFiles(Guid stateGuid, FileType[] fileTypes);
string SaveFile(Guid stateGuid, FileType[] fileTypes, string suggestedFileName = null, string overwritingFilePath = null);
}
public class FileDialogService : IFileDialogService
{
public async Task<StorageFolder> OpenFolder(Guid stateGuid)
{
return await NativeHelpers.RunCom(async () => {
var ofd = CreateFileOpenDialog(stateGuid, Shell32.FILEOPENDIALOGOPTIONS.FOS_PICKFOLDERS);
if (IsUserCancelled(ofd.Show(NativeHelpers.GetHwnd())))
{
// User closes the dialog by clicking "Cancel".
return null;
}
var selectedFolder = ofd.GetFolder();
var path = selectedFolder.GetDisplayName(Shell32.SIGDN.SIGDN_FILESYSPATH);
if (string.IsNullOrEmpty(path))
{
throw new InvalidOperationException("failed to get the selected folder's path");
}
var folder = await StorageFolder.GetFolderFromPathAsync(path);
if (folder is not null)
{
StorageApplicationPermissions.FutureAccessList.AddOrReplace(stateGuid.ToString(), folder);
}
return folder;
});
}
public async Task<StorageFile> OpenFile(Guid stateGuid, FileType[] fileTypes)
{
return await OpenFile(stateGuid, null, fileTypes);
}
public async Task<StorageFile> OpenFile(Guid stateGuid, string suggestedPath, FileType[] fileTypes)
{
return await NativeHelpers.RunCom(async () => {
var fd = CreateFileOpenDialog(stateGuid);
fd.SetFileTypes((uint)fileTypes.Length, fileTypes.Select(ft => ft.ToFilterSpec()).ToArray());
// Locate the suggested file if exists
if (ParseFilePath(suggestedPath, out var dir, out var fileName))
{
var folderItem = Shell32.SHCreateItemFromParsingName<Shell32.IShellItem>(dir);
fd.SetFolder(folderItem);
fd.SetFileName(fileName);
}
if (IsUserCancelled(fd.Show(NativeHelpers.GetHwnd())))
{
return null;
}
var path = fd.GetResult().GetDisplayName(Shell32.SIGDN.SIGDN_FILESYSPATH);
if (string.IsNullOrEmpty(path))
{
throw new InvalidOperationException("failed to get the file path");
}
var file = await StorageFile.GetFileFromPathAsync(path);
return file;
});
}
public async Task<IReadOnlyList<StorageFile>> OpenFiles(Guid stateGuid, FileType[] fileTypes)
{
return await NativeHelpers.RunCom(async () => {
var fd = CreateFileOpenDialog(stateGuid, Shell32.FILEOPENDIALOGOPTIONS.FOS_ALLOWMULTISELECT);
fd.SetFileTypes((uint)fileTypes.Length, fileTypes.Select(ft => ft.ToFilterSpec()).ToArray());
if (IsUserCancelled(fd.Show(NativeHelpers.GetHwnd())))
{
return null;
}
var results = fd.GetResults();
var count = results.GetCount();
var files = new StorageFile[count];
for (uint i = 0; i < count; i++)
{
var path = results.GetItemAt(i).GetDisplayName(Shell32.SIGDN.SIGDN_FILESYSPATH);
if (string.IsNullOrEmpty(path))
{
throw new InvalidOperationException($"failed to get the file path {path}");
}
files[i] = await StorageFile.GetFileFromPathAsync(path);
}
return files;
});
}
private Shell32.IFileOpenDialog CreateFileOpenDialog(Guid stateGuid, Shell32.FILEOPENDIALOGOPTIONS opts = 0)
{
var hr = Ole32.CoCreateInstance(typeof(Shell32.CFileOpenDialog).GUID,
null,
Ole32.CLSCTX.CLSCTX_INPROC_SERVER,
typeof(Shell32.IFileOpenDialog).GUID,
out var ppv);
if (hr != HRESULT.S_OK)
{
throw new HRESULTException(hr, "error in CoCreateInstance for a FileOpenDialog");
}
var fd = (Shell32.IFileOpenDialog)ppv;
fd.SetClientGuid(stateGuid);
fd.SetDefaultFolder(Shell32.KNOWNFOLDERID.FOLDERID_DocumentsLibrary.GetIShellItem());
fd.SetOptions(fd.GetOptions() | Shell32.FILEOPENDIALOGOPTIONS.FOS_FORCEFILESYSTEM | opts);
return fd;
}
private bool IsUserCancelled(HRESULT hr)
{
return hr == HRESULT.HRESULT_FROM_WIN32(Win32Error.ERROR_CANCELLED);
}
public string SaveFile(Guid stateGuid,
FileType[] fileTypes,
string suggestedFileName = "",
string overwritingFilePath = null)
{
return NativeHelpers.RunCom(() => {
var hr = Ole32.CoCreateInstance(typeof(Shell32.CFileSaveDialog).GUID,
null,
Ole32.CLSCTX.CLSCTX_INPROC_SERVER,
typeof(Shell32.IFileSaveDialog).GUID,
out var ppv);
if (hr != HRESULT.S_OK)
{
throw new HRESULTException(hr, "error in CoCreateInstance for a FileSaveDialog");
}
var fd = (Shell32.IFileSaveDialog)ppv;
fd.SetClientGuid(stateGuid);
fd.SetDefaultFolder(Shell32.KNOWNFOLDERID.FOLDERID_DocumentsLibrary.GetIShellItem());
fd.SetOptions(fd.GetOptions() | Shell32.FILEOPENDIALOGOPTIONS.FOS_FORCEFILESYSTEM);
if (fileTypes.Length > 0)
{
fd.SetDefaultExtension(fileTypes[0].Extension);
}
fd.SetFileTypes((uint)fileTypes.Length, fileTypes.Select(ft => ft.ToFilterSpec()).ToArray());
if (overwritingFilePath != null && ParseFilePath(overwritingFilePath, out var dir, out var fileName))
{
var folder = Shell32.SHCreateItemFromParsingName<Shell32.IShellItem>(dir);
fd.SetFolder(folder);
fd.SetFileName(fileName);
}
else if (!string.IsNullOrWhiteSpace(suggestedFileName))
{
var ext = Path.GetExtension(suggestedFileName).TrimStart('.');
fd.SetDefaultExtension(ext);
fd.SetFileName(Path.GetFileNameWithoutExtension(suggestedFileName));
}
if (IsUserCancelled(fd.Show(NativeHelpers.GetHwnd())))
{
return null;
}
return fd.GetResult().GetDisplayName(Shell32.SIGDN.SIGDN_FILESYSPATH);
});
}
private bool ParseFilePath(string filePath, out string dir, out string fileName)
{
dir = null;
fileName = null;
if (string.IsNullOrWhiteSpace(filePath))
{
return false;
}
var fullPath = Path.GetFullPath(filePath);
if (!File.Exists(filePath))
{
return false;
}
dir = Path.GetDirectoryName(fullPath);
fileName = Path.GetFileName(filePath);
return true;
}
}