private async void RecentsView_ItemClick(object sender, ItemClickEventArgs e) { var path = (e.ClickedItem as RecentItem).RecentPath; try { await Interaction.InvokeWin32Component(path); } catch (UnauthorizedAccessException) { await App.ConsentDialogDisplay.ShowAsync(); } catch (ArgumentException) { if (new DirectoryInfo(path).Root.ToString().Contains(@"C:\")) { App.CurrentInstance.ContentFrame.Navigate(App.AppSettings.GetLayoutType(), path); } else { foreach (DriveItem drive in App.AppSettings.DrivesManager.Drives) { if (drive.Path.ToString() == new DirectoryInfo(path).Root.ToString()) { App.CurrentInstance.ContentFrame.Navigate(App.AppSettings.GetLayoutType(), path); return; } } } } catch (COMException) { await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("DriveUnpluggedDialog.Title"), ResourceController.GetTranslation("DriveUnpluggedDialog.Text")); } }
public static async void CreateFile(AddItemType itemType) { string currentPath = null; if (App.CurrentInstance.ContentPage != null) { currentPath = App.CurrentInstance.FilesystemViewModel.WorkingDirectory; } StorageFolderWithPath folderWithPath = await ItemViewModel.GetFolderWithPathFromPathAsync(currentPath); StorageFolder folderToCreateItem = folderWithPath.Folder; // Show rename dialog RenameDialog renameDialog = new RenameDialog(); var renameResult = await renameDialog.ShowAsync(); if (renameResult != ContentDialogResult.Primary) { return; } // Create file based on dialog result string userInput = renameDialog.storedRenameInput; try { switch (itemType) { case AddItemType.Folder: userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : "NewFolder".GetLocalized(); await folderToCreateItem.CreateFolderAsync(userInput, CreationCollisionOption.GenerateUniqueName); break; case AddItemType.TextDocument: userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : "NewTextDocument".GetLocalized(); await folderToCreateItem.CreateFileAsync(userInput + ".txt", CreationCollisionOption.GenerateUniqueName); break; case AddItemType.BitmapImage: userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : "NewBitmapImage".GetLocalized(); await folderToCreateItem.CreateFileAsync(userInput + ".bmp", CreationCollisionOption.GenerateUniqueName); break; } } catch (UnauthorizedAccessException) { await DialogDisplayHelper.ShowDialog("AccessDeniedCreateDialog/Title".GetLocalized(), "AccessDeniedCreateDialog/Text".GetLocalized()); } }
private async void RecentFilesWidget_RecentFileInvoked(object sender, UserControls.PathNavigationEventArgs e) { try { var directoryName = Path.GetDirectoryName(e.ItemPath); await AppInstance.InteractionOperations.InvokeWin32Component(e.ItemPath, workingDir : directoryName); } catch (UnauthorizedAccessException) { var consentDialog = new ConsentDialog(); await consentDialog.ShowAsync(); } catch (ArgumentException) { if (new DirectoryInfo(e.ItemPath).Root.ToString().Contains(@"C:\")) { AppInstance.ContentFrame.Navigate(AppSettings.GetLayoutType(), new NavigationArguments() { AssociatedTabInstance = AppInstance, NavPathParam = e.ItemPath }); } else { foreach (DriveItem drive in AppSettings.DrivesManager.Drives) { if (drive.Path.ToString() == new DirectoryInfo(e.ItemPath).Root.ToString()) { AppInstance.ContentFrame.Navigate(AppSettings.GetLayoutType(), new NavigationArguments() { AssociatedTabInstance = AppInstance, NavPathParam = e.ItemPath }); return; } } } } catch (COMException) { await DialogDisplayHelper.ShowDialog( "DriveUnpluggedDialog/Title".GetLocalized(), "DriveUnpluggedDialog/Text".GetLocalized()); } }
public async void ToggleQuickLook() { try { if (CurrentInstance.ContentPage.IsItemSelected && !App.CurrentInstance.ContentPage.isRenamingItem) { var clickedOnItem = CurrentInstance.ContentPage.SelectedItem; Debug.WriteLine("Toggle QuickLook"); ApplicationData.Current.LocalSettings.Values["path"] = clickedOnItem.ItemPath; ApplicationData.Current.LocalSettings.Values["Arguments"] = "ToggleQuickLook"; await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); } } catch (FileNotFoundException) { await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("FileNotFoundDialog.Title"), ResourceController.GetTranslation("FileNotFoundPreviewDialog.Text")); NavigationActions.Refresh_Click(null, null); } }
private async void RemoveOneFrequentItem(object sender, RoutedEventArgs e) { // Get the sender frameworkelement if (sender is MenuFlyoutItem fe) { // Grab it's datacontext ViewModel and remove it from the list. if (fe.DataContext is RecentItem vm) { if (await DialogDisplayHelper.ShowDialog("Remove item from Recents List", "Do you wish to remove " + vm.Name + " from the list?", "Yes", "No")) { // remove it from the visible collection recentItemsCollection.Remove(vm); // Now clear it also from the recent list cache permanently. // No token stored in the viewmodel, so need to find it the old fashioned way. var mru = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList; foreach (var element in mru.Entries) { var f = await mru.GetItemAsync(element.Token); if (f.Path == vm.RecentPath || element.Metadata == vm.RecentPath) { mru.Remove(element.Token); if (recentItemsCollection.Count == 0) { Empty.Visibility = Visibility.Visible; } break; } } } } } }
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); }
public async void CheckPathInput(ItemViewModel instance, string currentInput, string currentSelectedPath) { if (currentSelectedPath == currentInput) { return; } if (currentInput != instance.WorkingDirectory || App.CurrentInstance.ContentFrame.CurrentSourcePageType == typeof(YourHome)) { //(App.CurrentInstance.OperationsControl as RibbonArea).RibbonViewModel.HomeItems.isEnabled = false; //(App.CurrentInstance.OperationsControl as RibbonArea).RibbonViewModel.ShareItems.isEnabled = false; if (currentInput.Equals("Home", StringComparison.OrdinalIgnoreCase) || currentInput.Equals(ResourceController.GetTranslation("NewTab"), StringComparison.OrdinalIgnoreCase)) { await App.CurrentInstance.FilesystemViewModel.SetWorkingDirectory(ResourceController.GetTranslation("NewTab")); App.CurrentInstance.ContentFrame.Navigate(typeof(YourHome), ResourceController.GetTranslation("NewTab"), new SuppressNavigationTransitionInfo()); } else { var workingDir = string.IsNullOrEmpty(App.CurrentInstance.FilesystemViewModel.WorkingDirectory) ? AppSettings.HomePath : App.CurrentInstance.FilesystemViewModel.WorkingDirectory; currentInput = StorageFileExtensions.GetPathWithoutEnvironmentVariable(currentInput); if (currentSelectedPath == currentInput) { return; } var item = await DrivesManager.GetRootFromPath(currentInput); try { var pathToNavigate = (await StorageFileExtensions.GetFolderWithPathFromPathAsync(currentInput, item)).Path; App.CurrentInstance.ContentFrame.Navigate(AppSettings.GetLayoutType(), pathToNavigate); // navigate to folder } catch (Exception) // Not a folder or inaccessible { try { var pathToInvoke = (await StorageFileExtensions.GetFileWithPathFromPathAsync(currentInput, item)).Path; await Interaction.InvokeWin32Component(pathToInvoke); } catch (Exception ex) // Not a file or not accessible { // Launch terminal application if possible foreach (var terminal in AppSettings.TerminalController.Model.Terminals) { if (terminal.Path.Equals(currentInput, StringComparison.OrdinalIgnoreCase) || terminal.Path.Equals(currentInput + ".exe", StringComparison.OrdinalIgnoreCase)) { if (App.Connection != null) { var value = new ValueSet { { "WorkingDirectory", workingDir }, { "Application", terminal.Path }, { "Arguments", string.Format(terminal.Arguments, Helpers.PathNormalization.NormalizePath(App.CurrentInstance.FilesystemViewModel.WorkingDirectory)) } }; await App.Connection.SendMessageAsync(value); } return; } } try { if (!await Launcher.LaunchUriAsync(new Uri(currentInput))) { throw new Exception(); } } catch { await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("InvalidItemDialogTitle"), string.Format(ResourceController.GetTranslation("InvalidItemDialogContent"), ex.Message)); } } } } App.CurrentInstance.NavigationToolbar.PathControlDisplayText = App.CurrentInstance.FilesystemViewModel.WorkingDirectory; } }
public async void DeleteItem_Click(object sender, RoutedEventArgs e) { if (App.AppSettings.ShowConfirmDeleteDialog == true) //check if the setting to show a confirmation dialog is on { var dialog = new ConfirmDeleteDialog(); await dialog.ShowAsync(); if (dialog.Result != MyResult.Delete) //delete selected item(s) if the result is yes { return; //return if the result isn't delete } } try { var CurrentInstance = App.CurrentInstance; List <ListedItem> selectedItems = new List <ListedItem>(); foreach (ListedItem selectedItem in CurrentInstance.ContentPage.SelectedItems) { selectedItems.Add(selectedItem); } int itemsDeleted = 0; if (selectedItems.Count > 3) { (App.CurrentInstance as ModernShellPage).UpdateProgressFlyout(InteractionOperationType.DeleteItems, itemsDeleted, selectedItems.Count); } foreach (ListedItem storItem in selectedItems) { if (selectedItems.Count > 3) { (App.CurrentInstance as ModernShellPage).UpdateProgressFlyout(InteractionOperationType.DeleteItems, ++itemsDeleted, selectedItems.Count); } IStorageItem item; try { if (storItem.PrimaryItemAttribute == StorageItemTypes.File) { item = await StorageFile.GetFileFromPathAsync(storItem.ItemPath); } else { item = await StorageFolder.GetFolderFromPathAsync(storItem.ItemPath); } await item.DeleteAsync(App.InteractionViewModel.PermanentlyDelete); } catch (FileLoadException) { // try again if (storItem.PrimaryItemAttribute == StorageItemTypes.File) { item = await StorageFile.GetFileFromPathAsync(storItem.ItemPath); } else { item = await StorageFolder.GetFolderFromPathAsync(storItem.ItemPath); } await item.DeleteAsync(App.InteractionViewModel.PermanentlyDelete); } CurrentInstance.ViewModel.RemoveFileOrFolder(storItem); } App.CurrentInstance.NavigationToolbar.CanGoForward = false; } catch (UnauthorizedAccessException) { await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("AccessDeniedDeleteDialog.Title"), ResourceController.GetTranslation("AccessDeniedDeleteDialog.Text")); } catch (FileNotFoundException) { await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("FileNotFoundDialog.Title"), ResourceController.GetTranslation("FileNotFoundDialog.Text")); } App.InteractionViewModel.PermanentlyDelete = StorageDeleteOption.Default; //reset PermanentlyDelete flag }
private async void OpenSelectedItems(bool displayApplicationPicker) { try { int selectedItemCount; Type sourcePageType = App.CurrentInstance.CurrentPageType; selectedItemCount = CurrentInstance.ContentPage.SelectedItems.Count; // Access MRU List var mostRecentlyUsed = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList; if (selectedItemCount == 1) { var clickedOnItem = CurrentInstance.ContentPage.SelectedItem; var clickedOnItemPath = clickedOnItem.ItemPath; if (clickedOnItem.PrimaryItemAttribute == StorageItemTypes.Folder) { // Add location to MRU List mostRecentlyUsed.Add(await StorageFolder.GetFolderFromPathAsync(clickedOnItemPath)); CurrentInstance.ViewModel.WorkingDirectory = clickedOnItemPath; CurrentInstance.NavigationToolbar.PathControlDisplayText = clickedOnItemPath; CurrentInstance.ContentPage.AssociatedViewModel.EmptyTextState.IsVisible = Visibility.Collapsed; CurrentInstance.ContentFrame.Navigate(sourcePageType, clickedOnItemPath, new SuppressNavigationTransitionInfo()); } else { // Add location to MRU List mostRecentlyUsed.Add(await StorageFile.GetFileFromPathAsync(clickedOnItem.ItemPath)); if (displayApplicationPicker) { StorageFile file = await StorageFile.GetFileFromPathAsync(clickedOnItem.ItemPath); var options = new LauncherOptions { DisplayApplicationPicker = true }; await Launcher.LaunchFileAsync(file, options); } else { await InvokeWin32Component(clickedOnItem.ItemPath); } } } else if (selectedItemCount > 1) { foreach (ListedItem clickedOnItem in CurrentInstance.ContentPage.SelectedItems) { if (clickedOnItem.PrimaryItemAttribute == StorageItemTypes.Folder) { instanceTabsView.AddNewTab(typeof(ModernShellPage), clickedOnItem.ItemPath); } else { // Add location to MRU List mostRecentlyUsed.Add(await StorageFile.GetFileFromPathAsync(clickedOnItem.ItemPath)); if (displayApplicationPicker) { StorageFile file = await StorageFile.GetFileFromPathAsync(clickedOnItem.ItemPath); var options = new LauncherOptions { DisplayApplicationPicker = true }; await Launcher.LaunchFileAsync(file, options); } else { await InvokeWin32Component(clickedOnItem.ItemPath); } } } } } catch (FileNotFoundException) { await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("FileNotFoundDialog.Title"), ResourceController.GetTranslation("FileNotFoundDialog.Text")); NavigationActions.Refresh_Click(null, null); } }