Beispiel #1
0
        private static async Task <FilesystemResult> OpenLibrary(string path, IShellPage associatedInstance, IEnumerable <string> selectItems)
        {
            IUserSettingsService userSettingsService = Ioc.Default.GetService <IUserSettingsService>();

            var  opened       = (FilesystemResult)false;
            bool isHiddenItem = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Hidden);

            if (isHiddenItem)
            {
                if (userSettingsService.PreferencesSettingsService.OpenFoldersInNewTab)
                {
                    await OpenPathInNewTab(path);
                }
                else
                {
                    associatedInstance.NavToolbarViewModel.PathControlDisplayText = path;
                    associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
                    {
                        NavPathParam          = path,
                        AssociatedTabInstance = associatedInstance
                    });
                }
                opened = (FilesystemResult)true;
            }
            else if (App.LibraryManager.TryGetLibrary(path, out LibraryLocationItem library))
            {
                opened = (FilesystemResult)await library.CheckDefaultSaveFolderAccess();

                if (opened)
                {
                    if (userSettingsService.PreferencesSettingsService.OpenFoldersInNewTab)
                    {
                        await OpenPathInNewTab(library.Text);
                    }
                    else
                    {
                        associatedInstance.NavToolbarViewModel.PathControlDisplayText = library.Text;
                        associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
                        {
                            NavPathParam          = path,
                            AssociatedTabInstance = associatedInstance,
                            SelectItems           = selectItems,
                        });
                    }
                }
            }
            return(opened);
        }
Beispiel #2
0
        private static async Task <FilesystemResult> OpenFile(string path, IShellPage associatedInstance, IEnumerable <string> selectItems, ShortcutItem shortcutInfo, bool openViaApplicationPicker = false, string args = default)
        {
            var  opened         = (FilesystemResult)false;
            bool isHiddenItem   = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Hidden);
            bool isShortcutItem = path.EndsWith(".lnk") || path.EndsWith(".url"); // Determine

            if (isShortcutItem)
            {
                if (string.IsNullOrEmpty(shortcutInfo.TargetPath))
                {
                    await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance, args);
                }
                else
                {
                    if (!path.EndsWith(".url"))
                    {
                        StorageFileWithPath childFile = await associatedInstance.FilesystemViewModel.GetFileWithPathFromPathAsync(shortcutInfo.TargetPath);

                        if (childFile != null)
                        {
                            // Add location to MRU List
                            if (childFile.File is SystemStorageFile)
                            {
                                var mostRecentlyUsed = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList;
                                mostRecentlyUsed.Add(await childFile.File.ToStorageFileAsync(), childFile.Path);
                            }
                        }
                    }
                    await Win32Helpers.InvokeWin32ComponentAsync(shortcutInfo.TargetPath, associatedInstance, $"{args} {shortcutInfo.Arguments}", shortcutInfo.RunAsAdmin, shortcutInfo.WorkingDirectory);
                }
                opened = (FilesystemResult)true;
            }
            else if (isHiddenItem)
            {
                await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance, args);
            }
            else
            {
                opened = await associatedInstance.FilesystemViewModel.GetFileWithPathFromPathAsync(path)
                         .OnSuccess(async childFile =>
                {
                    // Add location to MRU List
                    if (childFile.File is SystemStorageFile)
                    {
                        var mostRecentlyUsed = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList;
                        mostRecentlyUsed.Add(await childFile.File.ToStorageFileAsync(), childFile.Path);
                    }

                    if (openViaApplicationPicker)
                    {
                        LauncherOptions options = new LauncherOptions
                        {
                            DisplayApplicationPicker = true
                        };
                        if (!await Launcher.LaunchFileAsync(childFile.File, options))
                        {
                            var connection = await AppServiceConnectionHelper.Instance;
                            if (connection != null)
                            {
                                await connection.SendMessageAsync(new ValueSet()
                                {
                                    { "Arguments", "InvokeVerb" },
                                    { "FilePath", path },
                                    { "Verb", "openas" }
                                });
                            }
                        }
                    }
                    else
                    {
                        //try using launcher first
                        bool launchSuccess = false;

                        BaseStorageFileQueryResult fileQueryResult = null;

                        //Get folder to create a file query (to pass to apps like Photos, Movies & TV..., needed to scroll through the folder like what Windows Explorer does)
                        BaseStorageFolder currentFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(path));

                        if (currentFolder != null)
                        {
                            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, null);

                            //We can have many sort entries
                            SortEntry sortEntry = new SortEntry()
                            {
                                AscendingOrder = associatedInstance.InstanceViewModel.FolderSettings.DirectorySortDirection == SortDirection.Ascending
                            };

                            //Basically we tell to the launched app to follow how we sorted the files in the directory.
                            var sortOption = associatedInstance.InstanceViewModel.FolderSettings.DirectorySortOption;

                            switch (sortOption)
                            {
                            case Enums.SortOption.Name:
                                sortEntry.PropertyName = "System.ItemNameDisplay";
                                queryOptions.SortOrder.Clear();
                                queryOptions.SortOrder.Add(sortEntry);
                                break;

                            case Enums.SortOption.DateModified:
                                sortEntry.PropertyName = "System.DateModified";
                                queryOptions.SortOrder.Clear();
                                queryOptions.SortOrder.Add(sortEntry);
                                break;

                            case Enums.SortOption.DateCreated:
                                sortEntry.PropertyName = "System.DateCreated";
                                queryOptions.SortOrder.Clear();
                                queryOptions.SortOrder.Add(sortEntry);
                                break;

                            //Unfortunately this is unsupported | Remarks: https://docs.microsoft.com/en-us/uwp/api/windows.storage.search.queryoptions.sortorder?view=winrt-19041
                            //case Enums.SortOption.Size:

                            //sortEntry.PropertyName = "System.TotalFileSize";
                            //queryOptions.SortOrder.Clear();
                            //queryOptions.SortOrder.Add(sortEntry);
                            //break;

                            //Unfortunately this is unsupported | Remarks: https://docs.microsoft.com/en-us/uwp/api/windows.storage.search.queryoptions.sortorder?view=winrt-19041
                            //case Enums.SortOption.FileType:

                            //sortEntry.PropertyName = "System.FileExtension";
                            //queryOptions.SortOrder.Clear();
                            //queryOptions.SortOrder.Add(sortEntry);
                            //break;

                            //Handle unsupported
                            default:
                                //keep the default one in SortOrder IList
                                break;
                            }

                            var options = new LauncherOptions();
                            if (currentFolder.AreQueryOptionsSupported(queryOptions))
                            {
                                fileQueryResult = currentFolder.CreateFileQueryWithOptions(queryOptions);
                                options.NeighboringFilesQuery = fileQueryResult.ToStorageFileQueryResult();
                            }

                            // Now launch file with options.
                            launchSuccess = await Launcher.LaunchFileAsync(await childFile.File.ToStorageFileAsync(), options);
                        }

                        if (!launchSuccess)
                        {
                            await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance, args);
                        }
                    }
                });
            }
            return(opened);
        }
