Exemple #1
0
        internal DropCompletedEventArgs(UIElement originalSource, DataPackageOperation result)
            : base(originalSource)
        {
            DropResult = result;

            CanBubbleNatively = false;
        }
Exemple #2
0
        public async Task <ReturnResult> PerformOperationTypeAsync(DataPackageOperation operation,
                                                                   DataPackageView packageView,
                                                                   string destination,
                                                                   bool registerHistory)
        {
            try
            {
                switch (operation)
                {
                case DataPackageOperation.Copy:
                    return(await CopyItemsFromClipboard(packageView, destination, registerHistory));

                case DataPackageOperation.Move:
                    return(await MoveItemsFromClipboard(packageView, destination, registerHistory));

                case DataPackageOperation.None:     // Other
                    return(await CopyItemsFromClipboard(packageView, destination, registerHistory));

                default: return(default);
                }
            }
            finally
            {
                packageView.ReportOperationCompleted(operation);
            }
        }
Exemple #3
0
 public async Task <ReturnResult> PerformOperationTypeAsync(DataPackageOperation operation,
                                                            DataPackageView packageView,
                                                            string destination,
                                                            bool registerHistory)
 {
     try
     {
         if (destination == null)
         {
             return(default);
Exemple #4
0
        private async void dragGrid_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            // 通过 StartDragAsync() 开启拖放操作,拖放操作的其他部分遵循相同的模式
            DataPackageOperation dpo = await dragGrid.StartDragAsync(e.GetCurrentPoint(dragGrid));

            if (dpo != DataPackageOperation.None)
            {
                targetTextBlock.Text += dpo;
                targetTextBlock.Text += Environment.NewLine;
            }
        }
Exemple #5
0
        private void Complete(DataPackageOperation result)
        {
            if (_state == State.Completed)
            {
                return;
            }
            _state = State.Completed;

            _viewHandle.Dispose();
            Info.Complete(result);
        }
Exemple #6
0
 internal DataPackageView(
     DataPackageOperation requestedOperation,
     ImmutableDictionary <string, object> data,
     ImmutableDictionary <string, RandomAccessStreamReference> resourceMap,
     Action <string?, DataPackageOperation> reportCompleted)
 {
     _data              = data;
     _resourceMap       = resourceMap;
     _reportCompleted   = reportCompleted;
     RequestedOperation = requestedOperation;
 }
Exemple #7
0
 public async Task <ReturnResult> PerformOperationTypeAsync(DataPackageOperation operation,
                                                            DataPackageView packageView,
                                                            string destination,
                                                            bool showDialog,
                                                            bool registerHistory,
                                                            bool isTargetExecutable = false)
 {
     try
     {
         if (destination == null)
         {
             return(default);
Exemple #8
0
        internal CoreDragInfo(
            IDragEventSource source,
            DataPackageView data,
            DataPackageOperation allowedOperations,
            object?dragUI = null)
        {
            _source = source;
            (Position, Modifiers) = source.GetState();

            Data = data;
            AllowedOperations = allowedOperations;
            DragUI            = dragUI;
        }
Exemple #9
0
        internal void Complete(DataPackageOperation result)
        {
            if (Interlocked.CompareExchange(ref _result, (int)result, -1) != -1)
            {
                this.Log().Error("This drag operation has already been completed");
                return;
            }

            var completions = Interlocked.Exchange(ref _completions, null);

            foreach (var callback in completions !)
            {
                callback(result);
            }
        }
Exemple #10
0
        private async Task RaiseFinalLeave(CancellationToken ct)
        {
            try
            {
                if (_state != State.Over)
                {
                    return;
                }

                _state             = State.Completing;
                _acceptedOperation = DataPackageOperation.None;
                await _target.LeaveAsync(Info).AsTask(ct);
            }
            finally
            {
                Complete(DataPackageOperation.None);
            }
        }
Exemple #11
0
 public async Task <ReturnResult> PerformOperationTypeAsync(DataPackageOperation operation,
                                                            DataPackageView packageView,
                                                            string destination,
                                                            bool registerHistory)
 {
     try
     {
         if (operation.HasFlag(DataPackageOperation.Copy))
         {
             return(await CopyItemsFromClipboard(packageView, destination, registerHistory));
         }
         else if (operation.HasFlag(DataPackageOperation.Move))
         {
             return(await MoveItemsFromClipboard(packageView, destination, registerHistory));
         }
         else if (operation.HasFlag(DataPackageOperation.Link))
         {
             // TODO: Support link creation
             return(default);
Exemple #12
0
        private async Task RaiseEnterOrOver(CancellationToken ct)
        {
            if (_state >= State.Completing)
            {
                return;
            }

            var isOver = _state == State.Over;

            _state = State.Over;

            var acceptedOperation = isOver
                                ? await _target.OverAsync(Info, _viewOverride).AsTask(ct)
                                : await _target.EnterAsync(Info, _viewOverride).AsTask(ct);

            acceptedOperation &= Info.AllowedOperations;

            _acceptedOperation = acceptedOperation;
            _view.Update(acceptedOperation, _viewOverride);
        }
Exemple #13
0
        private async Task RaiseRecoverableLeave(CancellationToken ct)
        {
            if (_state != State.Over)
            {
                return;
            }

            _state             = State.None;
            _acceptedOperation = DataPackageOperation.None;
            await _target.LeaveAsync(Info).AsTask(ct);

            // When the pointer goes out of the window, we hide our internal control and,
            // if supported by the OS, we request a Drag and Drop operation with the native UI.
            _view.Hide();
            if (!_hasRequestedNativeDrag)
            {
                _extension?.StartNativeDrag(Info);
                _hasRequestedNativeDrag = true;
            }
        }
        private static NSDragOperation ToNSDragOperation(DataPackageOperation uwpOperation)
        {
            NSDragOperation result = NSDragOperation.None;

            if (uwpOperation.HasFlag(DataPackageOperation.Copy))
            {
                result |= NSDragOperation.Copy;
            }

            if (uwpOperation.HasFlag(DataPackageOperation.Link))
            {
                result |= NSDragOperation.Link;
            }

            if (uwpOperation.HasFlag(DataPackageOperation.Move))
            {
                result |= NSDragOperation.Move;
            }

            return(result);
        }
Exemple #15
0
        private async Task RaiseDrop(CancellationToken ct)
        {
            var result = DataPackageOperation.None;

            try
            {
                if (_state != State.Over)
                {
                    return;
                }

                _state = State.Completing;
                result = await _target.DropAsync(Info).AsTask(ct);

                result &= Info.AllowedOperations;

                _acceptedOperation = result;
            }
            finally
            {
                Complete(result);
            }
        }
Exemple #16
0
        private async Task PasteItemAsync(DataPackageView packageView, string destinationPath, DataPackageOperation acceptedOperation, IShellPage AppInstance, IProgress <uint> progress)
        {
            if (!packageView.Contains(StandardDataFormats.StorageItems))
            {
                // Happens if you copy some text and then you Ctrl+V in FilesUWP
                // Should this be done in ModernShellPage?
                return;
            }

            IReadOnlyList <IStorageItem> itemsToPaste = await packageView.GetStorageItemsAsync();

            if (AppInstance.FilesystemViewModel.WorkingDirectory.StartsWith(App.AppSettings.RecycleBinPath))
            {
                // Do not paste files and folders inside the recycle bin
                await DialogDisplayHelper.ShowDialogAsync("ErrorDialogThisActionCannotBeDone".GetLocalized(), "ErrorDialogUnsupportedOperation".GetLocalized());

                return;
            }

            List <IStorageItem>    pastedSourceItems = new List <IStorageItem>();
            HashSet <IStorageItem> pastedItems       = new HashSet <IStorageItem>();
            var  totalItemsSize       = CalculateTotalItemsSize(itemsToPaste);
            bool isItemSizeUnreported = totalItemsSize <= 0;

            foreach (IStorageItem item in itemsToPaste)
            {
                if (item.IsOfType(StorageItemTypes.Folder))
                {
                    if (!string.IsNullOrEmpty(item.Path) && destinationPath.IsSubPathOf(item.Path))
                    {
                        ImpossibleActionResponseTypes responseType = ImpossibleActionResponseTypes.Abort;

                        /// Currently following implementation throws exception until it is resolved keep it disabled

                        /*Binding themeBind = new Binding();
                         * themeBind.Source = ThemeHelper.RootTheme;
                         *
                         * ContentDialog dialog = new ContentDialog()
                         * {
                         *  Title = ResourceController.GetTranslation("ErrorDialogThisActionCannotBeDone"),
                         *  Content = ResourceController.GetTranslation("ErrorDialogTheDestinationFolder") + " (" + destinationPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last() + ") " + ResourceController.GetTranslation("ErrorDialogIsASubfolder") + " (" + item.Name + ")",
                         *  PrimaryButtonText = ResourceController.GetTranslation("ErrorDialogSkip"),
                         *  CloseButtonText = ResourceController.GetTranslation("ErrorDialogCancel"),
                         *  PrimaryButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Skip; }),
                         *  CloseButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Abort; }),
                         * };
                         * BindingOperations.SetBinding(dialog, FrameworkElement.RequestedThemeProperty, themeBind);
                         *
                         * await dialog.ShowAsync();*/
                        if (responseType == ImpossibleActionResponseTypes.Skip)
                        {
                            continue;
                        }
                        else if (responseType == ImpossibleActionResponseTypes.Abort)
                        {
                            return;
                        }
                    }
                    else
                    {
                        if (!isItemSizeUnreported)
                        {
                            var pastedItemSize = await Task.Run(() => CalculateTotalItemsSize(pastedSourceItems));

                            uint progressValue = (uint)(pastedItemSize * 100 / totalItemsSize);
                            progress.Report(progressValue);
                        }

                        await AppInstance.FilesystemViewModel.GetFolderFromPathAsync(destinationPath)
                        .OnSuccess(t => CloneDirectoryAsync((StorageFolder)item, t, item.Name))
                        .OnSuccess(t =>
                        {
                            if (AppInstance.FilesystemViewModel.CheckFolderForHiddenAttribute(item.Path))
                            {
                                // The source folder was hidden, apply hidden attribute to destination
                                NativeFileOperationsHelper.SetFileAttribute(t.Path, FileAttributes.Hidden);
                            }
                            pastedSourceItems.Add(item);
                            pastedItems.Add(t);
                        });
                    }
                }
                else if (item.IsOfType(StorageItemTypes.File))
                {
                    if (!isItemSizeUnreported)
                    {
                        var pastedItemSize = await Task.Run(() => CalculateTotalItemsSize(pastedSourceItems));

                        uint progressValue = (uint)(pastedItemSize * 100 / totalItemsSize);
                        progress.Report(progressValue);
                    }

                    var res = await AppInstance.FilesystemViewModel.GetFolderFromPathAsync(destinationPath);

                    if (res)
                    {
                        StorageFile clipboardFile = (StorageFile)item;
                        var         pasted        = await FilesystemTasks.Wrap(() => clipboardFile.CopyAsync(res.Result, item.Name, NameCollisionOption.GenerateUniqueName).AsTask());

                        if (pasted)
                        {
                            pastedSourceItems.Add(item);
                            pastedItems.Add(pasted.Result);
                        }
                        else if (pasted.ErrorCode == FilesystemErrorCode.ERROR_UNAUTHORIZED)
                        {
                            // Try again with CopyFileFromApp
                            if (NativeFileOperationsHelper.CopyFileFromApp(item.Path, Path.Combine(destinationPath, item.Name), true))
                            {
                                pastedSourceItems.Add(item);
                            }
                            else
                            {
                                Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                            }
                        }
                        else if (pasted.ErrorCode == FilesystemErrorCode.ERROR_NOTFOUND)
                        {
                            // File was moved/deleted in the meantime
                            continue;
                        }
                    }
                }
            }
            if (!isItemSizeUnreported)
            {
                var finalPastedItemSize = await Task.Run(() => CalculateTotalItemsSize(pastedSourceItems));

                uint finalProgressValue = (uint)(finalPastedItemSize * 100 / totalItemsSize);
                progress.Report(finalProgressValue);
            }
            else
            {
                progress.Report(100);
            }

            if (acceptedOperation == DataPackageOperation.Move)
            {
                foreach (IStorageItem item in pastedSourceItems)
                {
                    var deleted = (FilesystemResult)false;
                    if (string.IsNullOrEmpty(item.Path))
                    {
                        // Can't move (only copy) files from MTP devices because:
                        // StorageItems returned in DataPackageView are read-only
                        // The item.Path property will be empty and there's no way of retrieving a new StorageItem with R/W access
                        continue;
                    }
                    if (item.IsOfType(StorageItemTypes.File))
                    {
                        // If we reached this we are not in an MTP device, using StorageFile.* is ok here
                        deleted = await AppInstance.FilesystemViewModel.GetFileFromPathAsync(item.Path)
                                  .OnSuccess(t => t.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask());
                    }
                    else if (item.IsOfType(StorageItemTypes.Folder))
                    {
                        // If we reached this we are not in an MTP device, using StorageFolder.* is ok here
                        deleted = await AppInstance.FilesystemViewModel.GetFolderFromPathAsync(item.Path)
                                  .OnSuccess(t => t.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask());
                    }

                    if (deleted == FilesystemErrorCode.ERROR_UNAUTHORIZED)
                    {
                        // Try again with fulltrust process
                        if (AppInstance.FilesystemViewModel.Connection != null)
                        {
                            var response = await AppInstance.FilesystemViewModel.Connection.SendMessageAsync(new ValueSet()
                            {
                                { "Arguments", "FileOperation" },
                                { "fileop", "DeleteItem" },
                                { "filepath", item.Path },
                                { "permanently", true }
                            });

                            deleted = (FilesystemResult)(response.Status == Windows.ApplicationModel.AppService.AppServiceResponseStatus.Success);
                        }
                    }
                    else if (deleted == FilesystemErrorCode.ERROR_NOTFOUND)
                    {
                        // File or Folder was moved/deleted in the meantime
                        continue;
                    }
                }
            }

            if (destinationPath == AppInstance.FilesystemViewModel.WorkingDirectory)
            {
                List <string>     pastedItemPaths = pastedItems.Select(item => item.Path).ToList();
                List <ListedItem> copiedItems     = AppInstance.FilesystemViewModel.FilesAndFolders.Where(listedItem => pastedItemPaths.Contains(listedItem.ItemPath)).ToList();
                if (copiedItems.Any())
                {
                    AppInstance.ContentPage.SetSelectedItemsOnUi(copiedItems);
                    AppInstance.ContentPage.FocusSelectedItems();
                }
            }
            packageView.ReportOperationCompleted(acceptedOperation);
        }
Exemple #17
0
        private static async Task PasteItem(DataPackageView packageView, string destinationPath, DataPackageOperation acceptedOperation, IShellPage AppInstance, IProgress <uint> progress)
        {
            IReadOnlyList <IStorageItem> itemsToPaste = await packageView.GetStorageItemsAsync();

            if (!packageView.Contains(StandardDataFormats.StorageItems))
            {
                // Happens if you copy some text and then you Ctrl+V in FilesUWP
                // Should this be done in ModernShellPage?
                return;
            }
            if (AppInstance.FilesystemViewModel.WorkingDirectory.StartsWith(App.AppSettings.RecycleBinPath))
            {
                // Do not paste files and folders inside the recycle bin
                await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("ErrorDialogThisActionCannotBeDone"), ResourceController.GetTranslation("ErrorDialogUnsupportedOperation"));

                return;
            }

            List <IStorageItem>    pastedSourceItems = new List <IStorageItem>();
            HashSet <IStorageItem> pastedItems       = new HashSet <IStorageItem>();
            var  totalItemsSize       = CalculateTotalItemsSize(itemsToPaste);
            bool isItemSizeUnreported = totalItemsSize <= 0;

            foreach (IStorageItem item in itemsToPaste)
            {
                if (item.IsOfType(StorageItemTypes.Folder))
                {
                    if (!string.IsNullOrEmpty(item.Path) && destinationPath.IsSubPathOf(item.Path))
                    {
                        ImpossibleActionResponseTypes responseType = ImpossibleActionResponseTypes.Abort;

                        /// Currently following implementation throws exception until it is resolved keep it disabled

                        /*Binding themeBind = new Binding();
                         * themeBind.Source = ThemeHelper.RootTheme;
                         *
                         * ContentDialog dialog = new ContentDialog()
                         * {
                         *  Title = ResourceController.GetTranslation("ErrorDialogThisActionCannotBeDone"),
                         *  Content = ResourceController.GetTranslation("ErrorDialogTheDestinationFolder") + " (" + destinationPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last() + ") " + ResourceController.GetTranslation("ErrorDialogIsASubfolder") + " (" + item.Name + ")",
                         *  PrimaryButtonText = ResourceController.GetTranslation("ErrorDialogSkip"),
                         *  CloseButtonText = ResourceController.GetTranslation("ErrorDialogCancel"),
                         *  PrimaryButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Skip; }),
                         *  CloseButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Abort; }),
                         * };
                         * BindingOperations.SetBinding(dialog, FrameworkElement.RequestedThemeProperty, themeBind);
                         *
                         * await dialog.ShowAsync();*/
                        if (responseType == ImpossibleActionResponseTypes.Skip)
                        {
                            continue;
                        }
                        else if (responseType == ImpossibleActionResponseTypes.Abort)
                        {
                            return;
                        }
                    }
                    else
                    {
                        if (!isItemSizeUnreported)
                        {
                            var pastedItemSize = await Task.Run(() => CalculateTotalItemsSize(pastedSourceItems));

                            uint progressValue = (uint)(pastedItemSize * 100 / totalItemsSize);
                            progress.Report(progressValue);
                        }

                        try
                        {
                            ClonedDirectoryOutput pastedOutput = await CloneDirectoryAsync(
                                (StorageFolder)item,
                                await ItemViewModel.GetFolderFromPathAsync(destinationPath),
                                item.Name);

                            pastedSourceItems.Add(item);
                            pastedItems.Add(pastedOutput.FolderOutput);
                        }
                        catch (FileNotFoundException)
                        {
                            // Folder was moved/deleted in the meantime
                            continue;
                        }
                    }
                }
                else if (item.IsOfType(StorageItemTypes.File))
                {
                    if (!isItemSizeUnreported)
                    {
                        var pastedItemSize = await Task.Run(() => CalculateTotalItemsSize(pastedSourceItems));

                        uint progressValue = (uint)(pastedItemSize * 100 / totalItemsSize);
                        progress.Report(progressValue);
                    }

                    try
                    {
                        StorageFile clipboardFile = (StorageFile)item;
                        StorageFile pastedFile    = await clipboardFile.CopyAsync(
                            await ItemViewModel.GetFolderFromPathAsync(destinationPath),
                            item.Name,
                            NameCollisionOption.GenerateUniqueName);

                        pastedSourceItems.Add(item);
                        pastedItems.Add(pastedFile);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // Try again with CopyFileFromApp
                        if (NativeDirectoryChangesHelper.CopyFileFromApp(item.Path, Path.Combine(destinationPath, item.Name), true))
                        {
                            pastedSourceItems.Add(item);
                        }
                        else
                        {
                            Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                        }
                    }
                    catch (FileNotFoundException)
                    {
                        // File was moved/deleted in the meantime
                        continue;
                    }
                }
            }
            if (!isItemSizeUnreported)
            {
                var finalPastedItemSize = await Task.Run(() => CalculateTotalItemsSize(pastedSourceItems));

                uint finalProgressValue = (uint)(finalPastedItemSize * 100 / totalItemsSize);
                progress.Report(finalProgressValue);
            }
            else
            {
                progress.Report(100);
            }

            if (acceptedOperation == DataPackageOperation.Move)
            {
                foreach (IStorageItem item in pastedSourceItems)
                {
                    try
                    {
                        if (string.IsNullOrEmpty(item.Path))
                        {
                            // Can't move (only copy) files from MTP devices because:
                            // StorageItems returned in DataPackageView are read-only
                            // The item.Path property will be empty and there's no way of retrieving a new StorageItem with R/W access
                            continue;
                        }
                        if (item.IsOfType(StorageItemTypes.File))
                        {
                            // If we reached this we are not in an MTP device, using StorageFile.* is ok here
                            StorageFile file = await StorageFile.GetFileFromPathAsync(item.Path);

                            await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
                        }
                        else if (item.IsOfType(StorageItemTypes.Folder))
                        {
                            // If we reached this we are not in an MTP device, using StorageFolder.* is ok here
                            StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(item.Path);

                            await folder.DeleteAsync(StorageDeleteOption.PermanentDelete);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // Try again with DeleteFileFromApp
                        if (!NativeDirectoryChangesHelper.DeleteFileFromApp(item.Path))
                        {
                            Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                        }
                    }
                    catch (FileNotFoundException)
                    {
                        // File or Folder was moved/deleted in the meantime
                        continue;
                    }
                    ListedItem listedItem = AppInstance.FilesystemViewModel.FilesAndFolders.FirstOrDefault(listedItem => listedItem.ItemPath.Equals(item.Path, StringComparison.OrdinalIgnoreCase));
                }
            }

            if (destinationPath == AppInstance.FilesystemViewModel.WorkingDirectory)
            {
                List <string>     pastedItemPaths = pastedItems.Select(item => item.Path).ToList();
                List <ListedItem> copiedItems     = AppInstance.FilesystemViewModel.FilesAndFolders.Where(listedItem => pastedItemPaths.Contains(listedItem.ItemPath)).ToList();
                if (copiedItems.Any())
                {
                    AppInstance.ContentPage.SetSelectedItemsOnUi(copiedItems);
                    AppInstance.ContentPage.FocusSelectedItems();
                }
            }
            packageView.ReportOperationCompleted(acceptedOperation);
        }
Exemple #18
0
        public static async void PasteItemWithStatus(DataPackageView packageView, string destinationPath, DataPackageOperation acceptedOperation)
        {
            var CurrentInstance       = App.CurrentInstance;
            PostedStatusBanner banner = App.CurrentInstance.StatusBarControl.OngoingTasksControl.PostBanner(
                null,
                CurrentInstance.FilesystemViewModel.WorkingDirectory,
                0,
                StatusBanner.StatusBannerSeverity.Ongoing,
                StatusBanner.StatusBannerOperation.Paste);

            Stopwatch sw = new Stopwatch();

            sw.Start();

            await PasteItem(packageView, destinationPath, acceptedOperation, CurrentInstance, banner.Progress);

            banner.Remove();

            sw.Stop();

            if (sw.Elapsed.TotalSeconds >= 10)
            {
                App.CurrentInstance.StatusBarControl.OngoingTasksControl.PostBanner(
                    "Paste Complete",
                    "The operation has completed.",
                    0,
                    StatusBanner.StatusBannerSeverity.Success,
                    StatusBanner.StatusBannerOperation.Paste);
            }
        }
Exemple #19
0
 internal TabViewTabDragCompletedEventArgs(DataPackageOperation dropResult, object item, TabViewItem tab)
 {
     DropResult = dropResult;
     Item       = item;
     Tab        = tab;
 }
Exemple #20
0
 void IDataPackageViewResolver.ReportOperationCompleted(DataPackageView dataPackageView, DataPackageOperation value) => dataPackageView.ReportOperationCompleted(value);
 private static DragDropEffects ToDropEffects(DataPackageOperation uwpOp)
 => (DragDropEffects)((int)uwpOp) & (DragDropEffects.Copy | DragDropEffects.Move | DragDropEffects.Link);
Exemple #22
0
 /// <summary>
 /// Informs the system that your app is finished using the DataPackageView object. Primarily used for Clipboard operations.
 /// </summary>
 /// <param name="dataPackageView">The requested <see cref="DataPackageView"/>.</param>
 /// <param name="value">An enumeration that states what operation (such as copy or move) was completed. At most one operation flag can be set.</param>
 public static void ReportOperationCompletedWrapped(this DataPackageView dataPackageView, DataPackageOperation value) => Resolver.ReportOperationCompleted(dataPackageView, value);
Exemple #23
0
        public async Task PasteItems(DataPackageView packageView, string destinationPath, DataPackageOperation acceptedOperation)
        {
            itemsToPaste = await packageView.GetStorageItemsAsync();

            HashSet <IStorageItem> pastedItems = new HashSet <IStorageItem>();

            itemsPasted = 0;
            if (itemsToPaste.Count > 3)
            {
                (App.CurrentInstance as ModernShellPage).UpdateProgressFlyout(InteractionOperationType.PasteItems, itemsPasted, itemsToPaste.Count);
            }

            foreach (IStorageItem item in itemsToPaste)
            {
                if (item.IsOfType(StorageItemTypes.Folder))
                {
                    if (destinationPath.IsSubPathOf(item.Path))
                    {
                        ImpossibleActionResponseTypes responseType = ImpossibleActionResponseTypes.Abort;
                        Binding themeBind = new Binding();
                        themeBind.Source = ThemeHelper.RootTheme;

                        ContentDialog dialog = new ContentDialog()
                        {
                            Title                = ResourceController.GetTranslation("ErrorDialogThisActionCannotBeDone"),
                            Content              = ResourceController.GetTranslation("ErrorDialogTheDestinationFolder") + " (" + destinationPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last() + ") " + ResourceController.GetTranslation("ErrorDialogIsASubfolder") + " (" + item.Name + ")",
                            PrimaryButtonText    = ResourceController.GetTranslation("ErrorDialogSkip"),
                            CloseButtonText      = ResourceController.GetTranslation("ErrorDialogCancel"),
                            PrimaryButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Skip; }),
                            CloseButtonCommand   = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Abort; })
                        };
                        BindingOperations.SetBinding(dialog, FrameworkElement.RequestedThemeProperty, themeBind);

                        await dialog.ShowAsync();

                        if (responseType == ImpossibleActionResponseTypes.Skip)
                        {
                            continue;
                        }
                        else if (responseType == ImpossibleActionResponseTypes.Abort)
                        {
                            return;
                        }
                    }
                    else
                    {
                        StorageFolder pastedFolder = await CloneDirectoryAsync(item.Path, destinationPath, item.Name, false);

                        pastedItems.Add(pastedFolder);
                        if (destinationPath == CurrentInstance.ViewModel.WorkingDirectory)
                        {
                            CurrentInstance.ViewModel.AddFolder(pastedFolder.Path);
                        }
                    }
                }
                else if (item.IsOfType(StorageItemTypes.File))
                {
                    if (itemsToPaste.Count > 3)
                    {
                        (App.CurrentInstance as ModernShellPage).UpdateProgressFlyout(InteractionOperationType.PasteItems, ++itemsPasted, itemsToPaste.Count);
                    }
                    StorageFile clipboardFile = await StorageFile.GetFileFromPathAsync(item.Path);

                    StorageFile pastedFile = await clipboardFile.CopyAsync(await StorageFolder.GetFolderFromPathAsync(destinationPath), item.Name, NameCollisionOption.GenerateUniqueName);

                    pastedItems.Add(pastedFile);
                    if (destinationPath == CurrentInstance.ViewModel.WorkingDirectory)
                    {
                        CurrentInstance.ViewModel.AddFile(pastedFile.Path);
                    }
                }
            }

            if (acceptedOperation == DataPackageOperation.Move)
            {
                foreach (IStorageItem item in itemsToPaste)
                {
                    if (item.IsOfType(StorageItemTypes.File))
                    {
                        StorageFile file = await StorageFile.GetFileFromPathAsync(item.Path);

                        await file.DeleteAsync();
                    }
                    else if (item.IsOfType(StorageItemTypes.Folder))
                    {
                        StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(item.Path);

                        await folder.DeleteAsync();
                    }
                    ListedItem listedItem = CurrentInstance.ViewModel.FilesAndFolders.FirstOrDefault(listedItem => listedItem.ItemPath.Equals(item.Path, StringComparison.OrdinalIgnoreCase));
                    if (listedItem != null)
                    {
                        CurrentInstance.ViewModel.RemoveFileOrFolder(listedItem);
                    }
                }
            }
            if (destinationPath == CurrentInstance.ViewModel.WorkingDirectory)
            {
                List <string>     pastedItemPaths = pastedItems.Select(item => item.Path).ToList();
                List <ListedItem> copiedItems     = CurrentInstance.ViewModel.FilesAndFolders.Where(listedItem => pastedItemPaths.Contains(listedItem.ItemPath)).ToList();
                CurrentInstance.ContentPage.SetSelectedItemsOnUi(copiedItems);
                CurrentInstance.ContentPage.FocusSelectedItems();
            }
            packageView.ReportOperationCompleted(acceptedOperation);
        }
Exemple #24
0
 /// <summary>
 /// Sets a value that specifies which operations are allowed by the originator of the drag event.
 /// </summary>
 /// <param name="e">The requested <see cref="DragEventArgs"/>.</param>
 /// <param name="acceptedOperation">
 /// A member of the DataPackageOperation enumeration that specifies which operations are allowed
 /// by the originator of the drag event.
 /// </param>
 public static void AcceptedOperation(this DragEventArgs e, DataPackageOperation acceptedOperation) => Resolver.AcceptedOperation(e, acceptedOperation);
Exemple #25
0
 /// <summary>
 /// Sets the allowed data package operations (none, move, copy and/or link) for the drag and drop operation.
 /// </summary>
 /// <param name="e">The requested <see cref="DragStartingEventArgs"/>.</param>
 /// <param name="dataPackageOperation">The allowed data operations.</param>
 public static void AllowedOperations(this DragStartingEventArgs e, DataPackageOperation dataPackageOperation) => Resolver.AllowedOperations(e, dataPackageOperation);
Exemple #26
0
        public static async Task <DataPackage> GetAsDataPackageAsync(this IEnumerable <FileSystemStorageItemBase> Collection, DataPackageOperation Operation)
        {
            DataPackage Package = new DataPackage
            {
                RequestedOperation = Operation
            };

            Package.Properties.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;

            FileSystemStorageItemBase[] StorageItems    = Collection.Where((Item) => Item is not IUnsupportedStorageItem).ToArray();
            FileSystemStorageItemBase[] NotStorageItems = Collection.Where((Item) => Item is IUnsupportedStorageItem).ToArray();

            if (StorageItems.Any())
            {
                List <IStorageItem> TempItemList = new List <IStorageItem>();

                foreach (FileSystemStorageItemBase Item in StorageItems)
                {
                    if (await Item.GetStorageItemAsync() is IStorageItem It)
                    {
                        TempItemList.Add(It);
                    }
                }

                if (TempItemList.Count > 0)
                {
                    Package.SetStorageItems(TempItemList, false);
                }
            }

            if (NotStorageItems.Any())
            {
                XmlDocument Document = new XmlDocument();

                XmlElement RootElemnt = Document.CreateElement("RX-Explorer");
                Document.AppendChild(RootElemnt);

                XmlElement KindElement = Document.CreateElement("Kind");
                KindElement.InnerText = "RX-Explorer-TransferNotStorageItem";
                RootElemnt.AppendChild(KindElement);

                foreach (FileSystemStorageItemBase Item in NotStorageItems)
                {
                    XmlElement InnerElement = Document.CreateElement("Item");
                    InnerElement.InnerText = Item.Path;
                    RootElemnt.AppendChild(InnerElement);
                }

                Package.SetText(Document.GetXml());
            }

            return(Package);
        }
Exemple #27
0
 internal OperationCompletedEventArgs(string?acceptedFormatId, DataPackageOperation operation)
 {
     AcceptedFormatId = acceptedFormatId;
     Operation        = operation;
 }
Exemple #28
0
 void IDragEventArgsResolver.AcceptedOperation(DragEventArgs e, DataPackageOperation acceptedOperation) => e.AcceptedOperation = acceptedOperation;
Exemple #29
0
 void IDragStartingEventArgsResolver.AllowedOperations(DragStartingEventArgs e, DataPackageOperation dataPackageOperation) => e.AllowedOperations = dataPackageOperation;
 public void ReportOperationCompleted( DataPackageOperation value )
 {
     adapted.ReportOperationCompleted( value );
 }