public async Task <string?> TryGetTextAsync()
        {
            try
            {
                DataPackageView view = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();

                // Try to extract the requested content
                string?item;
                if (view.Contains(StandardDataFormats.Text))
                {
                    item = await view.GetTextAsync();

                    view.ReportOperationCompleted(DataPackageOperation.Copy);
                }
                else
                {
                    item = null;
                }

                return(item);
            }
            catch
            {
                // Y u do dis?
                return(null);
            }
        }
示例#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);
            }
        }
示例#3
0
文件: Paste.cs 项目: askfriends/Files
        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);
        }
示例#4
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);
        }
示例#5
0
 void IDataPackageViewResolver.ReportOperationCompleted(DataPackageView dataPackageView, DataPackageOperation value) => dataPackageView.ReportOperationCompleted(value);
示例#6
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);
        }