Beispiel #3
0
        private static async Task <FilesystemResult> OpenDirectory(string path, IShellPage associatedInstance, IEnumerable <string> selectItems, ShortcutItem shortcutInfo)
        {
            IUserSettingsService userSettingsService = Ioc.Default.GetService <IUserSettingsService>();

            var  opened         = (FilesystemResult)false;
            bool isHiddenItem   = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Hidden);
            bool isShortcutItem = path.EndsWith(".lnk") || path.EndsWith(".url"); // Determine

            if (isShortcutItem)
            {
                if (string.IsNullOrEmpty(shortcutInfo.TargetPath))
                {
                    await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance);

                    opened = (FilesystemResult)true;
                }
                else
                {
                    if (userSettingsService.PreferencesSettingsService.OpenFoldersInNewTab)
                    {
                        await OpenPathInNewTab(shortcutInfo.TargetPath);
                    }
                    else
                    {
                        associatedInstance.NavToolbarViewModel.PathControlDisplayText = shortcutInfo.TargetPath;
                        associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(shortcutInfo.TargetPath), new NavigationArguments()
                        {
                            NavPathParam          = shortcutInfo.TargetPath,
                            AssociatedTabInstance = associatedInstance,
                            SelectItems           = selectItems
                        });
                    }

                    opened = (FilesystemResult)true;
                }
            }
            else if (isHiddenItem)
            {
                if (userSettingsService.PreferencesSettingsService.OpenFoldersInNewTab)
                {
                    await OpenPathInNewTab(path);
                }
                else
                {
                    associatedInstance.NavToolbarViewModel.PathControlDisplayText = path;
                    associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
                    {
                        NavPathParam          = path,
                        AssociatedTabInstance = associatedInstance
                    });
                }

                opened = (FilesystemResult)true;
            }
            else
            {
                opened = await associatedInstance.FilesystemViewModel.GetFolderWithPathFromPathAsync(path)
                         .OnSuccess(async(childFolder) =>
                {
                    // Add location to MRU List
                    if (childFolder.Folder is SystemStorageFolder)
                    {
                        var mostRecentlyUsed = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList;
                        mostRecentlyUsed.Add(await childFolder.Folder.ToStorageFolderAsync(), childFolder.Path);
                    }
                });

                if (!opened)
                {
                    opened = (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path);
                }
                if (opened)
                {
                    if (userSettingsService.PreferencesSettingsService.OpenFoldersInNewTab)
                    {
                        await OpenPathInNewTab(path);
                    }
                    else
                    {
                        associatedInstance.NavToolbarViewModel.PathControlDisplayText = path;
                        associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
                        {
                            NavPathParam          = path,
                            AssociatedTabInstance = associatedInstance,
                            SelectItems           = selectItems
                        });
                    }
                }
            }
            return(opened);
        }
