示例#1
0
        public static async Task <IStorageItem> CreateFileFromDialogResultTypeForResult(AddItemDialogItemType itemType, ShellNewEntry itemInfo, IShellPage associatedInstance)
        {
            string currentPath = null;

            if (associatedInstance.SlimContentPage != null)
            {
                currentPath = associatedInstance.FilesystemViewModel.WorkingDirectory;
                if (App.LibraryManager.TryGetLibrary(currentPath, out var library))
                {
                    if (!library.IsEmpty && library.Folders.Count == 1) // TODO: handle libraries with multiple folders
                    {
                        currentPath = library.Folders.First();
                    }
                }
            }

            // Skip rename dialog when ShellNewEntry has a Command (e.g. ".accdb", ".gdoc")
            string userInput = null;

            if (itemType != AddItemDialogItemType.File || itemInfo?.Command == null)
            {
                DynamicDialog dialog = DynamicDialogFactory.GetFor_RenameDialog();
                await dialog.ShowAsync(); // Show rename dialog

                if (dialog.DynamicResult != DynamicDialogResult.Primary)
                {
                    return(null);
                }

                userInput = dialog.ViewModel.AdditionalData as string;
            }

            // Create file based on dialog result
            (ReturnResult Status, IStorageItem Item)created = (ReturnResult.Failed, null);
            switch (itemType)
            {
            case AddItemDialogItemType.Folder:
                userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : "NewFolder".GetLocalized();
                created   = await associatedInstance.FilesystemHelpers.CreateAsync(
                    StorageHelpers.FromPathAndType(PathNormalization.Combine(currentPath, userInput), FilesystemItemType.Directory),
                    true);

                break;

            case AddItemDialogItemType.File:
                userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : itemInfo?.Name ?? "NewFile".GetLocalized();
                created   = await associatedInstance.FilesystemHelpers.CreateAsync(
                    StorageHelpers.FromPathAndType(PathNormalization.Combine(currentPath, userInput + itemInfo?.Extension), FilesystemItemType.File),
                    true);

                break;
            }

            if (created.Status == ReturnResult.AccessUnauthorized)
            {
                await DialogDisplayHelper.ShowDialogAsync("AccessDenied".GetLocalized(), "AccessDeniedCreateDialog/Text".GetLocalized());
            }

            return(created.Item);
        }
示例#2
0
        public static async Task <byte[]> LoadIconFromPathAsync(string filePath, uint thumbnailSize, ThumbnailMode thumbnailMode)
        {
            if (!filePath.EndsWith(".lnk", StringComparison.Ordinal) && !filePath.EndsWith(".url", StringComparison.Ordinal))
            {
                var item = await StorageHelpers.ToStorageItem <IStorageItem>(filePath);

                if (item != null)
                {
                    var iconData = await LoadIconFromStorageItemAsync(item, thumbnailSize, thumbnailMode);

                    if (iconData != null)
                    {
                        return(iconData);
                    }
                }
            }
            return(await LoadIconWithoutOverlayAsync(filePath, thumbnailSize));
        }
示例#3
0
        public static async void SetAsBackground(WallpaperType type, string filePath)
        {
            if (UserProfilePersonalizationSettings.IsSupported())
            {
                // Get the path of the selected file
                BaseStorageFile sourceFile = await StorageHelpers.ToStorageItem <BaseStorageFile>(filePath);

                if (sourceFile == null)
                {
                    return;
                }

                // Get the app's local folder to use as the destination folder.
                BaseStorageFolder localFolder = ApplicationData.Current.LocalFolder;

                // the file to the destination folder.
                // Generate unique name if the file already exists.
                // If the file you are trying to set as the wallpaper has the same name as the current wallpaper,
                // the system will ignore the request and no-op the operation
                BaseStorageFile file = await FilesystemTasks.Wrap(() => sourceFile.CopyAsync(localFolder, sourceFile.Name, NameCollisionOption.GenerateUniqueName).AsTask());

                if (file == null)
                {
                    return;
                }

                UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current;
                if (type == WallpaperType.Desktop)
                {
                    // Set the desktop background
                    await profileSettings.TrySetWallpaperImageAsync(await file.ToStorageFileAsync());
                }
                else if (type == WallpaperType.LockScreen)
                {
                    // Set the lockscreen background
                    await profileSettings.TrySetLockScreenImageAsync(await file.ToStorageFileAsync());
                }
            }
        }
