/// <summary>
        /// Adds the item do the navigation sidebar
        /// </summary>
        /// <param name="path">The path which to save</param>
        /// <returns>Task</returns>
        public async Task AddItemToSidebarAsync(string path)
        {
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path, item));

            if (res || (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path))
            {
                var lastItem    = favoriteSection.ChildItems.LastOrDefault(x => x.ItemType == NavigationControlItemType.Location && !x.Path.Equals(App.AppSettings.RecycleBinPath));
                int insertIndex = lastItem != null?favoriteSection.ChildItems.IndexOf(lastItem) + 1 : 0;

                var locationItem = new LocationItem
                {
                    Font              = InteractionViewModel.FontName,
                    Path              = path,
                    Section           = SectionType.Favorites,
                    Icon              = GlyphHelper.GetIconUri(path),
                    IsDefaultLocation = false,
                    Text              = res.Result?.DisplayName ?? Path.GetFileName(path.TrimEnd('\\'))
                };

                if (!favoriteSection.ChildItems.Contains(locationItem))
                {
                    favoriteSection.ChildItems.Insert(insertIndex, locationItem);
                }
            }
            else
            {
                Debug.WriteLine($"Pinned item was invalid and will be removed from the file lines list soon: {res.ErrorCode}");
                RemoveItem(path);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Adds the item do the navigation sidebar
        /// </summary>
        /// <param name="path">The path which to save</param>
        /// <returns>Task</returns>
        public async Task AddItemToSidebarAsync(string path)
        {
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path, item));

            if (res || (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path))
            {
                int insertIndex = MainPage.SideBarItems.IndexOf(MainPage.SideBarItems.Last(x => x.ItemType == NavigationControlItemType.Location &&
                                                                                           !x.Path.Equals(App.AppSettings.RecycleBinPath))) + 1;
                var locationItem = new LocationItem
                {
                    Font              = App.Current.Resources["FluentUIGlyphs"] as FontFamily,
                    Path              = path,
                    Glyph             = GetItemIcon(path),
                    IsDefaultLocation = false,
                    Text              = res.Result?.DisplayName ?? Path.GetFileName(path.TrimEnd('\\'))
                };

                if (!MainPage.SideBarItems.Contains(locationItem))
                {
                    MainPage.SideBarItems.Insert(insertIndex, locationItem);
                }
            }
            else
            {
                Debug.WriteLine($"Pinned item was invalid and will be removed from the file lines list soon: {res.ErrorCode}");
                RemoveItem(path);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Adds the item (from a path) to the navigation sidebar
        /// </summary>
        /// <param name="path">The path which to save</param>
        /// <returns>Task</returns>
        public async Task AddItemToSidebarAsync(string path)
        {
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path, item));

            var locationItem = new LocationItem
            {
                Font        = MainViewModel.FontName,
                Path        = path,
                Section     = SectionType.Favorites,
                MenuOptions = new ContextMenuOptions
                {
                    IsLocationItem      = true,
                    ShowProperties      = true,
                    ShowUnpinItem       = true,
                    ShowShellItems      = true,
                    ShowEmptyRecycleBin = path == CommonPaths.RecycleBinPath,
                },
                IsDefaultLocation = false,
                Text = res.Result?.DisplayName ?? Path.GetFileName(path.TrimEnd('\\'))
            };

            if (res || (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path))
            {
                locationItem.IsInvalid = false;
                if (res)
                {
                    var iconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(res.Result, 24u, Windows.Storage.FileProperties.ThumbnailMode.ListView);

                    if (iconData == null)
                    {
                        iconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(res.Result, 24u, Windows.Storage.FileProperties.ThumbnailMode.SingleItem);
                    }
                    locationItem.IconData = iconData;
                    locationItem.Icon     = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => locationItem.IconData.ToBitmapAsync());
                }
                if (locationItem.IconData == null)
                {
                    locationItem.IconData = await FileThumbnailHelper.LoadIconWithoutOverlayAsync(path, 24u);

                    if (locationItem.IconData != null)
                    {
                        locationItem.Icon = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => locationItem.IconData.ToBitmapAsync());
                    }
                }
            }
            else
            {
                locationItem.Icon = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => UIHelpers.GetIconResource(Constants.ImageRes.Folder));

                locationItem.IsInvalid = true;
                Debug.WriteLine($"Pinned item was invalid {res.ErrorCode}, item: {path}");
            }

            AddLocationItemToSidebar(locationItem);
        }