Beispiel #4
0
        /// <summary>
        /// Navigates to a directory or opens file
        /// </summary>
        /// <param name="path">The path to navigate to or open</param>
        /// <param name="associatedInstance">The instance associated with view</param>
        /// <param name="itemType"></param>
        /// <param name="openSilent">Determines whether history of opened item is saved (... to Recent Items/Windows Timeline/opening in background)</param>
        /// <param name="openViaApplicationPicker">Determines whether open file using application picker</param>
        /// <param name="selectItems">List of filenames that are selected upon navigation</param>
        public static async Task <bool> OpenPath(string path, IShellPage associatedInstance, FilesystemItemType?itemType = null, bool openSilent = false, bool openViaApplicationPicker = false, IEnumerable <string> selectItems = null, string args = default)
        {
            string           previousDir    = associatedInstance.FilesystemViewModel.WorkingDirectory;
            bool             isHiddenItem   = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Hidden);
            bool             isShortcutItem = path.EndsWith(".lnk") || path.EndsWith(".url"); // Determine
            FilesystemResult opened         = (FilesystemResult)false;

            var shortcutInfo = new ShortcutItem();

            if (itemType == null || isShortcutItem || isHiddenItem)
            {
                if (isShortcutItem)
                {
                    var connection = await AppServiceConnectionHelper.Instance;
                    if (connection == null)
                    {
                        return(false);
                    }
                    var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
                    {
                        { "Arguments", "FileOperation" },
                        { "fileop", "ParseLink" },
                        { "filepath", path }
                    });

                    if (status == AppServiceResponseStatus.Success)
                    {
                        shortcutInfo.TargetPath           = response.Get("TargetPath", string.Empty);
                        shortcutInfo.Arguments            = response.Get("Arguments", string.Empty);
                        shortcutInfo.WorkingDirectory     = response.Get("WorkingDirectory", string.Empty);
                        shortcutInfo.RunAsAdmin           = response.Get("RunAsAdmin", false);
                        shortcutInfo.PrimaryItemAttribute = response.Get("IsFolder", false) ? StorageItemTypes.Folder : StorageItemTypes.File;

                        itemType = response.Get("IsFolder", false) ? FilesystemItemType.Directory : FilesystemItemType.File;
                    }
                    else
                    {
                        return(false);
                    }
                }
                else if (isHiddenItem)
                {
                    itemType = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Directory) ? FilesystemItemType.Directory : FilesystemItemType.File;
                }
                else
                {
                    itemType = await StorageItemHelpers.GetTypeFromPath(path);
                }
            }

            if (itemType == FilesystemItemType.Library)
            {
                opened = await OpenLibrary(path, associatedInstance, selectItems);
            }
            else if (itemType == FilesystemItemType.Directory)
            {
                opened = await OpenDirectory(path, associatedInstance, selectItems, shortcutInfo);
            }
            else if (itemType == FilesystemItemType.File)
            {
                opened = await OpenFile(path, associatedInstance, selectItems, shortcutInfo, openViaApplicationPicker, args);
            }

            if (opened.ErrorCode == FileSystemStatusCode.NotFound && !openSilent)
            {
                await DialogDisplayHelper.ShowDialogAsync("FileNotFoundDialog/Title".GetLocalized(), "FileNotFoundDialog/Text".GetLocalized());

                associatedInstance.NavToolbarViewModel.CanRefresh = false;
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    var ContentOwnedViewModelInstance = associatedInstance.FilesystemViewModel;
                    ContentOwnedViewModelInstance?.RefreshItems(previousDir);
                });
            }

            return(opened);
        }
Beispiel #5
0
 public static bool Exists(string path)
 {
     return(NativeFileOperationsHelper.GetFileAttributesExFromApp(path, NativeFileOperationsHelper.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, out _));
 }
