-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathAssetCollectionViewModel.cs
More file actions
1761 lines (1504 loc) · 76.5 KB
/
AssetCollectionViewModel.cs
File metadata and controls
1761 lines (1504 loc) · 76.5 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System.Collections.Specialized;
using System.IO;
using System.Threading.Tasks.Dataflow;
using Stride.Core;
using Stride.Core.Annotations;
using Stride.Core.Assets.Analysis;
using Stride.Core.Assets.Editor.Components.AddAssets;
using Stride.Core.Assets.Editor.Components.Properties;
using Stride.Core.Assets.Editor.Components.TemplateDescriptions;
using Stride.Core.Assets.Editor.Components.TemplateDescriptions.ViewModels;
using Stride.Core.Assets.Editor.Services;
using Stride.Core.Assets.Editor.Settings;
using Stride.Core.Assets.Editor.View.Behaviors;
using Stride.Core.Assets.Editor.ViewModel.Progress;
using Stride.Core.Assets.Templates;
using Stride.Core.Assets.Tracking;
using Stride.Core.Diagnostics;
using Stride.Core.Extensions;
using Stride.Core.IO;
using Stride.Core.Presentation.Collections;
using Stride.Core.Presentation.Commands;
using Stride.Core.Presentation.Core;
using Stride.Core.Presentation.Dirtiables;
using Stride.Core.Presentation.Interop;
using Stride.Core.Presentation.Services;
using Stride.Core.Presentation.ViewModels;
using Stride.Core.Presentation.Windows;
using Stride.Core.Translation;
namespace Stride.Core.Assets.Editor.ViewModel
{
public enum DisplayAssetMode
{
AssetInSelectedFolderOnly,
AssetInSelectedFolderAndSubFolder,
AssetAndFolderInSelectedFolder,
}
public enum FilterCategory
{
AssetName,
AssetTag,
AssetType,
}
public enum SortRule
{
Name,
TypeOrderThenName,
DirtyThenName,
ModificationDateThenName,
}
public sealed class AssetCollectionViewModel : DispatcherViewModel, IAddChildViewModel
{
public sealed class AssetFilterViewModel : DispatcherViewModel, IEquatable<AssetFilterViewModel>
{
private readonly AssetCollectionViewModel collection;
private bool isActive;
private bool isReadOnly;
public AssetFilterViewModel([NotNull] AssetCollectionViewModel collection, FilterCategory category, [NotNull] string filter, string displayName)
: base(collection.SafeArgument(nameof(collection)).ServiceProvider)
{
this.collection = collection;
Category = category;
DisplayName = displayName;
Filter = filter ?? throw new ArgumentNullException(nameof(filter));
isActive = true;
RemoveFilterCommand = new AnonymousCommand<AssetFilterViewModel>(ServiceProvider, collection.RemoveAssetFilter);
ToggleIsActiveCommand = new AnonymousCommand(ServiceProvider, () => { IsActive = !IsActive; collection.SaveAssetFilters(); });
}
public FilterCategory Category { get; }
public string DisplayName { get; }
public string Filter { get; }
public bool IsActive { get => isActive; set => SetValue(ref isActive, value, collection.RefreshFilters); }
public bool IsReadOnly
{
get => isReadOnly;
set
{
SetValue(ref isReadOnly, value, () =>
{
RemoveFilterCommand.IsEnabled = !value;
ToggleIsActiveCommand.IsEnabled = !value;
});
}
}
public ICommandBase RemoveFilterCommand { get; }
public ICommandBase ToggleIsActiveCommand { get; }
public bool Match(AssetViewModel asset)
{
switch (Category)
{
case FilterCategory.AssetName:
return ComputeTokens(Filter).All(x => asset.Name.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0);
case FilterCategory.AssetTag:
return asset.Tags.Any(y => y.IndexOf(Filter, StringComparison.OrdinalIgnoreCase) >= 0);
case FilterCategory.AssetType:
return string.Equals(asset.AssetType.FullName, Filter);
}
return false;
}
public bool Equals(AssetFilterViewModel other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Category == other.Category && string.Equals(Filter, other.Filter, StringComparison.OrdinalIgnoreCase);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return Equals(obj as AssetFilterViewModel);
}
public override int GetHashCode()
{
unchecked
{
return ((int)Category * 397) ^ StringComparer.OrdinalIgnoreCase.GetHashCode(Filter);
}
}
public static bool operator ==(AssetFilterViewModel left, AssetFilterViewModel right)
{
return Equals(left, right);
}
public static bool operator !=(AssetFilterViewModel left, AssetFilterViewModel right)
{
return !Equals(left, right);
}
}
[DataContract(nameof(AssetFilterViewModelData))]
public sealed class AssetFilterViewModelData
{
public string DisplayName = "";
public string Filter = "";
public bool IsActive = false;
public FilterCategory category = FilterCategory.AssetName;
}
// Storing out primitive data for filters to save between instances of editor
private List<AssetFilterViewModelData> StoredListData = InternalSettings.ViewFilters.GetValue();
public static readonly IEnumerable<FilterCategory> AllFilterCategories = Enum.GetValues(typeof(FilterCategory)).Cast<FilterCategory>();
private readonly ObservableSet<AssetViewModel> assets = new ObservableSet<AssetViewModel>();
// /!\ FIXME: we need to rework that as we probably don't need that many lists
private readonly ObservableList<AssetViewModel> filteredAssets = new ObservableList<AssetViewModel>();
private readonly ObservableList<object> filteredContent = new ObservableList<object>();
/// <remarks>
/// <see cref="selectedAssets"/> is a sub-collection of <see cref="selectedContent"/>. It should always be read from and never directly updated, except in <see cref="SelectedContentCollectionChanged"/>.
/// </remarks>
private readonly ObservableList<AssetViewModel> selectedAssets = new ObservableList<AssetViewModel>();
/// <summary>
/// List of all selected items (e.g. in the asset view).
/// </summary>
private readonly ObservableList<object> selectedContent = new ObservableList<object>();
private object singleSelectedContent;
private readonly Lazy<AddAssetTemplateCollectionViewModel> addAssetTemplateCollection;
private readonly List<AssetFilterViewModel> typeFilters = new List<AssetFilterViewModel>();
private readonly Dictionary<FilterCategory, bool> availableFilterCategories;
private readonly ObservableList<AssetFilterViewModel> availableAssetFilters = new ObservableList<AssetFilterViewModel>();
private readonly ObservableSet<AssetFilterViewModel> currentAssetFilters = new ObservableSet<AssetFilterViewModel>();
private string assetFilterPattern;
private Func<AssetViewModel, bool> customFilter;
private readonly IAssetDependencyManager dependencyManager;
private readonly HashSet<DirectoryBaseViewModel> monitoredDirectories = new HashSet<DirectoryBaseViewModel>();
private readonly SessionObjectPropertiesViewModel assetProperties;
private DisplayAssetMode displayMode = InternalSettings.AssetViewDisplayMode.GetValue();
private SortRule sortRule = InternalSettings.AssetViewSortRule.GetValue();
private bool discardSelectionChanges;
private bool refreshing;
private IEnumerable<TemplateDescriptionViewModel> lastMatchingTemplates;
private readonly FuncClipboardMonitor<bool> pasteMonitor = new FuncClipboardMonitor<bool>();
public AssetCollectionViewModel([NotNull] IViewModelServiceProvider serviceProvider, [NotNull] SessionViewModel session, [NotNull] IEnumerable<FilterCategory> filterCategories, SessionObjectPropertiesViewModel assetProperties = null)
: base(serviceProvider)
{
refreshing = true;
Session = session ?? throw new ArgumentNullException(nameof(session));
dependencyManager = Session.DependencyManager;
this.assetProperties = assetProperties;
addAssetTemplateCollection = new Lazy<AddAssetTemplateCollectionViewModel>(() => new AddAssetTemplateCollectionViewModel(session));
typeFilters.AddRange(AssetRegistry.GetPublicTypes().Where(type => type != typeof(Package)).Select(type => new AssetFilterViewModel(this, FilterCategory.AssetType, type.FullName, DisplayAttribute.GetDisplayName(type))));
typeFilters.Sort((a, b) => string.Compare(a.DisplayName, b.DisplayName, StringComparison.InvariantCultureIgnoreCase));
availableFilterCategories = AllFilterCategories.ToDictionary(f => f, f => false);
foreach (var cat in filterCategories)
{
availableFilterCategories[cat] = true;
}
ChangeDisplayAssetModeCommand = new AnonymousCommand<DisplayAssetMode>(serviceProvider, x => { DisplayAssetMode = x; });
SortAssetsCommand = new AnonymousCommand<SortRule>(serviceProvider, x => { SortRule = x; UpdateCommands(); });
SelectAssetCommand = new AnonymousCommand<AssetViewModel>(serviceProvider, x => SelectAssets(x.Yield()));
DeleteContentCommand = new AnonymousTaskCommand(serviceProvider, () => DeleteContent(SelectedContent));
RunAssetTemplateCommand = new AnonymousTaskCommand<ITemplateDescriptionViewModel>(serviceProvider, x => RunAssetTemplate(x, null));
SelectFilesToCreateAssetCommand = new AnonymousTaskCommand(serviceProvider, SelectFilesToCreateAsset);
ShowAddAssetDialogCommand = new AnonymousTaskCommand(serviceProvider, ShowAddAssetDialog);
CutLocationsCommand = new AnonymousTaskCommand(serviceProvider, CutSelectedLocations, CanCopy);
CopyLocationsCommand = new AnonymousTaskCommand(serviceProvider, CopySelectedLocations, CanCopy);
CutContentCommand = new AnonymousTaskCommand(serviceProvider, CutSelectedContent, CanCopy);
CopyContentCommand = new AnonymousTaskCommand(serviceProvider, CopySelectedContent, CanCopy);
CopyAssetsRecursivelyCommand = new AnonymousTaskCommand(serviceProvider, CopySelectedAssetsRecursively, CanCopy);
CopyAssetUrlCommand = new AnonymousCommand(ServiceProvider, CopyAssetUrl);
PasteCommand = new AnonymousTaskCommand(serviceProvider, Paste, () => pasteMonitor.Get(CanPaste));
AddAssetFilterCommand = new AnonymousCommand<AssetFilterViewModel>(serviceProvider, AddAssetFilter);
ClearAssetFiltersCommand = new AnonymousCommand(serviceProvider, ClearAssetFilters);
RefreshAssetFilterCommand = new AnonymousCommand<AssetFilterViewModel>(serviceProvider, RefreshAssetFilter);
currentAssetFilters.CollectionChanged += (s, e) => RefreshFilters();
SelectedLocations.CollectionChanged += SelectedLocationCollectionChanged;
filteredAssets.CollectionChanged += FilteredAssetsCollectionChanged;
selectedContent.CollectionChanged += SelectedContentCollectionChanged;
LoadAssetFilters();
refreshing = false;
DependentProperties.Add(nameof(DisplayAssetMode), new[] { nameof(DisplayLocationContentRecursively) });
DependentProperties.Add(nameof(SingleSelectedContent), new[] { nameof(SingleSelectedAsset) });
}
public SessionViewModel Session { get; }
public IReadOnlyObservableCollection<AssetViewModel> Assets => assets;
public int AssetCount => assets.Count;
// FIXME: this property was added because for some reason DataGridEx has a lot of issues when displaying both assets and folders
[Obsolete("Should not be used except by AssetViewUserControl GridView")]
public IReadOnlyObservableCollection<AssetViewModel> FilteredAssets => filteredAssets;
public IReadOnlyObservableCollection<object> FilteredContent => filteredContent;
public IReadOnlyCollection<AssetFilterViewModel> TypeFilters => typeFilters;
public IReadOnlyObservableCollection<AssetFilterViewModel> AvailableAssetFilters => availableAssetFilters;
public IReadOnlyObservableCollection<AssetFilterViewModel> CurrentAssetFilters => currentAssetFilters;
public string AssetFilterPattern { get => assetFilterPattern; set { SetValue(ref assetFilterPattern, value, () => UpdateAvailableAssetFilters(value)); } }
public Func<AssetViewModel, bool> CustomFilter { get => customFilter; set => SetValue(ref customFilter, value, RefreshFilters); }
public DisplayAssetMode DisplayAssetMode { get => displayMode; private set => SetValue(ref displayMode, value, UpdateLocations); }
public SortRule SortRule { get => sortRule; private set => SetValue(ref sortRule, value, RefreshFilters); }
public IReadOnlyObservableCollection<AssetViewModel> SelectedAssets => selectedAssets;
public IReadOnlyObservableCollection<object> SelectedContent => selectedContent;
public PackageViewModel SelectedAssetsPackage { get { var p = SelectedAssets.Select(x => x.Directory.Package).Distinct().ToArray(); return p.Length == 1 ? p[0] : null; } }
/// <summary>
/// List of selected locations (in the solution explorer).
/// </summary>
[NotNull]
public ObservableList<object> SelectedLocations { get; } = new ObservableList<object>();
public bool DisplayLocationContentRecursively => DisplayAssetMode == DisplayAssetMode.AssetInSelectedFolderAndSubFolder;
public object SingleSelectedContent { get => singleSelectedContent; private set => SetValue(ref singleSelectedContent, value); }
[CanBeNull]
public AssetViewModel SingleSelectedAsset => SingleSelectedContent as AssetViewModel;
public AddAssetTemplateCollectionViewModel AddAssetTemplateCollection => addAssetTemplateCollection.Value;
[NotNull]
public IEnumerable<IDirtiable> Dirtiables => Enumerable.Empty<IDirtiable>();
[NotNull]
public IEditorDialogService Dialogs => ServiceProvider.Get<IEditorDialogService>();
public IEnumerable<TemplateDescriptionViewModel> LastMatchingTemplates { get => lastMatchingTemplates; set => SetValue(ref lastMatchingTemplates, value); }
[NotNull]
public ICommandBase ChangeDisplayAssetModeCommand { get; }
[NotNull]
public ICommandBase SortAssetsCommand { get; }
[NotNull]
public ICommandBase SelectAssetCommand { get; }
[NotNull]
public ICommandBase DeleteContentCommand { get; }
[NotNull]
public ICommandBase RunAssetTemplateCommand { get; }
[NotNull]
public ICommandBase SelectFilesToCreateAssetCommand { get; }
[NotNull]
public ICommandBase ShowAddAssetDialogCommand { get; }
[NotNull]
public ICommandBase CutLocationsCommand { get; }
[NotNull]
public ICommandBase CopyLocationsCommand { get; }
[NotNull]
public ICommandBase CutContentCommand { get; }
[NotNull]
public ICommandBase CopyContentCommand { get; }
[NotNull]
public ICommandBase CopyAssetsRecursivelyCommand { get; }
[NotNull]
public ICommandBase CopyAssetUrlCommand { get; }
[NotNull]
public ICommandBase PasteCommand { get; }
[NotNull]
public ICommandBase AddAssetFilterCommand { get; }
[NotNull]
public ICommandBase ClearAssetFiltersCommand { get; }
[NotNull]
public ICommandBase RefreshAssetFilterCommand { get; }
public void ClearSelection()
{
selectedContent.Clear();
}
public void SelectAssets([ItemNotNull, NotNull] IEnumerable<AssetViewModel> assetsToSelect)
{
Dispatcher.EnsureAccess();
var assetList = assetsToSelect.ToList();
// Ensure the location of the assets to select are themselves selected.
var locations = new HashSet<DirectoryBaseViewModel>(assetList.Select(x => x.Directory));
if (locations.All(x => !SelectedLocations.Contains(x)))
{
SelectedLocations.Clear();
SelectedLocations.AddRange(locations);
}
// Don't reselect if the current selection is the same
if (assetList.Count != SelectedAssets.Count || !assetList.All(x => SelectedAssets.Contains(x)))
{
selectedContent.Clear();
selectedContent.AddRange(assetList.Where(x => filteredAssets.Contains(x)));
}
UpdateCommands();
}
public IReadOnlyCollection<DirectoryBaseViewModel> GetSelectedDirectories(bool includeSubDirectoriesOfSelected)
{
var selectedDirectories = new List<DirectoryBaseViewModel>();
foreach (var location in SelectedLocations)
{
var packageCategory = location as PackageCategoryViewModel;
var package = location as PackageViewModel;
var directory = location as DirectoryBaseViewModel;
if (packageCategory != null && includeSubDirectoriesOfSelected)
{
selectedDirectories.AddRange(packageCategory.Content.Select(x => x.AssetMountPoint).NotNull());
}
if (package != null)
{
selectedDirectories.Add(package.AssetMountPoint);
}
if (directory != null)
{
selectedDirectories.Add(directory);
}
}
if (!includeSubDirectoriesOfSelected)
{
return selectedDirectories;
}
var result = new HashSet<DirectoryBaseViewModel>();
foreach (var selectedDirectory in selectedDirectories)
{
var hierarchy = new List<DirectoryBaseViewModel>();
selectedDirectory.GetDirectoryHierarchy(hierarchy);
foreach (var directory in hierarchy)
{
result.Add(directory);
}
}
return result.ToList();
}
public void UpdateAssetsCollection(ICollection<AssetViewModel> newAssets)
{
UpdateAssetsCollection(newAssets, true);
}
/// <summary>
/// Deletes the given assets in a single transaction without asking for confirmation nor fixing broken references.
/// Assets whose <see cref="AssetViewModel.CanDelete()"/> method returns <c>false</c> won't be deleted, unless <paramref name="forceDelete"/> is <c>true</c>.
/// </summary>
/// <param name="assetsToDelete">The list of assets to delete.</param>
/// <param name="forceDelete">If <c>true</c> the asset whose <see cref="AssetViewModel.CanDelete()"/> method returns <c>false</c> will still be deleted</param>
/// <returns>The number of assets that have been successfully deleted.</returns>
internal int DeleteAssets(IEnumerable<AssetViewModel> assetsToDelete, bool forceDelete = false)
{
using (var transaction = Session.UndoRedoService.CreateTransaction())
{
var deletedAssets = new List<AssetViewModel>();
foreach (var asset in assetsToDelete.Where(x => forceDelete || x.CanDelete()))
{
if (asset.Directory == null)
throw new InvalidOperationException("The asset directory cannot be null before deleting an asset.");
if (!forceDelete && !asset.CanDelete())
continue;
// This must be done before we clear the Directory property of the asset
AssetDependenciesViewModel.NotifyAssetChanged(asset.Session, asset);
var oldDirectory = asset.Directory;
// It is important to set IsDeleted before clearing the directory, so the parent project can be marked as dirty
asset.IsDeleted = true;
asset.Directory.RemoveAsset(asset);
asset.Directory = null;
// Update RootAssets, for both current package and packages referencing this one
// Note: Package to Asset references should be handled in a more generic way (same as Asset to Asset references)
// We check only local
foreach (var localPackage in Session.LocalPackages)
{
localPackage.RootAssets.Remove(asset);
}
oldDirectory.Package.CheckConsistency();
deletedAssets.Add(asset);
}
Session.UndoRedoService.SetName(transaction, deletedAssets.Count == 1 ? $"Delete asset '{deletedAssets[0]}'" : $"Delete {deletedAssets.Count} assets");
return deletedAssets.Count;
}
}
/// <inheritdoc />
public override void Destroy()
{
EnsureNotDestroyed(nameof(AssetCollectionViewModel));
pasteMonitor.Destroy();
base.Destroy();
}
public async Task<List<AssetViewModel>> RunAssetTemplate(ITemplateDescriptionViewModel template, [CanBeNull] IList<UFile> files, PropertyContainer? customParameters = null)
{
if (template == null)
return new List<AssetViewModel>();
var loggerResult = new LoggerResult();
var directory = await GetAssetCreationTargetFolder();
if (directory == null)
return new List<AssetViewModel>();
var templateDescription = template.GetTemplate() as TemplateAssetDescription;
if (templateDescription == null)
{
await Dialogs.MessageBoxAsync(Tr._p("Message", "Unable to use the selected template because it is not an asset template."), MessageBoxButton.OK, MessageBoxImage.Warning);
return new List<AssetViewModel>();
}
var assetType = templateDescription.GetAssetType();
// If the mount point of the current folder does not support this type of asset, try to select the first mount point that support it.
directory = AssetViewModel.FindValidCreationLocation(assetType, directory, Session.CurrentProject);
if (directory == null)
return new List<AssetViewModel>();
string name = string.Empty;
if (templateDescription.RequireName)
{
name = templateDescription.DefaultOutputName ?? templateDescription.AssetTypeName;
}
return await InvokeAddAssetTemplate(loggerResult, name, directory, templateDescription, files, customParameters);
}
private async Task ShowAddAssetDialog()
{
var directory = await GetAssetCreationTargetFolder();
if (directory == null)
return;
var templateDialog = ServiceProvider.Get<IEditorDialogService>().CreateAddAssetDialog(Session, directory);
var result = await templateDialog.ShowModal();
if (result == DialogResult.Ok)
{
var selectedTemplate = templateDialog.SelectedTemplate;
if (selectedTemplate != null)
{
await RunAssetTemplate(selectedTemplate, null);
}
}
}
private string ComputeNamespace(DirectoryBaseViewModel directory)
{
switch (directory)
{
case ProjectCodeViewModel projectCode:
return projectCode.Project.RootNamespace;
case var directoryWithParent when directoryWithParent.Parent != null:
return $"{ComputeNamespace(directoryWithParent.Parent)}.{directoryWithParent.Name}";
default:
return directory.Name;
}
}
private async Task<string> GetAssetCopyDirectory(DirectoryBaseViewModel directory, UFile file)
{
var path = directory.Path;
var message = Tr._p("Message", "Do you want to place the resource in the default location ?");
var finalPath = Path.GetFullPath(Path.Combine(directory.Package.Package.ResourceFolders[0], path, file.GetFileName()));
var pathResult = await Dialogs.MessageBoxAsync(message, MessageBoxButton.YesNo, MessageBoxImage.Question);
if (pathResult == MessageBoxResult.No)
{
while (true)
{
var filePath = await Dialogs.SaveFilePickerAsync(
Path.GetFullPath(directory.Package.Package.ResourceFolders[0].FullPath),
[new FilePickerFilter("") { Patterns = [file.GetFileExtension()]}],
defaultFileName: file.GetFileName());
// If the user closes the dialog, assume that they want to use the default directory
if (filePath is null)
{
return finalPath;
}
var fullPath = Path.GetFullPath(filePath);
bool inResource = directory.Package.Package.ResourceFolders.Any(x => fullPath.StartsWith(Path.GetFullPath(x.FullPath), StringComparison.Ordinal));
if (inResource)
{
return fullPath;
}
message = Tr._p("Message", "The selected directory is not a subdirectory of the resources folder!");
await Dialogs.MessageBoxAsync(message, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return finalPath;
}
private async Task<List<AssetViewModel>> InvokeAddAssetTemplate(LoggerResult logger, string name, DirectoryBaseViewModel directory, TemplateAssetDescription templateDescription, [CanBeNull] IList<UFile> files, PropertyContainer? customParameters)
{
const int DialogClosed = 0;
const int DialogYes = 1;
const int DialogNo = 2;
const int DialogYesToAll = 3;
const int DialogNoToAll = 4;
var newAssets = new List<AssetViewModel>();
IReadOnlyList<DialogButtonInfo> copyPromptWithToAllButtons = DialogHelper.CreateButtons(
[
Tr._p("Button", "Yes"),
Tr._p("Button", "No"),
Tr._p("Button", "Yes to all"),
Tr._p("Button", "No to all")
], 1, 2);
IReadOnlyList<DialogButtonInfo> overwritePromptWithToAllButtons = DialogHelper.CreateButtons(
[
Tr._p("Button", "Yes"),
Tr._p("Button", "No"),
Tr._p("Button", "Yes to all")
], 1, 2);
IReadOnlyList<DialogButtonInfo> dialogDefaultButtons = DialogHelper.CreateButtons(
[
Tr._p("Button", "Yes"),
Tr._p("Button", "No")
], 1, 2);
var yesToAll = false;
var overwriteAll = false;
var finalPath = string.Empty;
if (files is not null)
{
for (var i = 0; i < files.Count; i++)
{
var file = files[i];
var inResourceFolder = directory.Package.Package.ResourceFolders.Any(x => file.FullPath.StartsWith(x.FullPath, StringComparison.Ordinal));
if (inResourceFolder)
{
continue;
}
if (!yesToAll)
{
var message = Tr._p("Message", "Source file '{0}' is not inside of your project's resource folders, do you want to copy it?").ToFormat(file.FullPath);
var copyResult = await Dialogs.MessageBoxAsync(message, i != files.Count - 1 ? copyPromptWithToAllButtons : dialogDefaultButtons, MessageBoxImage.Warning);
if (copyResult is DialogClosed or DialogNo)
{
continue;
}
if (copyResult is DialogNoToAll)
{
break;
}
if (copyResult is DialogYesToAll)
{
yesToAll = true;
}
if (copyResult is DialogYes or DialogYesToAll)
{
finalPath = await GetAssetCopyDirectory(directory, file);
}
}
else
{
// If "Yes to all" we're going to assume they want to use the same directory as the initial file.
finalPath = Path.Combine(Path.GetDirectoryName(finalPath), file.GetFileName());
}
try
{
Directory.CreateDirectory(Path.GetDirectoryName(finalPath));
if (File.Exists(finalPath))
{
if (!overwriteAll)
{
var message = Tr._p("Message", "The file '{0}' already exists, it will get overwritten if you continue, do you really want to proceed?").ToFormat(finalPath);
var copyResult = await Dialogs.MessageBoxAsync(message, i != files.Count - 1 ? overwritePromptWithToAllButtons : dialogDefaultButtons, MessageBoxImage.Warning);
overwriteAll = copyResult is DialogYesToAll;
if (copyResult is DialogClosed)
{
return newAssets;
}
if (copyResult is DialogNo)
{
continue;
}
}
File.Copy(file.FullPath, finalPath, true);
}
else
{
File.Copy(file.FullPath, finalPath);
}
files[i] = new UFile(finalPath);
}
catch (Exception ex)
{
var message = Tr._p("Message", "An error occurred while copying the asset to the resources folder: {0}").ToFormat(ex.Message);
await Dialogs.MessageBoxAsync(message, MessageBoxButton.OK, MessageBoxImage.Error);
return newAssets;
}
}
}
var parameters = new AssetTemplateGeneratorParameters(directory.Path, files)
{
Name = name,
Description = templateDescription,
Package = directory.Package.Package,
Logger = logger,
Namespace = ComputeNamespace(directory),
};
if (customParameters.HasValue)
{
foreach (var tag in customParameters.Value)
{
parameters.Tags[tag.Key] = tag.Value;
}
}
var generator = TemplateManager.FindTemplateGenerator(parameters);
if (generator == null)
{
await Dialogs.MessageBoxAsync(Tr._p("Message", "Unable to retrieve template generator for the selected template. Aborting."), MessageBoxButton.OK, MessageBoxImage.Error);
return newAssets;
}
var workProgress = new WorkProgressViewModel(ServiceProvider, logger)
{
Title = Tr._p("Title", "Add asset…"),
KeepOpen = KeepOpen.OnWarningsOrErrors,
IsIndeterminate = true,
IsCancellable = false, // The process is not cancellable at the beginning.
};
workProgress.RegisterProgressStatus(logger, true);
try
{
var bufferBlock = new BufferBlock<IReadOnlyList<SourceFileChangedData>>();
var cancel = new CancellationTokenSource();
List<AssetItem> newAssetItems;
using (Session.SourceTracker.SourceFileChanged.LinkTo(bufferBlock))
{
// Run the template generator first. This method also takes care of showing the progress window.
await TemplateGeneratorHelper.RunTemplateGeneratorSafe(generator, parameters, workProgress);
var previousAssetItems = new HashSet<AssetItem>(directory.Package.Assets.Select(x => x.AssetItem));
newAssetItems = new List<AssetItem>(directory.Package.Package.Assets.Where(x => !previousAssetItems.Contains(x)));
// No asset to create, early exit.
if (newAssetItems.Count == 0)
{
logger.Info("Nothing to import.");
return newAssets;
}
// Collect all the source files that affect the assets, we want their hashes before creating view models.
var sources = new Dictionary<AssetId, HashSet<UFile>>();
var collector = new SourceFilesCollector();
foreach (var newAsset in newAssetItems)
{
var assetSources = collector.GetSourceFiles(newAsset.Asset).Where(x => x.Value).Select(x => x.Key).ToList();
if (assetSources.Count > 0)
{
sources.Add(newAsset.Id, new HashSet<UFile>(assetSources));
}
}
logger.Info($"Computing hashes of {sources.Sum(x => x.Value.Count)} source files...");
// From now the import become cancellable. If for some reason, the hashes of some source files is never computed,
// this process will wait forever until the user cancels.
workProgress.IsCancellable = true;
workProgress.CancelCommand = new AnonymousCommand(ServiceProvider, () => cancel.Cancel());
while (sources.Count > 0)
{
var changes = await bufferBlock.ReceiveAsync(cancel.Token);
if (cancel.IsCancellationRequested)
{
logger.Info("Operation cancelled");
break;
}
foreach (var change in changes)
{
// Filter out changes unrelated to our new assets.
if (!sources.ContainsKey(change.AssetId))
continue;
var assetItem = newAssetItems.First(x => x.Id == change.AssetId);
var assetSources = sources[assetItem.Id];
// We care only about source files changes
if (change.Type == SourceFileChangeType.SourceFile)
{
// Retrieve the currently stored hashes for this asset.
var assetHashes = SourceHashesHelper.GetAllHashes(assetItem.Asset);
foreach (var file in change.Files)
{
// Update it with newly computed hashes
var hash = Session.SourceTracker.GetCurrentHash(file);
assetHashes[file] = hash;
// Remove hashes that have been registered.
assetSources.Remove(file);
logger.Verbose($"Computed hash of {file} for asset {assetItem.Location}. {sources.Sum(x => x.Value.Count)} files remaining...");
}
// Push the changes we did to the stored hashes.
SourceHashesHelper.UpdateHashes(assetItem.Asset, assetHashes);
// Remove this asset from the list if we got all its hashes
if (assetSources.Count == 0)
sources.Remove(assetItem.Id);
}
}
}
}
// If user cancelled, stops here and return an empty list.
if (cancel.IsCancellationRequested)
return newAssets;
// Actually create the transaction and the view models now.
using (var transaction = Session.UndoRedoService.CreateTransaction())
{
newAssets = newAssetItems.Select(assetItem => directory.Package.CreateAsset(directory, assetItem, true, logger)).ToList();
Session.UndoRedoService.SetName(transaction, newAssets.Count == 1 ? $"Create asset '{newAssets.First().Url}'" : $"Create {newAssets.Count} assets");
}
Session.CheckConsistency();
if (parameters.RequestSessionSave)
{
await Session.SaveSession();
}
SelectAssets(newAssets);
return newAssets;
}
catch (Exception e)
{
logger.Error("There was a problem generating the asset", e);
return newAssets;
}
finally
{
await workProgress.NotifyWorkFinished(false, logger.HasErrors);
}
}
private async Task<DirectoryBaseViewModel> GetAssetCreationTargetFolder()
{
var directories = GetSelectedDirectories(false);
var directoryCount = directories.Count;
if (directoryCount > 1)
{
await Dialogs.MessageBoxAsync(Tr._p("Message", "Game Studio can't create assets in multiple locations. In the solution explorer, select a single directory or package to create the asset in."), MessageBoxButton.OK, MessageBoxImage.Warning);
return null;
}
if (directoryCount == 0)
{
await Dialogs.MessageBoxAsync(Tr._p("Message", "Game Studio can't create an asset here. In the solution explorer, select a directory or package to create the asset in."), MessageBoxButton.OK, MessageBoxImage.Warning);
return null;
}
var directory = directories.First();
if (!directory.Package.IsEditable)
{
await Dialogs.MessageBoxAsync(Tr._p("Message", "Game Studio can't create an asset here because the selected directory or package can't be edited. In the solution explorer, select a directory or package to create the asset in."), MessageBoxButton.OK, MessageBoxImage.Warning);
return null;
}
return directory;
}
private async Task CutSelectedLocations()
{
var directories = GetSelectedDirectories(false);
await CutSelection(directories, null);
UpdateCommands();
}
private bool CanCopy()
{
return ServiceProvider.TryGet<ICopyPasteService>() != null;
}
private void CopyAssetUrl()
{
if (SingleSelectedAsset == null)
return;
try
{
SafeClipboard.SetText(SingleSelectedAsset.Url);
}
catch (SystemException e)
{
// We don't provide feedback when copying fails.
e.Ignore();
}
}
private async Task CopySelectedLocations()
{
var directories = GetSelectedDirectories(false);
await CopySelection(directories, null);
UpdateCommands();
}
private async Task CutSelectedContent()
{
var directories = SelectedContent.OfType<DirectoryBaseViewModel>().ToList();
await CutSelection(directories, SelectedAssets);
UpdateCommands();
}
private async Task CopySelectedContent()
{
var directories = SelectedContent.OfType<DirectoryBaseViewModel>().ToList();
await CopySelection(directories, SelectedAssets);
UpdateCommands();
}
private async Task CopySelectedAssetsRecursively()
{
var assetsToCopy = new ObservableSet<AssetViewModel>();
foreach (var asset in SelectedAssets)
{
assetsToCopy.Add(asset);
assetsToCopy.AddRange(asset.Dependencies.RecursiveReferencedAssets.Where(a => a.IsEditable));
}
await CopySelection(null, assetsToCopy);
UpdateCommands();
}
private async Task CutSelection(IReadOnlyCollection<DirectoryBaseViewModel> directories, IEnumerable<AssetViewModel> assetsToCut)
{
// Ensure all directories can be cut
if (directories?.Any(d => !d.IsEditable) == true)
{
await Dialogs.MessageBoxAsync(Tr._p("Message", "Read-only folders can't be cut."), MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
var assetsToWrite = await GetCopyCollection(directories, assetsToCut);
if (assetsToWrite == null || assetsToWrite.Count == 0)
{
return;
}
// Flatten to a list
var assetList = assetsToWrite.SelectMany(x => x).ToList();
foreach (var asset in assetList)
{
string error;
if (!asset.CanDelete(out error))
{
error = string.Format(Tr._p("Message", "The asset {0} can't be deleted. {1}{2}"), asset.Url, Environment.NewLine, error);
await Dialogs.MessageBoxAsync(error, MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
}
// Copy
if (!WriteToClipboard(assetsToWrite))
{
return;
}
using (var transaction = Session.UndoRedoService.CreateTransaction())
{
// Clear the selection at first to reduce view updates in the following actions
ClearSelection();
// Add an action item that will fix back the references in the referencers of the assets being cut, in case the
var assetsToFix = PackageViewModel.GetReferencers(dependencyManager, Session, assetList.Select(x => x.AssetItem));
var fixReferencesOperation = new FixAssetReferenceOperation(assetsToFix, true, false);
Session.UndoRedoService.PushOperation(fixReferencesOperation);
// Delete the assets
DeleteAssets(assetList);
if (directories != null)
{
// Delete the directories
foreach (var directory in directories)
{
string error;
// Last-chance check (note that we already checked that the directories are not read-only)
if (!directory.CanDelete(out error))
{
error = string.Format(Tr._p("Message", "{0} can't be deleted. {1}{2}"), directory.Name, Environment.NewLine, error);
await Dialogs.MessageBoxAsync(error, MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
directory.Delete();
}
}
Session.UndoRedoService.SetName(transaction, "Cut selection");
}
}
private async Task CopySelection(IReadOnlyCollection<DirectoryBaseViewModel> directories, IEnumerable<AssetViewModel> assetsToCopy)
{
var assetsToWrite = await GetCopyCollection(directories, assetsToCopy);