示例#4
0
        public static async Task <bool> RenameFileItemAsync(ListedItem item, string newName, IShellPage associatedInstance)
        {
            if (item is AlternateStreamItem ads) // For alternate streams ItemName is not a substring ItemNameRaw
            {
                newName = item.ItemNameRaw.Replace(
                    item.ItemName.Substring(item.ItemName.LastIndexOf(":") + 1),
                    newName.Substring(newName.LastIndexOf(":") + 1),
                    StringComparison.Ordinal);
                newName = $"{ads.MainStreamName}:{newName}";
            }
            else
            {
                newName = item.ItemNameRaw.Replace(item.ItemName, newName, StringComparison.Ordinal);
            }
            if (item.ItemNameRaw == newName || string.IsNullOrEmpty(newName))
            {
                return(true);
            }

            ReturnResult renamed = ReturnResult.InProgress;

            if (item.PrimaryItemAttribute == StorageItemTypes.Folder)
            {
                renamed = await associatedInstance.FilesystemHelpers.RenameAsync(StorageHelpers.FromPathAndType(item.ItemPath, FilesystemItemType.Directory),
                                                                                 newName, NameCollisionOption.FailIfExists, true);
            }
            else
            {
                renamed = await associatedInstance.FilesystemHelpers.RenameAsync(StorageHelpers.FromPathAndType(item.ItemPath, FilesystemItemType.File),
                                                                                 newName, NameCollisionOption.FailIfExists, true);
            }

            if (renamed == ReturnResult.Success)
            {
                associatedInstance.ToolbarViewModel.CanGoForward = false;
                return(true);
            }
            return(false);
        }
示例#5
0
        /// <summary>
        /// Rotates the image at the specified file path.
        /// </summary>
        /// <param name="filePath">The file path to the image.</param>
        /// <param name="rotation">The rotation direction.</param>
        /// <remarks>
        /// https://docs.microsoft.com/en-us/uwp/api/windows.graphics.imaging.bitmapdecoder?view=winrt-22000
        /// https://docs.microsoft.com/en-us/uwp/api/windows.graphics.imaging.bitmapencoder?view=winrt-22000
        /// </remarks>
        public static async Task Rotate(string filePath, BitmapRotation rotation)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return;
            }

            var file = await StorageHelpers.ToStorageItem <IStorageFile>(filePath);

            if (file == null)
            {
                return;
            }

            var fileStreamRes = await FilesystemTasks.Wrap(() => file.OpenAsync(FileAccessMode.ReadWrite).AsTask());

            using IRandomAccessStream fileStream = fileStreamRes.Result;
            if (fileStream == null)
            {
                return;
            }

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

            using var memStream = new InMemoryRandomAccessStream();
            BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder);

            encoder.BitmapTransform.Rotation = rotation;

            await encoder.FlushAsync();

            memStream.Seek(0);
            fileStream.Seek(0);
            fileStream.Size = 0;

            await RandomAccessStream.CopyAsync(memStream, fileStream);
        }
示例#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>
        /// <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.ToolbarViewModel.CanRefresh = false;
                associatedInstance.FilesystemViewModel?.RefreshItems(previousDir);
            }

            return(opened);
        }
示例#7
0
        public static async Task CreateFolderWithSelectionAsync(IShellPage associatedInstance)
        {
            try
            {
                var items = associatedInstance.SlimContentPage.SelectedItems.ToList().Select((item) => StorageHelpers.FromPathAndType(
                                                                                                 item.ItemPath,
                                                                                                 item.PrimaryItemAttribute == StorageItemTypes.File ? FilesystemItemType.File : FilesystemItemType.Directory));
                var folder = await CreateFileFromDialogResultTypeForResult(AddItemDialogItemType.Folder, null, associatedInstance);

                if (folder == null)
                {
                    return;
                }
                await associatedInstance.FilesystemHelpers.MoveItemsAsync(items, items.Select(x => PathNormalization.Combine(folder.Path, x.Name)), false, true);
            }
            catch (Exception ex)
            {
                App.Logger.Warn(ex);
            }
        }