Esempio n. 4
0
    private void OnOpenScreenshotFolder()
    {
        GUICommon.Instance.PlayButtonPressSound();

        if (!FolderHelpers.OpenFolder(Constants.SCREENSHOT_FOLDER))
        {
            screenshotDirectoryWarningBox.PopupCenteredShrink();
        }
    }
Esempio n. 5
0
        /// <summary>
        /// Adds the item do the navigation sidebar
        /// </summary>
        /// <param name="path">The path which to save</param>
        /// <returns>Task</returns>
        public async Task AddItemToSidebarAsync(string path)
        {
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path, item));

            var lastItem    = favoriteSection.ChildItems.LastOrDefault(x => x.ItemType == NavigationControlItemType.Location && !x.Path.Equals(CommonPaths.RecycleBinPath));
            int insertIndex = lastItem != null?favoriteSection.ChildItems.IndexOf(lastItem) + 1 : 0;

            var locationItem = new LocationItem
            {
                Font              = MainViewModel.FontName,
                Path              = path,
                Section           = SectionType.Favorites,
                IsDefaultLocation = false,
                Text              = res.Result?.DisplayName ?? Path.GetFileName(path.TrimEnd('\\'))
            };

            if (res || (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path))
            {
                locationItem.IsInvalid = false;
                if (res)
                {
                    var iconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(res.Result, 24u, Windows.Storage.FileProperties.ThumbnailMode.ListView);

                    if (iconData == null)
                    {
                        iconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(res.Result, 24u, Windows.Storage.FileProperties.ThumbnailMode.SingleItem);
                    }
                    locationItem.IconData = iconData;
                    locationItem.Icon     = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => locationItem.IconData.ToBitmapAsync());
                }
                if (locationItem.IconData == null)
                {
                    locationItem.IconData = await FileThumbnailHelper.LoadIconWithoutOverlayAsync(path, 24u);

                    if (locationItem.IconData != null)
                    {
                        locationItem.Icon = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => locationItem.IconData.ToBitmapAsync());
                    }
                }
            }
            else
            {
                locationItem.Icon = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => UIHelpers.GetIconResource(Constants.ImageRes.Folder));

                locationItem.IsInvalid = true;
                Debug.WriteLine($"Pinned item was invalid {res.ErrorCode}, item: {path}");
            }

            if (!favoriteSection.ChildItems.Any(x => x.Path == locationItem.Path))
            {
                await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => favoriteSection.ChildItems.Insert(insertIndex, locationItem));
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Adds the item do the navigation sidebar
        /// </summary>
        /// <param name="path">The path which to save</param>
        /// <returns>Task</returns>
        public async Task AddItemToSidebarAsync(string path)
        {
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path, item));

            if (res || (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path))
            {
                var lastItem    = favoriteSection.ChildItems.LastOrDefault(x => x.ItemType == NavigationControlItemType.Location && !x.Path.Equals(App.AppSettings.RecycleBinPath));
                int insertIndex = lastItem != null?favoriteSection.ChildItems.IndexOf(lastItem) + 1 : 0;

                var locationItem = new LocationItem
                {
                    Font              = MainViewModel.FontName,
                    Path              = path,
                    Section           = SectionType.Favorites,
                    IsDefaultLocation = false,
                    Text              = res.Result?.DisplayName ?? Path.GetFileName(path.TrimEnd('\\'))
                };

                if (res)
                {
                    var thumbnail = await res.Result.GetThumbnailAsync(
                        Windows.Storage.FileProperties.ThumbnailMode.ListView,
                        24,
                        Windows.Storage.FileProperties.ThumbnailOptions.ResizeThumbnail);

                    if (thumbnail != null)
                    {
                        locationItem.IconData = await thumbnail.ToByteArrayAsync();

                        locationItem.Icon = await locationItem.IconData.ToBitmapAsync();
                    }
                }

                if (!favoriteSection.ChildItems.Contains(locationItem))
                {
                    favoriteSection.ChildItems.Insert(insertIndex, locationItem);
                }
            }
            else
            {
                Debug.WriteLine($"Pinned item was invalid and will be removed from the file lines list soon: {res.ErrorCode}");
                RemoveItem(path);
            }
        }
