-
Notifications
You must be signed in to change notification settings - Fork 0
/
AssetFolderSynchronizer.cs
282 lines (245 loc) · 7.74 KB
/
AssetFolderSynchronizer.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FlaxEditor.Content;
using FlaxEditor.Utilities;
using FlaxEngine;
namespace ResourcesPlugin.Source.Editor
{
/// <summary>
/// Keeps 2 folders in sync (raw assets and imported assets)
///
/// TODO: It only cares about the files. It doesn't delete folders.
/// </summary>
public class AssetFolderSynchronizer : IDisposable
{
private FlaxEditor.Editor _editor;
private FileSystemEventBuffer _eventBuffer = new FileSystemEventBuffer();
private FileSystemWatcher _fileSystemWatcher;
public AssetFolderSynchronizer(string assetsPath, string importedAssetsPath, FlaxEditor.Editor editor)
{
AssetsPath = Path.GetFullPath(assetsPath);
ImportedAssetsPath = Path.GetFullPath(importedAssetsPath);
_editor = editor;
// Check if imported assets are in the content folder
if (!ImportedAssetsPath.StartsWith(Path.GetFullPath(_editor.ContentDatabase.ProjectContent.Path)))
{
throw new ArgumentException("Imported assets need to end up in the content folder", nameof(importedAssetsPath));
}
// Make sure that the directories exists
if (!Directory.Exists(AssetsPath))
{
Directory.CreateDirectory(AssetsPath);
}
if (!Directory.Exists(ImportedAssetsPath))
{
Directory.CreateDirectory(ImportedAssetsPath);
_editor.ContentDatabase.RefreshFolder(_editor.ContentDatabase.ProjectContent.Folder, true);
}
// Get the imported assets folder
ImportedAssetsContentFolder = _editor.ContentDatabase.Find(importedAssetsPath) as ContentFolder;
SynchronizeFolders();
FileSystemWatcherSetup();
}
public string AssetsPath { get; }
public string ImportedAssetsPath { get; }
public ContentFolder ImportedAssetsContentFolder { get; }
public string RawAssetToImportedPath(string assetPath)
{
assetPath = Path.GetFullPath(assetPath);
// Get the "relative" path of the asset
var relativeAssetPath = assetPath.Replace(AssetsPath, "").TrimStart(new char[] { '\\', '/' });
// Get the new path
var importedPath = Path.Combine(ImportedAssetsPath, relativeAssetPath);
// Remember to change the extension
// Because of this, it's not trivially possible to get back the original path
importedPath = Path.ChangeExtension(importedPath, ".flax");
return importedPath;
}
private ContentFolder GetOrCreateContentFolder(string path)
{
path = Path.GetDirectoryName(Path.GetFullPath(path));
Directory.CreateDirectory(path);
// TODO: Optimize this:
_editor.ContentDatabase.RefreshFolder(ImportedAssetsContentFolder, true);
return _editor.ContentDatabase.Find(path) as ContentFolder;
}
/// <summary>
/// Fully re-synchronizes the 2 folders
/// </summary>
private void SynchronizeFolders()
{
if (string.IsNullOrEmpty(ImportedAssetsPath) || string.IsNullOrEmpty(AssetsPath)) return;
// Delete the imported files that don't have an asset anymore
foreach (var importedFile in ImportedAssetsContentFolder.GetChildrenRecursive())
{
// TODO: Optimize this?
if (importedFile is BinaryAssetItem binaryAssetItem)
{
binaryAssetItem.GetImportPath(out string importPath);
bool hasSource = !string.IsNullOrEmpty(importPath) && File.Exists(importPath);
if (!hasSource)
{
_editor.ContentDatabase.Delete(binaryAssetItem);
}
}
}
// (Re)import the changed ones
foreach (string rawAssetPath in GetFilesRecursive(AssetsPath))
{
string importedPath = RawAssetToImportedPath(rawAssetPath);
// If it hasn't been imported, do it
if (!File.Exists(importedPath))
{
RawAssetCreated(rawAssetPath);
}
else
{
// If it's newer, reimport it
FileInfo rawAssetInfo = new FileInfo(rawAssetPath);
FileInfo importedAssetInfo = new FileInfo(importedPath);
if (rawAssetInfo.LastWriteTime > importedAssetInfo.LastWriteTime)
{
RawAssetChanged(rawAssetPath);
}
}
}
}
private void FileSystemWatcherSetup()
{
// Create the watcher
_fileSystemWatcher = new FileSystemWatcher
{
Path = AssetsPath,
NotifyFilter = NotifyFilters.LastWrite,
Filter = "*.*",
IncludeSubdirectories = true,
InternalBufferSize = 8192 // Something large, the max is 65536
};
// Hook up the watcher events
_fileSystemWatcher.Created += _eventBuffer.ChangeEvent;
_fileSystemWatcher.Changed += _eventBuffer.ChangeEvent;
_fileSystemWatcher.Renamed += _eventBuffer.ChangeEvent;
_fileSystemWatcher.Deleted += _eventBuffer.ChangeEvent;
_fileSystemWatcher.Error += FileSystemWatcherError;
// Hook up the buffer events
_eventBuffer.Created += RawAssetCreated;
_eventBuffer.Changed += RawAssetChanged;
_eventBuffer.Deleted += RawAssetDeleted;
// Enable both of them
_fileSystemWatcher.EnableRaisingEvents = true;
_eventBuffer.Enabled = true;
}
private void RawAssetCreated(string assetPath)
{
string importedPath = RawAssetToImportedPath(assetPath);
var newContentFolder = GetOrCreateContentFolder(importedPath);
if (File.Exists(importedPath))
{
_editor.ContentImporting.Import(assetPath, newContentFolder, true);
}
else
{
_editor.Windows.MainWindow.BringToFront();
_editor.ContentImporting.Import(assetPath, newContentFolder);
}
}
private void RawAssetChanged(string assetPath)
{
//TODO: Ignore directory changes?? (not sure about this)
//if (Directory.Exists(assetPath)) return;
if (Directory.Exists(assetPath))
{
Debug.Log(assetPath);
}
RawAssetCreated(assetPath);
}
private void RawAssetDeleted(string assetPath)
{
string importedPath = RawAssetToImportedPath(assetPath);
var item = _editor.ContentDatabase.Find(importedPath) as BinaryAssetItem;
if (item != null)
{
_editor.ContentDatabase.Delete(item);
}
}
private void FileSystemWatcherError(object sender, ErrorEventArgs e)
{
Debug.Log("File System Watcher Error: " + e.GetException());
}
// From https://stackoverflow.com/a/929418/3492994
private static IEnumerable<string> GetFilesRecursive(string path)
{
Queue<string> queue = new Queue<string>();
queue.Enqueue(path);
while (queue.Count > 0)
{
path = queue.Dequeue();
try
{
foreach (string subDir in Directory.GetDirectories(path))
{
queue.Enqueue(subDir);
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
string[] files = null;
try
{
files = Directory.GetFiles(path);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
if (files != null)
{
for (int i = 0; i < files.Length; i++)
{
yield return files[i];
}
}
}
}
#region IDisposable Support
private bool _disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
// File System Watcher Disposing
if (_fileSystemWatcher != null)
{
_fileSystemWatcher.Created -= _eventBuffer.ChangeEvent;
_fileSystemWatcher.Changed -= _eventBuffer.ChangeEvent;
_fileSystemWatcher.Renamed -= _eventBuffer.ChangeEvent;
_fileSystemWatcher.Deleted -= _eventBuffer.ChangeEvent;
_fileSystemWatcher.Error -= FileSystemWatcherError;
}
_fileSystemWatcher?.Dispose();
// Event Buffer Disposing
_eventBuffer.Created -= RawAssetCreated;
_eventBuffer.Changed -= RawAssetChanged;
_eventBuffer.Deleted -= RawAssetDeleted;
_eventBuffer.Dispose();
}
_disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
}
#endregion IDisposable Support
}
}