Beispiel #6
0
        /// <summary>
        /// Navigates to a directory or opens file
        /// </summary>
        /// <param name="path">The path to navigate to or open</param>
        /// <param name="associatedInstance">The instance associated with view</param>
        /// <param name="itemType"></param>
        /// <param name="openSilent">Determines whether history of opened item is saved (... to Recent Items/Windows Timeline/opening in background)</param>
        /// <param name="openViaApplicationPicker">Determines whether open file using application picker</param>
        /// <param name="selectItems">List of filenames that are selected upon navigation</param>
        public static async Task <bool> OpenPath(string path, IShellPage associatedInstance, FilesystemItemType?itemType = null, bool openSilent = false, bool openViaApplicationPicker = false, IEnumerable <string> selectItems = null)
        // TODO: This function reliability has not been extensively tested
        {
            string           previousDir    = associatedInstance.FilesystemViewModel.WorkingDirectory;
            bool             isHiddenItem   = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Hidden);
            bool             isShortcutItem = path.EndsWith(".lnk") || path.EndsWith(".url"); // Determine
            FilesystemResult opened         = (FilesystemResult)false;

            // Shortcut item variables
            string shortcutTargetPath       = null;
            string shortcutArguments        = null;
            string shortcutWorkingDirectory = null;
            bool   shortcutRunAsAdmin       = false;
            bool   shortcutIsFolder         = false;

            if (itemType == null || isShortcutItem || isHiddenItem)
            {
                if (isShortcutItem)
                {
                    var(status, response) = await associatedInstance.ServiceConnection?.SendMessageForResponseAsync(new ValueSet()
                    {
                        { "Arguments", "FileOperation" },
                        { "fileop", "ParseLink" },
                        { "filepath", path }
                    });

                    if (status == AppServiceResponseStatus.Success)
                    {
                        shortcutTargetPath       = response.Get("TargetPath", string.Empty);
                        shortcutArguments        = response.Get("Arguments", string.Empty);
                        shortcutWorkingDirectory = response.Get("WorkingDirectory", string.Empty);
                        shortcutRunAsAdmin       = response.Get("RunAsAdmin", false);
                        shortcutIsFolder         = response.Get("IsFolder", false);

                        itemType = shortcutIsFolder ? FilesystemItemType.Directory : FilesystemItemType.File;
                    }
                    else
                    {
                        return(false);
                    }
                }
                else if (isHiddenItem)
                {
                    itemType = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Directory) ? FilesystemItemType.Directory : FilesystemItemType.File;
                }
                else
                {
                    itemType = await StorageItemHelpers.GetTypeFromPath(path);
                }
            }

            var mostRecentlyUsed = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList;

            if (itemType == FilesystemItemType.Library) // OpenLibrary
            {
                if (isHiddenItem)
                {
                    associatedInstance.NavigationToolbar.PathControlDisplayText = path;
                    associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
                    {
                        NavPathParam          = path,
                        AssociatedTabInstance = associatedInstance
                    });
                    return(true);
                }
                else if (App.LibraryManager.TryGetLibrary(path, out LibraryLocationItem library))
                {
                    opened = (FilesystemResult)await library.CheckDefaultSaveFolderAccess();

                    if (opened)
                    {
                        associatedInstance.NavigationToolbar.PathControlDisplayText = library.Text;
                        associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
                        {
                            NavPathParam          = path,
                            AssociatedTabInstance = associatedInstance,
                            SelectItems           = selectItems,
                        });
                    }
                }
            }
            else if (itemType == FilesystemItemType.Directory) // OpenDirectory
            {
                if (isShortcutItem)
                {
                    if (string.IsNullOrEmpty(shortcutTargetPath))
                    {
                        await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance);

                        return(true);
                    }
                    else
                    {
                        associatedInstance.NavigationToolbar.PathControlDisplayText = shortcutTargetPath;
                        associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(shortcutTargetPath), new NavigationArguments()
                        {
                            NavPathParam          = shortcutTargetPath,
                            AssociatedTabInstance = associatedInstance,
                            SelectItems           = selectItems
                        });

                        return(true);
                    }
                }
                else if (isHiddenItem)
                {
                    associatedInstance.NavigationToolbar.PathControlDisplayText = path;
                    associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
                    {
                        NavPathParam          = path,
                        AssociatedTabInstance = associatedInstance
                    });

                    return(true);
                }
                else
                {
                    opened = await associatedInstance.FilesystemViewModel.GetFolderWithPathFromPathAsync(path)
                             .OnSuccess(childFolder =>
                    {
                        // Add location to MRU List
                        mostRecentlyUsed.Add(childFolder.Folder, childFolder.Path);
                    });

                    if (!opened)
                    {
                        opened = (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path);
                    }
                    if (!opened)
                    {
                        opened = (FilesystemResult)path.StartsWith("ftp:");
                    }
                    if (opened)
                    {
                        associatedInstance.NavigationToolbar.PathControlDisplayText = path;
                        associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
                        {
                            NavPathParam          = path,
                            AssociatedTabInstance = associatedInstance,
                            SelectItems           = selectItems
                        });
                    }
                }
            }
            else if (itemType == FilesystemItemType.File) // OpenFile
            {
                if (isShortcutItem)
                {
                    if (string.IsNullOrEmpty(shortcutTargetPath))
                    {
                        await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance);
                    }
                    else
                    {
                        if (!path.EndsWith(".url"))
                        {
                            StorageFileWithPath childFile = await associatedInstance.FilesystemViewModel.GetFileWithPathFromPathAsync(shortcutTargetPath);

                            if (childFile != null)
                            {
                                // Add location to MRU List
                                mostRecentlyUsed.Add(childFile.File, childFile.Path);
                            }
                        }
                        await Win32Helpers.InvokeWin32ComponentAsync(shortcutTargetPath, associatedInstance, shortcutArguments, shortcutRunAsAdmin, shortcutWorkingDirectory);
                    }
                    opened = (FilesystemResult)true;
                }
                else if (isHiddenItem)
                {
                    await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance);
                }
                else
                {
                    opened = await associatedInstance.FilesystemViewModel.GetFileWithPathFromPathAsync(path)
                             .OnSuccess(async childFile =>
                    {
                        // Add location to MRU List
                        mostRecentlyUsed.Add(childFile.File, childFile.Path);

                        if (openViaApplicationPicker)
                        {
                            LauncherOptions options = new LauncherOptions
                            {
                                DisplayApplicationPicker = true
                            };
                            await Launcher.LaunchFileAsync(childFile.File, options);
                        }
                        else
                        {
                            //try using launcher first
                            bool launchSuccess = false;

                            StorageFileQueryResult fileQueryResult = null;

                            //Get folder to create a file query (to pass to apps like Photos, Movies & TV..., needed to scroll through the folder like what Windows Explorer does)
                            StorageFolder currentFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(System.IO.Path.GetDirectoryName(path));

                            if (currentFolder != null)
                            {
                                QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, null);

                                //We can have many sort entries
                                SortEntry sortEntry = new SortEntry()
                                {
                                    AscendingOrder = associatedInstance.InstanceViewModel.FolderSettings.DirectorySortDirection == Microsoft.Toolkit.Uwp.UI.SortDirection.Ascending
                                };

                                //Basically we tell to the launched app to follow how we sorted the files in the directory.

                                var sortOption = associatedInstance.InstanceViewModel.FolderSettings.DirectorySortOption;

                                switch (sortOption)
                                {
                                case Enums.SortOption.Name:
                                    sortEntry.PropertyName = "System.ItemNameDisplay";
                                    queryOptions.SortOrder.Clear();
                                    queryOptions.SortOrder.Add(sortEntry);
                                    break;

                                case Enums.SortOption.DateModified:
                                    sortEntry.PropertyName = "System.DateModified";
                                    queryOptions.SortOrder.Clear();
                                    queryOptions.SortOrder.Add(sortEntry);
                                    break;

                                case Enums.SortOption.DateCreated:
                                    sortEntry.PropertyName = "System.DateCreated";
                                    queryOptions.SortOrder.Clear();
                                    queryOptions.SortOrder.Add(sortEntry);
                                    break;

                                //Unfortunately this is unsupported | Remarks: https://docs.microsoft.com/en-us/uwp/api/windows.storage.search.queryoptions.sortorder?view=winrt-19041
                                //case Enums.SortOption.Size:

                                //sortEntry.PropertyName = "System.TotalFileSize";
                                //queryOptions.SortOrder.Clear();
                                //queryOptions.SortOrder.Add(sortEntry);
                                //break;

                                //Unfortunately this is unsupported | Remarks: https://docs.microsoft.com/en-us/uwp/api/windows.storage.search.queryoptions.sortorder?view=winrt-19041
                                //case Enums.SortOption.FileType:

                                //sortEntry.PropertyName = "System.FileExtension";
                                //queryOptions.SortOrder.Clear();
                                //queryOptions.SortOrder.Add(sortEntry);
                                //break;

                                //Handle unsupported
                                default:
                                    //keep the default one in SortOrder IList
                                    break;
                                }

                                fileQueryResult = currentFolder.CreateFileQueryWithOptions(queryOptions);

                                var options = new LauncherOptions
                                {
                                    NeighboringFilesQuery = fileQueryResult
                                };

                                // Now launch file with options.
                                launchSuccess = await Launcher.LaunchFileAsync(childFile.File, options);
                            }

                            if (!launchSuccess)
                            {
                                await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance);
                            }
                        }
                    });
                }
            }

            if (opened.ErrorCode == FileSystemStatusCode.NotFound && !openSilent)
            {
                await DialogDisplayHelper.ShowDialogAsync("FileNotFoundDialog/Title".GetLocalized(), "FileNotFoundDialog/Text".GetLocalized());

                associatedInstance.NavigationToolbar.CanRefresh = false;
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    var ContentOwnedViewModelInstance = associatedInstance.FilesystemViewModel;
                    ContentOwnedViewModelInstance?.RefreshItems(previousDir);
                });
            }

            return(opened);
        }
        public static bool PredictLayoutMode(FolderSettingsViewModel folderSettings, ItemViewModel filesystemViewModel)
        {
            IUserSettingsService userSettingsService = Ioc.Default.GetService <IUserSettingsService>();

            if (userSettingsService.PreferencesSettingsService.AreLayoutPreferencesPerFolder && userSettingsService.PreferencesSettingsService.AdaptiveLayoutEnabled && !folderSettings.LayoutPreference.IsAdaptiveLayoutOverridden)
            {
                Action layoutDetails  = () => folderSettings.ToggleLayoutModeDetailsView.Execute(false);
                Action layoutTiles    = () => folderSettings.ToggleLayoutModeTiles.Execute(false);
                Action layoutGridView = () => folderSettings.ToggleLayoutModeGridView.Execute(folderSettings.GridViewSize);

                bool desktopIniFound = false;

                string path = filesystemViewModel?.WorkingDirectory;

                if (string.IsNullOrWhiteSpace(path))
                {
                    return(false);
                }

                var iniPath     = System.IO.Path.Combine(path, "desktop.ini");
                var iniContents = NativeFileOperationsHelper.ReadStringFromFile(iniPath)?.Trim();
                if (!string.IsNullOrEmpty(iniContents))
                {
                    var parser = new IniParser.Parser.IniDataParser();
                    parser.Configuration.ThrowExceptionsOnError = false;
                    var data = parser.Parse(iniContents);
                    if (data != null)
                    {
                        var viewModeSection = data.Sections.FirstOrDefault(x => "ViewState".Equals(x.SectionName, StringComparison.OrdinalIgnoreCase));
                        if (viewModeSection != null)
                        {
                            var folderTypeKey = viewModeSection.Keys.FirstOrDefault(s => "FolderType".Equals(s.KeyName, StringComparison.OrdinalIgnoreCase));
                            if (folderTypeKey != null)
                            {
                                switch (folderTypeKey.Value)
                                {
                                case "Documents":
                                {
                                    layoutDetails();
                                    break;
                                }

                                case "Pictures":
                                {
                                    layoutGridView();
                                    break;
                                }

                                case "Music":
                                {
                                    layoutDetails();
                                    break;
                                }

                                case "Videos":
                                {
                                    layoutGridView();
                                    break;
                                }

                                default:
                                {
                                    layoutDetails();
                                    break;
                                }
                                }

                                desktopIniFound = true;
                            }
                        }
                    }
                }

                if (desktopIniFound)
                {
                    return(true);
                }
                if (filesystemViewModel.FilesAndFolders.Count == 0)
                {
                    return(false);
                }

                int allItemsCount = filesystemViewModel.FilesAndFolders.Count;

                int mediaCount;
                int imagesCount;
                int foldersCount;
                int miscFilesCount;

                float mediaPercentage;
                float imagesPercentage;
                float foldersPercentage;
                float miscFilesPercentage;

                mediaCount = filesystemViewModel.FilesAndFolders.Where((item) =>
                {
                    return(!string.IsNullOrEmpty(item.FileExtension) && MediaPreviewViewModel.Extensions.Any((ext) => item.FileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)));
                }).Count();
                imagesCount = filesystemViewModel.FilesAndFolders.Where((item) =>
                {
                    return(!string.IsNullOrEmpty(item.FileExtension) && ImagePreviewViewModel.Extensions.Any((ext) => item.FileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)));
                }).Count();
                foldersCount   = filesystemViewModel.FilesAndFolders.Where((item) => item.PrimaryItemAttribute == StorageItemTypes.Folder).Count();
                miscFilesCount = allItemsCount - (mediaCount + imagesCount + foldersCount);

                mediaPercentage     = (float)((float)mediaCount / (float)allItemsCount) * 100.0f;
                imagesPercentage    = (float)((float)imagesCount / (float)allItemsCount) * 100.0f;
                foldersPercentage   = (float)((float)foldersCount / (float)allItemsCount) * 100.0f;
                miscFilesPercentage = (float)((float)miscFilesCount / (float)allItemsCount) * 100.0f;

                // Decide layout mode

                // Mostly files + folders, lesser media and image files | Mostly folders
                if ((foldersPercentage + miscFilesPercentage) > Constants.AdaptiveLayout.LargeThreshold)
                {
                    layoutDetails();
                }
                // Mostly images, probably an images folder
                else if (imagesPercentage > Constants.AdaptiveLayout.ExtraLargeThreshold ||
                         (imagesPercentage > Constants.AdaptiveLayout.MediumThreshold &&
                          (mediaPercentage + miscFilesPercentage + foldersPercentage) > Constants.AdaptiveLayout.SmallThreshold &&
                          (miscFilesPercentage + foldersPercentage) < Constants.AdaptiveLayout.ExtraSmallThreshold))
                {
                    layoutGridView();
                }
                // Mostly media i.e. sound files, videos
                else if (mediaPercentage > Constants.AdaptiveLayout.ExtraLargeThreshold ||
                         (mediaPercentage > Constants.AdaptiveLayout.MediumThreshold &&
                          (imagesPercentage + miscFilesPercentage + foldersPercentage) > Constants.AdaptiveLayout.SmallThreshold &&
                          (miscFilesPercentage + foldersPercentage) < Constants.AdaptiveLayout.ExtraSmallThreshold))
                {
                    layoutDetails();
                }
                else
                {
                    layoutDetails();
                }

                return(true);
            }

            return(false);
        }
