-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathBrowserControl.DragDrop.xaml.cs
More file actions
500 lines (428 loc) · 22 KB
/
Copy pathBrowserControl.DragDrop.xaml.cs
File metadata and controls
500 lines (428 loc) · 22 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
using APES.UI.XF;
using OwlCore.Storage;
using SecureFolderFS.Sdk.Enums;
using SecureFolderFS.Sdk.Extensions;
using SecureFolderFS.Sdk.ViewModels.Controls.Storage.Browser;
using SecureFolderFS.Shared.Extensions;
using SecureFolderFS.Shared.Helpers;
using SecureFolderFS.Storage.Extensions;
#if IOS || MACCATALYST
using Foundation;
using UniformTypeIdentifiers;
#elif ANDROID
using SecureFolderFS.Maui.Platforms.Android.Helpers;
#endif
namespace SecureFolderFS.Maui.UserControls.Browser
{
public partial class BrowserControl
{
private void DragGestureRecognizer_DragStarting(object? sender, DragStartingEventArgs e)
{
if (sender is not ContextMenuContainer { BindingContext: BrowserItemViewModel itemViewModel })
return;
e.Data.Properties["DraggedItem"] = itemViewModel;
}
/// <summary>
/// Tries to get the dragged item from either MAUI's <see cref="DataPackage"/> (iOS)
/// or from the static <see cref="DragThresholdTouchHandler.CurrentDraggedItem"/> (Android).
/// </summary>
private static BrowserItemViewModel? GetDraggedItem(DropEventArgs e)
{
// First, check MAUI's DataPackage (works on iOS and when DragGestureRecognizer is used)
if (e.Data.Properties.TryGetValue("DraggedItem", out var draggedItemObj) && draggedItemObj is BrowserItemViewModel draggedItem)
return draggedItem;
#if ANDROID
// On Android, check the static field set by DragThresholdTouchHandler
return DragThresholdTouchHandler.CurrentDraggedItem;
#else
return null;
#endif
}
/// <summary>
/// Clears the Android drag state after a drop operation completes.
/// </summary>
private static void ClearDragState()
{
#if ANDROID
DragThresholdTouchHandler.CurrentDraggedItem = null;
#endif
}
/// <summary>
/// Registers the Android-specific drag threshold touch handler on an item container.
/// On iOS/macOS, this is a no-op since the platform handles drag thresholds natively.
/// </summary>
internal static void RegisterAndroidDragThreshold(View view)
{
#if ANDROID
if (view.Handler?.PlatformView is global::Android.Views.View androidView)
{
var handler = new DragThresholdTouchHandler(view);
handler.Attach(androidView);
}
#endif
}
private void DropGestureRecognizer_DragOver(object? sender, DragEventArgs e)
{
if (IsReadOnly)
return;
if (sender is not DropGestureRecognizer { Parent: View view })
return;
if (view.BindingContext is not FolderViewModel)
{
e.AcceptedOperation = DataPackageOperation.None;
return;
}
e.AcceptedOperation = DataPackageOperation.Copy;
view.BackgroundColor = Color.FromArgb("#30808080");
}
private void DropGestureRecognizer_DragLeave(object? sender, DragEventArgs e)
{
if (sender is not DropGestureRecognizer { Parent: View view })
return;
view.BackgroundColor = Colors.Transparent;
}
private async void DropGestureRecognizer_Drop(object? sender, DropEventArgs e)
{
if (IsReadOnly)
return;
if (sender is not ContextMenuContainer { BindingContext: FolderViewModel folderViewModel })
return;
// Handle internal drag-and-drop (from within the app)
var draggedItem = GetDraggedItem(e);
if (draggedItem is not null)
{
ClearDragState();
// Disallow dropping on itself
if (draggedItem == folderViewModel)
return;
// Disallow dropping a folder into its own subfolder
if (folderViewModel.Inner.Id.Contains(draggedItem.Inner.Id, StringComparison.InvariantCultureIgnoreCase))
return;
await MoveItemToFolderAsync(draggedItem, folderViewModel);
return;
}
// Handle external files dropped from system apps (e.g., Files app)
await CopyExternalFilesToFolderAsync(e, folderViewModel);
}
private void CollectionDropGestureRecognizer_DragOver(object? sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
}
private void CollectionDropGestureRecognizer_DragLeave(object? sender, DragEventArgs e)
{
// No visual feedback needed for collection drop
}
private async void CollectionDropGestureRecognizer_Drop(object? sender, DropEventArgs e)
{
if (IsReadOnly)
return;
// Handle internal drag-and-drop (from within the app)
var draggedItem = GetDraggedItem(e);
if (draggedItem is not null)
{
ClearDragState();
if (draggedItem.ParentFolder is null)
return;
// Get the current folder from the BrowserViewModel
var browserViewModel = draggedItem.BrowserViewModel;
var currentFolder = browserViewModel.CurrentFolder;
if (currentFolder is null)
return;
// Don't move if the item is already in the current folder
if (draggedItem.ParentFolder == currentFolder)
return;
// Disallow dropping a folder into its own subfolder
if (currentFolder.Inner.Id.Contains(draggedItem.Inner.Id, StringComparison.InvariantCultureIgnoreCase))
return;
await MoveItemToFolderAsync(draggedItem, currentFolder);
return;
}
// Handle external files dropped from system apps (e.g., Files app)
// Get the current folder from the ItemsSource binding
if (ItemsSource is not { Count: >= 0 } items)
return;
// Try to get the BrowserViewModel from the first item, or from the binding context
var firstItem = items.FirstOrDefault();
var targetBrowserViewModel = firstItem?.BrowserViewModel;
var targetFolder = targetBrowserViewModel?.CurrentFolder;
if (targetFolder is null)
return;
await CopyExternalFilesToFolderAsync(e, targetFolder);
}
/// <summary>
/// Moves a dragged item to the specified destination folder.
/// </summary>
/// <param name="draggedItem">The item being dragged.</param>
/// <param name="destinationViewModel">The destination folder view model.</param>
private static async Task MoveItemToFolderAsync(BrowserItemViewModel draggedItem, FolderViewModel destinationViewModel)
{
if (draggedItem.ParentFolder?.Folder is not IModifiableFolder sourceFolder)
return;
if (destinationViewModel.Folder is not IModifiableFolder destinationFolder)
return;
if (draggedItem.Inner is not IStorableChild itemToMove)
return;
var browserViewModel = draggedItem.BrowserViewModel;
if (browserViewModel.TransferViewModel is not { IsProgressing: false } transferViewModel)
return;
try
{
transferViewModel.TransferType = TransferType.Move;
using var cts = transferViewModel.GetCancellation();
// Ensure the destination has content already loaded
if (destinationViewModel.Items.IsEmpty())
_ = destinationViewModel.ListContentsAsync(cts.Token);
await transferViewModel.TransferAsync([ itemToMove ], async (item, reporter, token) =>
{
// Get available name to avoid collision
var availableName = CollisionHelpers.GetAvailableName(item.Name, destinationViewModel.Items.Select(x => x.Inner.Name));
// Move
var movedItem = await destinationFolder.MoveStorableFromAsync(item, sourceFolder, false, availableName, reporter, token);
// Remove existing from source folder
draggedItem.ParentFolder.Items.RemoveMatch(x => x.Inner.Id == item.Id)?.Dispose();
// Add to destination
destinationViewModel.Items.Insert(movedItem switch
{
IFile file => new FileViewModel(file, browserViewModel, destinationViewModel),
IFolder folder => new FolderViewModel(folder, browserViewModel, destinationViewModel),
_ => throw new ArgumentOutOfRangeException(nameof(movedItem))
}, browserViewModel.Layouts.GetSorter());
}, cts.Token);
}
catch (Exception ex) when (ex is TaskCanceledException or OperationCanceledException)
{
_ = ex;
// TODO: Report error
}
finally
{
await transferViewModel.HideAsync();
}
}
/// <summary>
/// Copies external files from system apps (e.g., Files app) to the destination folder.
/// </summary>
/// <param name="dropEventArgs">The drop event args containing the dropped files.</param>
/// <param name="destinationViewModel">The destination folder view model.</param>
private static async Task CopyExternalFilesToFolderAsync(DropEventArgs dropEventArgs, FolderViewModel destinationViewModel)
{
if (destinationViewModel.Folder is not IModifiableFolder destinationFolder)
return;
var browserViewModel = destinationViewModel.BrowserViewModel;
if (browserViewModel.TransferViewModel is not { IsProgressing: false } transferViewModel)
return;
#if IOS || MACCATALYST
// Get items from PlatformArgs on iOS/macOS
if (dropEventArgs.PlatformArgs?.DropSession is { } dropSession)
{
var itemCount = dropSession.Items.Length;
if (itemCount == 0)
return;
// Collect all items to process - either as file URLs or as data streams
var itemsToProcess = new List<(string Name, Func<CancellationToken, Task<Stream?>> DataLoader, bool IsFolder)>();
foreach (var dragItem in dropSession.Items)
{
var itemProvider = dragItem.ItemProvider;
var suggestedName = itemProvider.SuggestedName ?? "Unknown";
// First, check for Gallery/Photos app items (specific image/video types loaded as data)
// These need to be checked first because UTTypes.Item would also match them
var galleryTypeIdentifiers = new[]
{
UTTypes.Jpeg.Identifier,
UTTypes.Png.Identifier,
UTTypes.Heic.Identifier,
UTTypes.Gif.Identifier,
UTTypes.Mpeg4Movie.Identifier,
UTTypes.QuickTimeMovie.Identifier,
UTTypes.Image.Identifier,
UTTypes.Movie.Identifier
};
// Check if this is a Gallery item by seeing if it does NOT have a FileUrl representation
// Files app items have FileUrl, Gallery items don't
var matchedGalleryTypeIdentifier = galleryTypeIdentifiers.FirstOrDefault(typeId => itemProvider.HasItemConformingTo(typeId));
var hasFileUrl = itemProvider.HasItemConformingTo(UTTypes.FileUrl.Identifier);
if (matchedGalleryTypeIdentifier is not null && !hasFileUrl)
{
// This is a Gallery/Photos app item - load as data representation
var capturedTypeId = matchedGalleryTypeIdentifier;
var capturedProvider = itemProvider;
// Determine extension from type identifier
var extension = GetExtensionFromTypeIdentifier(capturedTypeId);
var suggestedExtension = Path.GetExtension(suggestedName);
var actualName = suggestedName;
if (string.IsNullOrEmpty(suggestedExtension) && !string.IsNullOrEmpty(extension))
actualName = suggestedName + extension;
itemsToProcess.Add((actualName, async _ =>
{
var dataTcs = new TaskCompletionSource<NSData?>();
var utType = UTType.CreateFromIdentifier(capturedTypeId);
if (utType is null)
return null;
capturedProvider.LoadDataRepresentation(utType, (data, _) =>
{
dataTcs.TrySetResult(data);
});
var data = await dataTcs.Task;
return data?.AsStream();
}, false));
continue;
}
// Second, try to load as a file URL (works for Files app)
if (itemProvider.HasItemConformingTo(UTTypes.Item.Identifier))
{
var tcs = new TaskCompletionSource<(NSUrl? Url, bool IsFolder)>();
itemProvider.LoadItem(UTTypes.Item.Identifier, null, (item, _) =>
{
if (item is NSUrl { Path: not null } itemUrl)
{
var isDir = false;
var isDirectory = NSFileManager.DefaultManager.FileExists(itemUrl.Path, ref isDir) && isDir;
tcs.TrySetResult((itemUrl, isDirectory));
}
else
{
tcs.TrySetResult((null, false));
}
});
var (url, isFolder) = await tcs.Task;
if (url is not null)
{
// Get the actual filename from the URL path - this should include the correct extension
var fileNameFromPath = Path.GetFileName(url.Path!);
// Use the filename from path if available (it has the correct extension),
// otherwise fall back to suggestedName with extension appended
string actualName;
if (!string.IsNullOrEmpty(fileNameFromPath) && !string.IsNullOrEmpty(Path.GetExtension(fileNameFromPath)))
{
// URL path has filename with extension - use it directly
actualName = fileNameFromPath;
}
else
{
// Fall back to suggested name, appending extension from path if needed
var pathExtension = Path.GetExtension(url.Path!);
var suggestedExtension = Path.GetExtension(suggestedName);
actualName = string.IsNullOrEmpty(suggestedExtension) && !string.IsNullOrEmpty(pathExtension)
? suggestedName + pathExtension
: suggestedName;
}
if (isFolder)
{
itemsToProcess.Add((actualName, _ => Task.FromResult<Stream?>(null), true));
}
else
{
var capturedUrl = url;
itemsToProcess.Add((actualName, async ct =>
{
var accessStarted = capturedUrl.StartAccessingSecurityScopedResource();
try
{
if (capturedUrl.Path is not null && File.Exists(capturedUrl.Path))
{
var ms = new MemoryStream();
await using var fs = File.OpenRead(capturedUrl.Path);
await fs.CopyToAsync(ms, ct);
ms.Position = 0;
return ms;
}
}
finally
{
if (accessStarted)
capturedUrl.StopAccessingSecurityScopedResource();
}
return null;
}, false));
}
continue;
}
}
// Fall back to loading as generic data
if (itemProvider.HasItemConformingTo(UTTypes.Data.Identifier))
{
var capturedProvider = itemProvider;
itemsToProcess.Add((suggestedName, async _ =>
{
var dataTcs = new TaskCompletionSource<NSData?>();
capturedProvider.LoadDataRepresentation(UTTypes.Data, (data, _) =>
{
dataTcs.TrySetResult(data);
});
var data = await dataTcs.Task;
return data?.AsStream();
}, false));
}
}
if (itemsToProcess.Count == 0)
return;
try
{
transferViewModel.TransferType = TransferType.Copy;
using var cts = transferViewModel.GetCancellation();
// Ensure the destination has content already loaded
if (destinationViewModel.Items.IsEmpty())
_ = destinationViewModel.ListContentsAsync(cts.Token);
await transferViewModel.TransferAsync(itemsToProcess, async (item, reporter, token) =>
{
token.ThrowIfCancellationRequested();
// Get available name to avoid collision
var availableName = CollisionHelpers.GetAvailableName(item.Name, destinationViewModel.Items.Select(x => x.Inner.Name));
if (item.IsFolder)
{
// Create folder
var createdFolder = await destinationFolder.CreateFolderAsync(availableName, false, token);
destinationViewModel.Items.Insert(
new FolderViewModel(createdFolder, browserViewModel, destinationViewModel),
browserViewModel.Layouts.GetSorter());
}
else
{
// Load data and create file
await using var dataStream = await item.DataLoader(token);
if (dataStream is null)
return;
var createdFile = await destinationFolder.CreateFileAsync(availableName, false, token);
await using var destinationStream = await createdFile.OpenStreamAsync(FileAccess.Write, token);
await dataStream.CopyToAsync(destinationStream, token);
reporter.Report(createdFile);
destinationViewModel.Items.Insert(
new FileViewModel(createdFile, browserViewModel, destinationViewModel),
browserViewModel.Layouts.GetSorter());
}
}, x => x.Name, cts.Token);
}
catch (Exception ex) when (ex is TaskCanceledException or OperationCanceledException)
{
_ = ex;
// TODO: Report error
}
finally
{
await transferViewModel.HideAsync();
}
}
#elif ANDROID
// TODO: Implement Android drag-and-drop from external apps
#endif
}
#if IOS || MACCATALYST
private static string GetExtensionFromTypeIdentifier(string typeIdentifier)
{
return typeIdentifier switch
{
_ when typeIdentifier == UTTypes.Jpeg.Identifier => ".jpg",
_ when typeIdentifier == UTTypes.Png.Identifier => ".png",
_ when typeIdentifier == UTTypes.Heic.Identifier => ".heic",
_ when typeIdentifier == UTTypes.Gif.Identifier => ".gif",
_ when typeIdentifier == UTTypes.Mpeg4Movie.Identifier => ".mp4",
_ when typeIdentifier == UTTypes.QuickTimeMovie.Identifier => ".mov",
_ when typeIdentifier == UTTypes.Tiff.Identifier => ".tiff",
_ when typeIdentifier == UTTypes.Bmp.Identifier => ".bmp",
_ when typeIdentifier == UTTypes.Pdf.Identifier => ".pdf",
_ => string.Empty
};
}
#endif
}
}