Esempio n. 7
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);
        }
Esempio n. 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>
        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);
        }
Esempio n. 9
0
        public static async Task <ListedItem> GetFile(
            WIN32_FIND_DATA findData,
            string pathRoot,
            string dateReturnFormat,
            AppServiceConnection connection,
            CancellationToken cancellationToken
            )
        {
            var itemPath = Path.Combine(pathRoot, findData.cFileName);

            string itemName;

            if (App.AppSettings.ShowFileExtensions && !findData.cFileName.EndsWith(".lnk") && !findData.cFileName.EndsWith(".url"))
            {
                itemName = findData.cFileName; // never show extension for shortcuts
            }
            else
            {
                if (findData.cFileName.StartsWith("."))
                {
                    itemName = findData.cFileName; // Always show full name for dotfiles.
                }
                else
                {
                    itemName = Path.GetFileNameWithoutExtension(itemPath);
                }
            }

            DateTime itemModifiedDate, itemCreatedDate, itemLastAccessDate;

            try
            {
                FileTimeToSystemTime(ref findData.ftLastWriteTime, out SYSTEMTIME systemModifiedDateOutput);
                itemModifiedDate = new DateTime(
                    systemModifiedDateOutput.Year, systemModifiedDateOutput.Month, systemModifiedDateOutput.Day,
                    systemModifiedDateOutput.Hour, systemModifiedDateOutput.Minute, systemModifiedDateOutput.Second, systemModifiedDateOutput.Milliseconds,
                    DateTimeKind.Utc);

                FileTimeToSystemTime(ref findData.ftCreationTime, out SYSTEMTIME systemCreatedDateOutput);
                itemCreatedDate = new DateTime(
                    systemCreatedDateOutput.Year, systemCreatedDateOutput.Month, systemCreatedDateOutput.Day,
                    systemCreatedDateOutput.Hour, systemCreatedDateOutput.Minute, systemCreatedDateOutput.Second, systemCreatedDateOutput.Milliseconds,
                    DateTimeKind.Utc);

                FileTimeToSystemTime(ref findData.ftLastAccessTime, out SYSTEMTIME systemLastAccessOutput);
                itemLastAccessDate = new DateTime(
                    systemLastAccessOutput.Year, systemLastAccessOutput.Month, systemLastAccessOutput.Day,
                    systemLastAccessOutput.Hour, systemLastAccessOutput.Minute, systemLastAccessOutput.Second, systemLastAccessOutput.Milliseconds,
                    DateTimeKind.Utc);
            }
            catch (ArgumentException)
            {
                // Invalid date means invalid findData, do not add to list
                return(null);
            }

            long   itemSizeBytes     = findData.GetSize();
            var    itemSize          = ByteSize.FromBytes(itemSizeBytes).ToBinaryString().ConvertSizeAbbreviation();
            string itemType          = "ItemTypeFile".GetLocalized();
            string itemFileExtension = null;

            if (findData.cFileName.Contains('.'))
            {
                itemFileExtension = Path.GetExtension(itemPath);
                itemType          = itemFileExtension.Trim('.') + " " + itemType;
            }

            bool itemFolderImgVis = false;
            bool itemThumbnailImgVis;
            bool itemEmptyImgVis;

            itemEmptyImgVis     = true;
            itemThumbnailImgVis = false;

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            if (findData.cFileName.EndsWith(".lnk") || findData.cFileName.EndsWith(".url"))
            {
                if (connection != null)
                {
                    var response = await connection.SendMessageAsync(new ValueSet()
                    {
                        { "Arguments", "FileOperation" },
                        { "fileop", "ParseLink" },
                        { "filepath", itemPath }
                    });

                    // If the request was canceled return now
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(null);
                    }
                    if (response.Status == AppServiceResponseStatus.Success &&
                        response.Message.ContainsKey("TargetPath"))
                    {
                        var    isUrl  = findData.cFileName.EndsWith(".url");
                        string target = (string)response.Message["TargetPath"];
                        bool   containsFilesOrFolders = false;

                        if ((bool)response.Message["IsFolder"])
                        {
                            containsFilesOrFolders = FolderHelpers.CheckForFilesFolders(target);
                        }

                        bool   isHidden = (((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden);
                        double opacity  = 1;

                        if (isHidden)
                        {
                            opacity = 0.4;
                        }

                        return(new ShortcutItem(null, dateReturnFormat)
                        {
                            PrimaryItemAttribute = (bool)response.Message["IsFolder"] ? StorageItemTypes.Folder : StorageItemTypes.File,
                            FileExtension = itemFileExtension,
                            IsHiddenItem = isHidden,
                            Opacity = opacity,
                            FileImage = null,
                            LoadFileIcon = !(bool)response.Message["IsFolder"] && itemThumbnailImgVis,
                            LoadUnknownTypeGlyph = !(bool)response.Message["IsFolder"] && !isUrl && itemEmptyImgVis,
                            LoadFolderGlyph = (bool)response.Message["IsFolder"],
                            ItemName = itemName,
                            ItemDateModifiedReal = itemModifiedDate,
                            ItemDateAccessedReal = itemLastAccessDate,
                            ItemDateCreatedReal = itemCreatedDate,
                            ItemType = isUrl ? "ShortcutWebLinkFileType".GetLocalized() : "ShortcutFileType".GetLocalized(),
                            ItemPath = itemPath,
                            FileSize = itemSize,
                            FileSizeBytes = itemSizeBytes,
                            TargetPath = target,
                            Arguments = (string)response.Message["Arguments"],
                            WorkingDirectory = (string)response.Message["WorkingDirectory"],
                            RunAsAdmin = (bool)response.Message["RunAsAdmin"],
                            IsUrl = isUrl,
                            ContainsFilesOrFolders = containsFilesOrFolders
                        });
                    }
                }
            }
            else
            {
                bool   isHidden = (((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden);
                double opacity  = 1;

                if (isHidden)
                {
                    opacity = 0.4;
                }

                return(new ListedItem(null, dateReturnFormat)
                {
                    PrimaryItemAttribute = StorageItemTypes.File,
                    FileExtension = itemFileExtension,
                    LoadUnknownTypeGlyph = itemEmptyImgVis,
                    FileImage = null,
                    LoadFileIcon = itemThumbnailImgVis,
                    LoadFolderGlyph = itemFolderImgVis,
                    ItemName = itemName,
                    IsHiddenItem = isHidden,
                    Opacity = opacity,
                    ItemDateModifiedReal = itemModifiedDate,
                    ItemDateAccessedReal = itemLastAccessDate,
                    ItemDateCreatedReal = itemCreatedDate,
                    ItemType = itemType,
                    ItemPath = itemPath,
                    FileSize = itemSize,
                    FileSizeBytes = itemSizeBytes
                });
            }
            return(null);
        }
Esempio n. 10
0
        public static async Task <ListedItem> GetFolder(
            WIN32_FIND_DATA findData,
            string pathRoot,
            string dateReturnFormat,
            CancellationToken cancellationToken
            )
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            DateTime itemModifiedDate;
            DateTime itemCreatedDate;

            try
            {
                FileTimeToSystemTime(ref findData.ftLastWriteTime, out SYSTEMTIME systemModifiedTimeOutput);
                itemModifiedDate = new DateTime(
                    systemModifiedTimeOutput.Year, systemModifiedTimeOutput.Month, systemModifiedTimeOutput.Day,
                    systemModifiedTimeOutput.Hour, systemModifiedTimeOutput.Minute, systemModifiedTimeOutput.Second, systemModifiedTimeOutput.Milliseconds,
                    DateTimeKind.Utc);

                FileTimeToSystemTime(ref findData.ftCreationTime, out SYSTEMTIME systemCreatedTimeOutput);
                itemCreatedDate = new DateTime(
                    systemCreatedTimeOutput.Year, systemCreatedTimeOutput.Month, systemCreatedTimeOutput.Day,
                    systemCreatedTimeOutput.Hour, systemCreatedTimeOutput.Minute, systemCreatedTimeOutput.Second, systemCreatedTimeOutput.Milliseconds,
                    DateTimeKind.Utc);
            }
            catch (ArgumentException)
            {
                // Invalid date means invalid findData, do not add to list
                return(null);
            }
            var    itemPath = Path.Combine(pathRoot, findData.cFileName);
            string itemName = await fileListCache.ReadFileDisplayNameFromCache(itemPath, cancellationToken);

            if (string.IsNullOrEmpty(itemName))
            {
                itemName = findData.cFileName;
            }
            bool   isHidden = (((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden);
            double opacity  = 1;

            if (isHidden)
            {
                opacity = 0.4;
            }

            return(new ListedItem(null, dateReturnFormat)
            {
                PrimaryItemAttribute = StorageItemTypes.Folder,
                ItemName = itemName,
                ItemDateModifiedReal = itemModifiedDate,
                ItemDateCreatedReal = itemCreatedDate,
                ItemType = "FileFolderListItem".GetLocalized(),
                LoadFolderGlyph = true,
                FileImage = null,
                IsHiddenItem = isHidden,
                Opacity = opacity,
                LoadFileIcon = false,
                ItemPath = itemPath,
                LoadUnknownTypeGlyph = false,
                FileSize = null,
                FileSizeBytes = 0,
                ContainsFilesOrFolders = FolderHelpers.CheckForFilesFolders(itemPath),
                //FolderTooltipText = tooltipString,
            });
        }
Esempio n. 11
0
        public static async Task <List <ListedItem> > ListEntries(
            string path,
            string returnformat,
            IntPtr hFile,
            WIN32_FIND_DATA findData,
            NamedPipeAsAppServiceConnection connection,
            CancellationToken cancellationToken,
            int countLimit,
            Func <List <ListedItem>, Task> intermediateAction,
            Dictionary <string, BitmapImage> defaultIconPairs = null
            )
        {
            var sampler     = new IntervalSampler(500);
            var tempList    = new List <ListedItem>();
            var hasNextFile = false;
            var count       = 0;

            IUserSettingsService userSettingsService = Ioc.Default.GetService <IUserSettingsService>();
            bool showFolderSize = userSettingsService.PreferencesSettingsService.ShowFolderSize;

            do
            {
                var isSystem = ((FileAttributes)findData.dwFileAttributes & FileAttributes.System) == FileAttributes.System;
                var isHidden = ((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden;
                if (!isHidden || (userSettingsService.PreferencesSettingsService.AreHiddenItemsVisible && (!isSystem || !userSettingsService.PreferencesSettingsService.AreSystemItemsHidden)))
                {
                    if (((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) != FileAttributes.Directory)
                    {
                        var file = await GetFile(findData, path, returnformat, connection, cancellationToken);

                        if (file != null)
                        {
                            if (defaultIconPairs != null)
                            {
                                if (!string.IsNullOrEmpty(file.FileExtension))
                                {
                                    var lowercaseExtension = file.FileExtension.ToLowerInvariant();
                                    if (defaultIconPairs.ContainsKey(lowercaseExtension))
                                    {
                                        file.SetDefaultIcon(defaultIconPairs[lowercaseExtension]);
                                    }
                                }
                            }
                            tempList.Add(file);
                            ++count;
                        }
                    }
                    else if (((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory)
                    {
                        if (findData.cFileName != "." && findData.cFileName != "..")
                        {
                            var folder = await GetFolder(findData, path, returnformat, cancellationToken);

                            if (folder != null)
                            {
                                if (defaultIconPairs?.ContainsKey(string.Empty) ?? false)
                                {
                                    // Set folder icon (found by empty extension string)
                                    folder.SetDefaultIcon(defaultIconPairs[string.Empty]);
                                }
                                tempList.Add(folder);
                                ++count;

                                if (showFolderSize)
                                {
                                    FolderHelpers.UpdateFolder(folder, cancellationToken);
                                }
                            }
                        }
                    }
                }
                if (cancellationToken.IsCancellationRequested || count == countLimit)
                {
                    break;
                }

                hasNextFile = FindNextFile(hFile, out findData);
                if (intermediateAction != null && (count == 32 || sampler.CheckNow()))
                {
                    await intermediateAction(tempList);

                    // clear the temporary list every time we do an intermediate action
                    tempList.Clear();
                }
            } while (hasNextFile);

            FindClose(hFile);
            return(tempList);
        }
Esempio n. 12
0
 private void OnLogButtonPressed()
 {
     GUICommon.Instance.PlayButtonPressSound();
     FolderHelpers.OpenFolder(Constants.LOGS_FOLDER);
 }