Beispiel #8
0
        /// <summary>
        /// Navigates to a directory or opens file
        /// </summary>
        /// <param name="path">The path to navigate to or open</param>
        /// <param name="associatedInstance">The instance associated with view</param>
        /// <param name="itemType"></param>
        /// <param name="openSilent">Determines whether history of opened item is saved (... to Recent Items/Windows Timeline/opening in background)</param>
        /// <param name="openViaApplicationPicker">Determines whether open file using application picker</param>
        /// <param name="selectItems">List of filenames that are selected upon navigation</param>
        /// <param name="forceOpenInNewTab">Open folders in a new tab regardless of the "OpenFoldersInNewTab" option</param>
        public static async Task <bool> OpenPath(string path, IShellPage associatedInstance, FilesystemItemType?itemType = null, bool openSilent = false, bool openViaApplicationPicker = false, IEnumerable <string> selectItems = null, string args = default, bool forceOpenInNewTab = false)
        {
            string           previousDir    = associatedInstance.FilesystemViewModel.WorkingDirectory;
            bool             isHiddenItem   = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Hidden);
            bool             isDirectory    = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Directory);
            bool             isReparsePoint = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.ReparsePoint);
            bool             isShortcutItem = path.EndsWith(".lnk", StringComparison.Ordinal) || path.EndsWith(".url", StringComparison.Ordinal);
            FilesystemResult opened         = (FilesystemResult)false;

            var shortcutInfo = new ShellLinkItem();

            if (itemType == null || isShortcutItem || isHiddenItem || isReparsePoint)
            {
                if (isShortcutItem)
                {
                    var connection = await AppServiceConnectionHelper.Instance;
                    if (connection == null)
                    {
                        return(false);
                    }
                    var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
                    {
                        { "Arguments", "FileOperation" },
                        { "fileop", "ParseLink" },
                        { "filepath", path }
                    });

                    if (status == AppServiceResponseStatus.Success && response.ContainsKey("ShortcutInfo"))
                    {
                        var shInfo = JsonConvert.DeserializeObject <ShellLinkItem>((string)response["ShortcutInfo"]);
                        if (shInfo != null)
                        {
                            shortcutInfo = shInfo;
                        }
                        itemType = shInfo != null && shInfo.IsFolder ? FilesystemItemType.Directory : FilesystemItemType.File;
                    }
                    else
                    {
                        return(false);
                    }
                }
                else if (isReparsePoint)
                {
                    if (!isDirectory)
                    {
                        if (NativeFindStorageItemHelper.GetWin32FindDataForPath(path, out var findData))
                        {
                            if (findData.dwReserved0 == NativeFileOperationsHelper.IO_REPARSE_TAG_SYMLINK)
                            {
                                shortcutInfo.TargetPath = NativeFileOperationsHelper.ParseSymLink(path);
                            }
                        }
                    }
                    itemType ??= isDirectory ? FilesystemItemType.Directory : FilesystemItemType.File;
                }
                else if (isHiddenItem)
                {
                    itemType = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Directory) ? FilesystemItemType.Directory : FilesystemItemType.File;
                }
                else
                {
                    itemType = await StorageHelpers.GetTypeFromPath(path);
                }
            }

            if (itemType == FilesystemItemType.Library)
            {
                opened = await OpenLibrary(path, associatedInstance, selectItems, forceOpenInNewTab);
            }
            else if (itemType == FilesystemItemType.Directory)
            {
                opened = await OpenDirectory(path, associatedInstance, selectItems, shortcutInfo, forceOpenInNewTab);
            }
            else if (itemType == FilesystemItemType.File)
            {
                opened = await OpenFile(path, associatedInstance, selectItems, shortcutInfo, openViaApplicationPicker, args);
            }

            if (opened.ErrorCode == FileSystemStatusCode.NotFound && !openSilent)
            {
                await DialogDisplayHelper.ShowDialogAsync("FileNotFoundDialog/Title".GetLocalized(), "FileNotFoundDialog/Text".GetLocalized());

                associatedInstance.NavToolbarViewModel.CanRefresh = false;
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    var ContentOwnedViewModelInstance = associatedInstance.FilesystemViewModel;
                    ContentOwnedViewModelInstance?.RefreshItems(previousDir);
                });
            }

            return(opened);
        }
        public static async Task ExtractArchive(BaseStorageFile archive, BaseStorageFolder destinationFolder, IProgress <float> progressDelegate, CancellationToken cancellationToken)
        {
            ZipFile zipFile = await Filesystem.FilesystemTasks.Wrap(async() => new ZipFile(await archive.OpenStreamForReadAsync()));

            if (zipFile == null)
            {
                return;
            }
            using (zipFile)
            {
                zipFile.IsStreamOwner = true;
                List <ZipEntry> directoryEntries = new List <ZipEntry>();
                List <ZipEntry> fileEntries      = new List <ZipEntry>();
                foreach (ZipEntry entry in zipFile)
                {
                    if (entry.IsFile)
                    {
                        fileEntries.Add(entry);
                    }
                    else
                    {
                        directoryEntries.Add(entry);
                    }
                }

                if (cancellationToken.IsCancellationRequested) // Check if cancelled
                {
                    return;
                }

                var wnt         = new WindowsNameTransform(destinationFolder.Path);
                var zipEncoding = ZipStorageFolder.DetectFileEncoding(zipFile);

                var directories = new List <string>();
                try
                {
                    directories.AddRange(directoryEntries.Select((entry) => wnt.TransformDirectory(ZipStorageFolder.DecodeEntryName(entry, zipEncoding))));
                    directories.AddRange(fileEntries.Select((entry) => Path.GetDirectoryName(wnt.TransformFile(ZipStorageFolder.DecodeEntryName(entry, zipEncoding)))));
                }
                catch (InvalidNameException ex)
                {
                    App.Logger.Warn(ex, $"Error transforming zip names into: {destinationFolder.Path}\n" +
                                    $"Directories: {string.Join(", ", directoryEntries.Select(x => x.Name))}\n" +
                                    $"Files: {string.Join(", ", fileEntries.Select(x => x.Name))}");
                    return;
                }

                foreach (var dir in directories.Distinct().OrderBy(x => x.Length))
                {
                    if (!NativeFileOperationsHelper.CreateDirectoryFromApp(dir, IntPtr.Zero))
                    {
                        var dirName = destinationFolder.Path;
                        foreach (var component in dir.Substring(destinationFolder.Path.Length).Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries))
                        {
                            dirName = Path.Combine(dirName, component);
                            NativeFileOperationsHelper.CreateDirectoryFromApp(dirName, IntPtr.Zero);
                        }
                    }

                    if (cancellationToken.IsCancellationRequested) // Check if canceled
                    {
                        return;
                    }
                }

                if (cancellationToken.IsCancellationRequested) // Check if canceled
                {
                    return;
                }

                // Fill files

                byte[] buffer          = new byte[4096];
                int    entriesAmount   = fileEntries.Count;
                int    entriesFinished = 0;

                foreach (var entry in fileEntries)
                {
                    if (cancellationToken.IsCancellationRequested) // Check if canceled
                    {
                        return;
                    }
                    if (entry.IsCrypted)
                    {
                        App.Logger.Info($"Skipped encrypted zip entry: {entry.Name}");
                        continue; // TODO: support password protected archives
                    }

                    string filePath = wnt.TransformFile(ZipStorageFolder.DecodeEntryName(entry, zipEncoding));

                    var hFile = NativeFileOperationsHelper.CreateFileForWrite(filePath);
                    if (hFile.IsInvalid)
                    {
                        return; // TODO: handle error
                    }

                    // We don't close hFile because FileStream.Dispose() already does that
                    using (FileStream destinationStream = new FileStream(hFile, FileAccess.Write))
                    {
                        int currentBlockSize = 0;

                        using (Stream entryStream = zipFile.GetInputStream(entry))
                        {
                            while ((currentBlockSize = await entryStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                            {
                                await destinationStream.WriteAsync(buffer, 0, currentBlockSize);

                                if (cancellationToken.IsCancellationRequested) // Check if cancelled
                                {
                                    return;
                                }
                            }
                        }
                    }

                    entriesFinished++;
                    float percentage = (float)((float)entriesFinished / (float)entriesAmount) * 100.0f;
                    progressDelegate?.Report(percentage);
                }
            }
        }
Beispiel #10
0
        public static async Task ExtractArchive(StorageFile archive, StorageFolder destinationFolder, IProgress <float> progressDelegate, CancellationToken cancellationToken)
        {
            using (ZipFile zipFile = new ZipFile(await archive.OpenStreamForReadAsync()))
            {
                zipFile.IsStreamOwner = true;
                List <ZipEntry> directoryEntries = new List <ZipEntry>();
                List <ZipEntry> fileEntries      = new List <ZipEntry>();
                foreach (ZipEntry entry in zipFile)
                {
                    if (entry.IsFile)
                    {
                        fileEntries.Add(entry);
                    }
                    else
                    {
                        directoryEntries.Add(entry);
                    }
                }

                if (cancellationToken.IsCancellationRequested) // Check if cancelled
                {
                    return;
                }

                var wnt = new WindowsNameTransform(destinationFolder.Path);

                var directories = new List <string>();
                directories.AddRange(directoryEntries.Select((item) => wnt.TransformDirectory(item.Name)));
                directories.AddRange(fileEntries.Select((item) => Path.GetDirectoryName(wnt.TransformFile(item.Name))));
                foreach (var dir in directories.Distinct().OrderBy(x => x.Length))
                {
                    if (!NativeFileOperationsHelper.CreateDirectoryFromApp(dir, IntPtr.Zero))
                    {
                        var dirName = destinationFolder.Path;
                        foreach (var component in dir.Substring(destinationFolder.Path.Length).Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries))
                        {
                            dirName = Path.Combine(dirName, component);
                            NativeFileOperationsHelper.CreateDirectoryFromApp(dirName, IntPtr.Zero);
                        }
                    }
                }

                if (cancellationToken.IsCancellationRequested) // Check if cancelled
                {
                    return;
                }

                // Fill files

                byte[] buffer          = new byte[4096];
                int    entriesAmount   = fileEntries.Count;
                int    entriesFinished = 0;

                foreach (var entry in fileEntries)
                {
                    if (cancellationToken.IsCancellationRequested) // Check if cancelled
                    {
                        return;
                    }

                    string filePath = wnt.TransformFile(entry.Name);

                    var hFile = NativeFileOperationsHelper.CreateFileForWrite(filePath);
                    if (hFile.IsInvalid)
                    {
                        return; // TODO: handle error
                    }

                    using (FileStream destinationStream = new FileStream(hFile, FileAccess.ReadWrite))
                    {
                        int currentBlockSize = 0;

                        using (Stream entryStream = zipFile.GetInputStream(entry))
                        {
                            while ((currentBlockSize = await entryStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                            {
                                await destinationStream.WriteAsync(buffer, 0, buffer.Length);

                                if (cancellationToken.IsCancellationRequested) // Check if cancelled
                                {
                                    return;
                                }
                            }
                        }
                    }
                    // We don't close handleContext because FileStream.Dispose() already does that

                    entriesFinished++;
                    float percentage = (float)((float)entriesFinished / (float)entriesAmount) * 100.0f;
                    progressDelegate?.Report(percentage);
                }
            }
        }
Beispiel #11
0
        public static bool PredictLayoutMode(FolderSettingsViewModel folderSettings, ItemViewModel filesystemViewModel)
        {
            if (App.AppSettings.AreLayoutPreferencesPerFolder && App.AppSettings.AdaptiveLayoutEnabled && !folderSettings.LayoutPreference.IsAdaptiveLayoutOverridden)
            {
                bool desktopIniFound = false;

                string path = filesystemViewModel?.WorkingDirectory;

                if (string.IsNullOrWhiteSpace(path))
                {
                    return(false);
                }

                var iniPath     = System.IO.Path.Combine(path, "desktop.ini");
                var iniContents = NativeFileOperationsHelper.ReadStringFromFile(iniPath)?.Trim();
                if (!string.IsNullOrEmpty(iniContents))
                {
                    var parser = new IniParser.Parser.IniDataParser();
                    parser.Configuration.ThrowExceptionsOnError = false;
                    var data = parser.Parse(iniContents);
                    if (data != null)
                    {
                        var viewModeSection = data.Sections.FirstOrDefault(x => "ViewState".Equals(x.SectionName, StringComparison.OrdinalIgnoreCase));
                        if (viewModeSection != null)
                        {
                            var folderTypeKey = viewModeSection.Keys.FirstOrDefault(s => "FolderType".Equals(s.KeyName, StringComparison.OrdinalIgnoreCase));
                            if (folderTypeKey != null)
                            {
                                switch (folderTypeKey.Value)
                                {
                                case "Documents":
                                {
                                    folderSettings.ToggleLayoutModeTiles.Execute(false);
                                    break;
                                }

                                case "Pictures":
                                {
                                    folderSettings.ToggleLayoutModeGridView.Execute(folderSettings.GridViewSize);
                                    break;
                                }

                                case "Music":
                                {
                                    folderSettings.ToggleLayoutModeDetailsView.Execute(false);
                                    break;
                                }

                                case "Videos":
                                {
                                    folderSettings.ToggleLayoutModeGridView.Execute(folderSettings.GridViewSize);
                                    break;
                                }

                                default:
                                {
                                    folderSettings.ToggleLayoutModeDetailsView.Execute(false);
                                    break;
                                }
                                }

                                desktopIniFound = true;
                            }
                        }
                    }
                }

                if (desktopIniFound)
                {
                    return(true);
                }
                if (filesystemViewModel.FilesAndFolders.Count == 0)
                {
                    return(false);
                }

                int imagesAndVideosCount = filesystemViewModel.FilesAndFolders.Where((item) =>

                                                                                     !string.IsNullOrEmpty(item.FileExtension)

                                                                                     // Images
                                                                                     && (ImagePreviewViewModel.Extensions.Any((ext) => item.FileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase))

                                                                                         // Audio & Video
                                                                                         || MediaPreviewViewModel.Extensions.Any((ext) => item.FileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase))
                                                                                         )).Count();

                int foldersCount = filesystemViewModel.FilesAndFolders.Where((item) => item.PrimaryItemAttribute == StorageItemTypes.Folder).Count();

                int otherFilesCount = filesystemViewModel.FilesAndFolders.Count - (imagesAndVideosCount + foldersCount);

                if (foldersCount > 0)
                {     // There are folders in current directory
                    if ((filesystemViewModel.FilesAndFolders.Count - imagesAndVideosCount) < (filesystemViewModel.FilesAndFolders.Count - 20) || (filesystemViewModel.FilesAndFolders.Count <= 20 && imagesAndVideosCount >= 5))
                    { // Most of items are images/videos
                        folderSettings.ToggleLayoutModeTiles.Execute(false);
                    }
                    else
                    {
                        folderSettings.ToggleLayoutModeDetailsView.Execute(false);
                    }
                }
                else
                {     // There are only files
                    if (imagesAndVideosCount == filesystemViewModel.FilesAndFolders.Count)
                    { // Only images/videos
                        folderSettings.ToggleLayoutModeGridView.Execute(folderSettings.GridViewSize);
                    }
                    else if (otherFilesCount < 20)
                    { // Most of files are images/videos
                        folderSettings.ToggleLayoutModeTiles.Execute(false);
                    }
                    else
                    { // Images/videos and other files
                        folderSettings.ToggleLayoutModeDetailsView.Execute(false);
                    }
                }

                return(true);
            }

            return(false);
        }