Exemplo n.º 1
0
        public static async Task <FilesystemResult <BaseStorageFile> > Create(this ShellNewEntry shellEntry, BaseStorageFolder parentFolder, string filePath)
        {
            FilesystemResult <BaseStorageFile> createdFile = null;
            var fileName = Path.GetFileName(filePath);

            if (!fileName.EndsWith(shellEntry.Extension, StringComparison.Ordinal))
            {
                fileName += shellEntry.Extension;
            }
            if (shellEntry.Command != null)
            {
                var args = CommandLine.CommandLineParser.SplitArguments(shellEntry.Command);
                if (args.Any())
                {
                    var connection = await AppServiceConnectionHelper.Instance;
                    if (connection != null)
                    {
                        _ = await connection.SendMessageForResponseAsync(new ValueSet()
                        {
                            { "Arguments", "LaunchApp" },
                            { "WorkingDirectory", PathNormalization.GetParentDir(filePath) },
                            { "Application", args[0].Replace("\"", "", StringComparison.Ordinal) },
                            { "Parameters", string.Join(" ", args.Skip(1)).Replace("%1", filePath) }
                        });
                    }
                }
                createdFile = new FilesystemResult <BaseStorageFile>(null, Shared.Enums.FileSystemStatusCode.Success);
            }
            else if (shellEntry.Template == null)
            {
                createdFile = await FilesystemTasks.Wrap(() => parentFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName).AsTask());
            }
            else
            {
                createdFile = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(shellEntry.Template))
                              .OnSuccess(t => t.CopyAsync(parentFolder, fileName, NameCollisionOption.GenerateUniqueName).AsTask());
            }
            if (createdFile)
            {
                if (shellEntry.Data != null)
                {
                    //await FileIO.WriteBytesAsync(createdFile.Result, shellEntry.Data); // Calls unsupported OpenTransactedWriteAsync
                    await createdFile.Result.WriteBytesAsync(shellEntry.Data);
                }
            }
            return(createdFile);
        }
Exemplo 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))
            {
                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);
            }
        }
Exemplo n.º 3
0
        public async override void GetSpecialProperties()
        {
            ViewModel.ItemAttributesVisibility = false;
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(Drive.Path));

            BaseStorageFolder diskRoot = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(Drive.Path, item));

            if (ViewModel.LoadFileIcon)
            {
                if (diskRoot != null)
                {
                    ViewModel.IconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(diskRoot, 80, ThumbnailMode.SingleItem);
                }
                else
                {
                    ViewModel.IconData = await FileThumbnailHelper.LoadIconWithoutOverlayAsync(Drive.Path, 80);
                }
                ViewModel.IconData ??= await FileThumbnailHelper.LoadIconWithoutOverlayAsync(Drive.DeviceID, 80); // For network shortcuts
            }

            if (diskRoot == null || diskRoot.Properties == null)
            {
                ViewModel.LastSeparatorVisibility = false;
                return;
            }

            try
            {
                string freeSpace  = "System.FreeSpace";
                string capacity   = "System.Capacity";
                string fileSystem = "System.Volume.FileSystem";

                var properties = await diskRoot.Properties.RetrievePropertiesAsync(new[] { freeSpace, capacity, fileSystem });

                ViewModel.DriveCapacityValue  = (ulong)properties[capacity];
                ViewModel.DriveFreeSpaceValue = (ulong)properties[freeSpace];
                ViewModel.DriveUsedSpaceValue = ViewModel.DriveCapacityValue - ViewModel.DriveFreeSpaceValue;
                ViewModel.DriveFileSystem     = (string)properties[fileSystem];
            }
            catch (Exception e)
            {
                ViewModel.LastSeparatorVisibility = false;
                App.Logger.Warn(e, e.Message);
            }
        }
Exemplo n.º 4
0
 public static async Task <IStorageItem> ToStorageItem(this IStorageItemWithPath item, IShellPage associatedInstance = null)
 {
     if (item.Item != null)
     {
         return(item.Item);
     }
     if (!string.IsNullOrEmpty(item.Path))
     {
         return((item.ItemType == FilesystemItemType.File) ?
                (associatedInstance != null ?
                 (IStorageItem)(StorageFile)await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(item.Path) :
                 (IStorageItem)(StorageFile)await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(item.Path))) :
                (associatedInstance != null ?
                 (IStorageItem)(StorageFolder)await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(item.Path) :
                 (IStorageItem)(StorageFolder)await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(item.Path))));
     }
     return(null);
 }
Exemplo n.º 5
0
        public async Task SyncPropertyChangesAsync()
        {
            BaseStorageFile file = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(Item.ItemPath));

            if (file == null)
            {
                // Could not access file, can't save properties
                return;
            }

            var failedProperties = "";

            foreach (var group in ViewModel.PropertySections)
            {
                foreach (FileProperty prop in group)
                {
                    if (!prop.IsReadOnly && prop.Modified)
                    {
                        var newDict = new Dictionary <string, object>();
                        newDict.Add(prop.Property, prop.Value);

                        try
                        {
                            if (file.Properties != null)
                            {
                                await file.Properties.SavePropertiesAsync(newDict);
                            }
                        }
                        catch
                        {
                            failedProperties += $"{prop.Name}\n";
                        }
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(failedProperties))
            {
                throw new Exception($"The following properties failed to save: {failedProperties}");
            }
        }
Exemplo 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 AddItemToSidebar(string path)
        {
            try
            {
                var item = await DrivesManager.GetRootFromPath(path);

                StorageFolder folder = await StorageFileExtensions.GetFolderFromPathAsync(path, item);

                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              = folder.DisplayName
                };

                if (!MainPage.sideBarItems.Contains(locationItem))
                {
                    MainPage.sideBarItems.Insert(insertIndex, locationItem);
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                Debug.WriteLine(ex.Message);
            }
            catch (Exception ex) when(
                ex is ArgumentException || // Pinned item was invalid
                ex is FileNotFoundException || // Pinned item was deleted
                ex is System.Runtime.InteropServices.COMException || // Pinned item's drive was ejected
                (uint)ex.HResult == 0x8007000F || // The system cannot find the drive specified
                (uint)ex.HResult == 0x800700A1)    // The specified path is invalid (usually an mtp device was disconnected)
            {
                Debug.WriteLine("Pinned item was invalid and will be removed from the file lines list soon: " + ex.Message);
                RemoveItem(path);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// This function goes through ever read-write property saved, then syncs it
        /// </summary>
        /// <returns></returns>
        public async Task ClearPropertiesAsync()
        {
            var             failedProperties = new List <string>();
            BaseStorageFile file             = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(Item.ItemPath));

            if (file == null)
            {
                return;
            }

            foreach (var group in ViewModel.PropertySections)
            {
                foreach (FileProperty prop in group)
                {
                    if (!prop.IsReadOnly)
                    {
                        var newDict = new Dictionary <string, object>();
                        newDict.Add(prop.Property, null);

                        try
                        {
                            if (file.Properties != null)
                            {
                                await file.Properties.SavePropertiesAsync(newDict);
                            }
                        }
                        catch
                        {
                            failedProperties.Add(prop.Name);
                        }
                    }
                }
            }

            GetSystemFileProperties();
        }
Exemplo n.º 8
0
        public static async Task <FilesystemResult <BaseStorageFile> > Create(this ShellNewEntry shellEntry, BaseStorageFolder parentFolder, string filePath)
        {
            FilesystemResult <BaseStorageFile> createdFile = null;
            var fileName = Path.GetFileName(filePath);

            if (shellEntry.Template == null)
            {
                createdFile = await FilesystemTasks.Wrap(() => parentFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName).AsTask());
            }
            else
            {
                createdFile = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(shellEntry.Template))
                              .OnSuccess(t => t.CopyAsync(parentFolder, fileName, NameCollisionOption.GenerateUniqueName).AsTask());
            }
            if (createdFile)
            {
                if (shellEntry.Data != null)
                {
                    //await FileIO.WriteBytesAsync(createdFile.Result, shellEntry.Data); // Calls unsupported OpenTransactedWriteAsync
                    await createdFile.Result.WriteBytesAsync(shellEntry.Data);
                }
            }
            return(createdFile);
        }
Exemplo n.º 9
0
        public void SetSelectedPathOrNavigate(string navigationPath, Type sourcePageType, NavigationArguments navArgs = null)
        {
            var destPath        = navArgs != null ? (navArgs.IsSearchResultPage ? navArgs.SearchPathParam : navArgs.NavPathParam) : navigationPath;
            var columnPath      = ((ColumnHost.ActiveBlades.Last().Content as Frame)?.Content as ColumnShellPage)?.FilesystemViewModel.WorkingDirectory;
            var columnFirstPath = ((ColumnHost.ActiveBlades.First().Content as Frame)?.Content as ColumnShellPage)?.FilesystemViewModel.WorkingDirectory;

            if (string.IsNullOrEmpty(destPath) || string.IsNullOrEmpty(destPath) || string.IsNullOrEmpty(destPath))
            {
                ParentShellPageInstance.NavigateToPath(navigationPath, sourcePageType, navArgs);
                return;
            }

            var destComponents        = StorageFileExtensions.GetDirectoryPathComponents(destPath);
            var columnComponents      = StorageFileExtensions.GetDirectoryPathComponents(columnPath);
            var columnFirstComponents = StorageFileExtensions.GetDirectoryPathComponents(columnFirstPath);

            var lastCommonItemIndex = columnComponents
                                      .Select((value, index) => new { value, index })
                                      .LastOrDefault(x => x.index < destComponents.Count && x.value.Path == destComponents[x.index].Path)?.index ?? -1;

            var relativeIndex = lastCommonItemIndex - (columnFirstComponents.Count - 1);

            if (relativeIndex < 0 || destComponents.Count - (lastCommonItemIndex + 1) > 1) // Going above parent or too deep down
            {
                ParentShellPageInstance.NavigateToPath(navigationPath, sourcePageType, navArgs);
            }
            else
            {
                DismissOtherBlades(relativeIndex);

                for (int ii = lastCommonItemIndex + 1; ii < destComponents.Count; ii++)
                {
                    var frame = new Frame();
                    frame.Navigated += Frame_Navigated;
                    var newblade = new BladeItem();
                    newblade.Content = frame;
                    ColumnHost.Items.Add(newblade);

                    if (navArgs != null)
                    {
                        frame.Navigate(typeof(ColumnShellPage), new ColumnParam
                        {
                            Column               = ColumnHost.ActiveBlades.IndexOf(newblade),
                            IsSearchResultPage   = navArgs.IsSearchResultPage,
                            SearchQuery          = navArgs.SearchQuery,
                            NavPathParam         = destComponents[ii].Path,
                            SearchUnindexedItems = navArgs.SearchUnindexedItems,
                            SearchPathParam      = navArgs.SearchPathParam
                        });
                    }
                    else
                    {
                        frame.Navigate(typeof(ColumnShellPage), new ColumnParam
                        {
                            Column       = ColumnHost.ActiveBlades.IndexOf(newblade),
                            NavPathParam = destComponents[ii].Path
                        });
                    }
                }
            }
        }
Exemplo n.º 10
0
        public static async Task <TOut> ToStorageItem <TOut>(string path, IShellPage associatedInstance = null) where TOut : IStorageItem
        {
            FilesystemResult <StorageFile>   file   = null;
            FilesystemResult <StorageFolder> folder = null;

            if (path.ToLower().EndsWith(".lnk") || path.ToLower().EndsWith(".url"))
            {
                // TODO: In the future, when IStorageItemWithPath will inherit from IStorageItem,
                //      we could implement this code here for getting .lnk files
                //      for now, we can't

                return(default(TOut));

                if (false) // Prevent unnecessary exceptions
                {
                    Debugger.Break();
                    throw new ArgumentException("Function ToStorageItem<TOut>() does not support converting from .lnk and .url files");
                }
            }

            if (typeof(IStorageFile).IsAssignableFrom(typeof(TOut)))
            {
                await GetFile();
            }
            else if (typeof(IStorageFolder).IsAssignableFrom(typeof(TOut)))
            {
                await GetFolder();
            }
            else if (typeof(IStorageItem).IsAssignableFrom(typeof(TOut)))
            {
                if (System.IO.Path.HasExtension(path)) // Probably a file
                {
                    await GetFile();
                }
                else // Possibly a folder
                {
                    await GetFolder();

                    if (!folder)
                    {
                        // It wasn't a folder, so check file then because it wasn't checked
                        await GetFile();
                    }
                }
            }

            if (file != null && file)
            {
                return((TOut)(IStorageItem)file.Result);
            }
            else if (folder != null && folder)
            {
                return((TOut)(IStorageItem)folder.Result);
            }

            return(default(TOut));

            // Extensions

            async Task GetFile()
            {
                if (associatedInstance == null)
                {
                    file = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(path));
                }
                else
                {
                    file = await associatedInstance?.FilesystemViewModel?.GetFileFromPathAsync(path);
                }
            }

            async Task GetFolder()
            {
                if (associatedInstance == null)
                {
                    folder = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path));
                }
                else
                {
                    folder = await associatedInstance?.FilesystemViewModel?.GetFolderFromPathAsync(path);
                }
            }
        }
Exemplo n.º 11
0
        public static async Task <FilesystemResult <IStorageItem> > ToStorageItemResult(this IStorageItemWithPath item, IShellPage associatedInstance = null)
        {
            var returnedItem = new FilesystemResult <IStorageItem>(null, FileSystemStatusCode.Generic);

            if (!string.IsNullOrEmpty(item.Path))
            {
                returnedItem = (item.ItemType == FilesystemItemType.File) ?
                               ToType <IStorageItem, StorageFile>(associatedInstance != null ?
                                                                  await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(item.Path) :
                                                                  await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(item.Path))) :
                               ToType <IStorageItem, StorageFolder>(associatedInstance != null ?
                                                                    await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(item.Path) :
                                                                    await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(item.Path)));
            }
            if (returnedItem.Result == null && item.Item != null)
            {
                returnedItem = new FilesystemResult <IStorageItem>(item.Item, FileSystemStatusCode.Success);
            }
            return(returnedItem);
        }
Exemplo n.º 12
0
        private async void SetAddressBarSuggestions(AutoSuggestBox sender, int maxSuggestions = 7)
        {
            try
            {
                IList <ListedItem> suggestions = null;
                var expandedPath = StorageFileExtensions.GetPathWithoutEnvironmentVariable(sender.Text);
                var folderPath   = Path.GetDirectoryName(expandedPath) ?? expandedPath;
                var folder       = await ItemViewModel.GetFolderWithPathFromPathAsync(folderPath);

                var currPath = await folder.GetFoldersWithPathAsync(Path.GetFileName(expandedPath), (uint)maxSuggestions);

                if (currPath.Count() >= maxSuggestions)
                {
                    suggestions = currPath.Select(x => new ListedItem(null)
                    {
                        ItemPath = x.Path, ItemName = x.Folder.Name
                    }).ToList();
                }
                else if (currPath.Any())
                {
                    var subPath = await currPath.First().GetFoldersWithPathAsync((uint)(maxSuggestions - currPath.Count()));

                    suggestions = currPath.Select(x => new ListedItem(null)
                    {
                        ItemPath = x.Path, ItemName = x.Folder.Name
                    }).Concat(
                        subPath.Select(x => new ListedItem(null)
                    {
                        ItemPath = x.Path, ItemName = Path.Combine(currPath.First().Folder.Name, x.Folder.Name)
                    })).ToList();
                }
                else
                {
                    suggestions = new List <ListedItem>()
                    {
                        new ListedItem(null)
                        {
                            ItemPath = App.CurrentInstance.FilesystemViewModel.WorkingDirectory,
                            ItemName = ResourceController.GetTranslation("NavigationToolbarVisiblePathNoResults")
                        }
                    };
                }

                // NavigationBarSuggestions becoming empty causes flickering of the suggestion box
                // Here we check whether at least an element is in common between old and new list
                if (!NavigationBarSuggestions.IntersectBy(suggestions, x => x.ItemName).Any())
                {
                    // No elemets in common, update the list in-place
                    for (int si = 0; si < suggestions.Count; si++)
                    {
                        if (si < NavigationBarSuggestions.Count)
                        {
                            NavigationBarSuggestions[si].ItemName = suggestions[si].ItemName;
                            NavigationBarSuggestions[si].ItemPath = suggestions[si].ItemPath;
                        }
                        else
                        {
                            NavigationBarSuggestions.Add(suggestions[si]);
                        }
                    }
                    while (NavigationBarSuggestions.Count > suggestions.Count)
                    {
                        NavigationBarSuggestions.RemoveAt(NavigationBarSuggestions.Count - 1);
                    }
                }
                else
                {
                    // At least an element in common, show animation
                    foreach (var s in NavigationBarSuggestions.ExceptBy(suggestions, x => x.ItemName).ToList())
                    {
                        NavigationBarSuggestions.Remove(s);
                    }
                    foreach (var s in suggestions.ExceptBy(NavigationBarSuggestions, x => x.ItemName).ToList())
                    {
                        NavigationBarSuggestions.Insert(suggestions.IndexOf(s), s);
                    }
                }
            }
            catch
            {
                NavigationBarSuggestions.Clear();
                NavigationBarSuggestions.Add(new ListedItem(null)
                {
                    ItemPath = App.CurrentInstance.FilesystemViewModel.WorkingDirectory,
                    ItemName = ResourceController.GetTranslation("NavigationToolbarVisiblePathNoResults")
                });
            }
        }
Exemplo n.º 13
0
        public async void CheckPathInput(ItemViewModel instance, string currentInput, string currentSelectedPath)
        {
            if (currentSelectedPath == currentInput)
            {
                return;
            }

            if (currentInput != instance.WorkingDirectory || App.CurrentInstance.ContentFrame.CurrentSourcePageType == typeof(YourHome))
            {
                //(App.CurrentInstance.OperationsControl as RibbonArea).RibbonViewModel.HomeItems.isEnabled = false;
                //(App.CurrentInstance.OperationsControl as RibbonArea).RibbonViewModel.ShareItems.isEnabled = false;

                if (currentInput.Equals("Home", StringComparison.OrdinalIgnoreCase) || currentInput.Equals(ResourceController.GetTranslation("NewTab"), StringComparison.OrdinalIgnoreCase))
                {
                    await App.CurrentInstance.FilesystemViewModel.SetWorkingDirectory(ResourceController.GetTranslation("NewTab"));

                    App.CurrentInstance.ContentFrame.Navigate(typeof(YourHome), ResourceController.GetTranslation("NewTab"), new SuppressNavigationTransitionInfo());
                }
                else
                {
                    var workingDir = string.IsNullOrEmpty(App.CurrentInstance.FilesystemViewModel.WorkingDirectory)
                        ? AppSettings.HomePath
                        : App.CurrentInstance.FilesystemViewModel.WorkingDirectory;

                    currentInput = StorageFileExtensions.GetPathWithoutEnvironmentVariable(currentInput);
                    if (currentSelectedPath == currentInput)
                    {
                        return;
                    }
                    var item = await DrivesManager.GetRootFromPath(currentInput);

                    try
                    {
                        var pathToNavigate = (await StorageFileExtensions.GetFolderWithPathFromPathAsync(currentInput, item)).Path;
                        App.CurrentInstance.ContentFrame.Navigate(AppSettings.GetLayoutType(), pathToNavigate); // navigate to folder
                    }
                    catch (Exception)                                                                           // Not a folder or inaccessible
                    {
                        try
                        {
                            var pathToInvoke = (await StorageFileExtensions.GetFileWithPathFromPathAsync(currentInput, item)).Path;
                            await Interaction.InvokeWin32Component(pathToInvoke);
                        }
                        catch (Exception ex) // Not a file or not accessible
                        {
                            // Launch terminal application if possible
                            foreach (var terminal in AppSettings.TerminalController.Model.Terminals)
                            {
                                if (terminal.Path.Equals(currentInput, StringComparison.OrdinalIgnoreCase) || terminal.Path.Equals(currentInput + ".exe", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (App.Connection != null)
                                    {
                                        var value = new ValueSet
                                        {
                                            { "WorkingDirectory", workingDir },
                                            { "Application", terminal.Path },
                                            { "Arguments", string.Format(terminal.Arguments,
                                                                         Helpers.PathNormalization.NormalizePath(App.CurrentInstance.FilesystemViewModel.WorkingDirectory)) }
                                        };
                                        await App.Connection.SendMessageAsync(value);
                                    }
                                    return;
                                }
                            }

                            try
                            {
                                if (!await Launcher.LaunchUriAsync(new Uri(currentInput)))
                                {
                                    throw new Exception();
                                }
                            }
                            catch
                            {
                                await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("InvalidItemDialogTitle"), string.Format(ResourceController.GetTranslation("InvalidItemDialogContent"), ex.Message));
                            }
                        }
                    }
                }

                App.CurrentInstance.NavigationToolbar.PathControlDisplayText = App.CurrentInstance.FilesystemViewModel.WorkingDirectory;
            }
        }
Exemplo n.º 14
0
        public async void CheckPathInput(ItemViewModel instance, string CurrentInput)
        {
            if (CurrentInput != instance.WorkingDirectory || App.CurrentInstance.ContentFrame.CurrentSourcePageType == typeof(YourHome))
            {
                //(App.CurrentInstance.OperationsControl as RibbonArea).RibbonViewModel.HomeItems.isEnabled = false;
                //(App.CurrentInstance.OperationsControl as RibbonArea).RibbonViewModel.ShareItems.isEnabled = false;

                if (CurrentInput.Equals("Home", StringComparison.OrdinalIgnoreCase) || CurrentInput.Equals(ResourceController.GetTranslation("NewTab"), StringComparison.OrdinalIgnoreCase))
                {
                    await App.CurrentInstance.FilesystemViewModel.SetWorkingDirectory(ResourceController.GetTranslation("NewTab"));

                    App.CurrentInstance.ContentFrame.Navigate(typeof(YourHome), ResourceController.GetTranslation("NewTab"), new SuppressNavigationTransitionInfo());
                }
                else
                {
                    switch (CurrentInput.ToLower())
                    {
                    case "%temp%":
                        CurrentInput = AppSettings.TempPath;
                        break;

                    case "%appdata":
                        CurrentInput = AppSettings.AppDataPath;
                        break;

                    case "%homepath%":
                        CurrentInput = AppSettings.HomePath;
                        break;

                    case "%windir%":
                        CurrentInput = AppSettings.WinDirPath;
                        break;
                    }

                    try
                    {
                        var item = await DrivesManager.GetRootFromPath(CurrentInput);

                        await StorageFileExtensions.GetFolderFromPathAsync(CurrentInput, item);

                        App.CurrentInstance.ContentFrame.Navigate(AppSettings.GetLayoutType(), CurrentInput); // navigate to folder
                    }
                    catch (Exception)                                                                         // Not a folder or inaccessible
                    {
                        try
                        {
                            var item = await DrivesManager.GetRootFromPath(CurrentInput);

                            await StorageFileExtensions.GetFileFromPathAsync(CurrentInput, item);

                            await Interaction.InvokeWin32Component(CurrentInput);
                        }
                        catch (Exception ex) // Not a file or not accessible
                        {
                            // Launch terminal application if possible
                            foreach (var item in AppSettings.TerminalsModel.Terminals)
                            {
                                if (item.Path.Equals(CurrentInput, StringComparison.OrdinalIgnoreCase) || item.Path.Equals(CurrentInput + ".exe", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (App.Connection != null)
                                    {
                                        var value = new ValueSet();
                                        value.Add("Application", item.Path);
                                        value.Add("Arguments", String.Format(item.Arguments, App.CurrentInstance.FilesystemViewModel.WorkingDirectory));
                                        await App.Connection.SendMessageAsync(value);
                                    }
                                    return;
                                }
                            }

                            var dialog = new ContentDialog()
                            {
                                Title           = "Invalid item",
                                Content         = "The item referenced is either invalid or inaccessible.\nMessage:\n\n" + ex.Message,
                                CloseButtonText = "OK"
                            };

                            await dialog.ShowAsync();
                        }
                    }
                }

                App.CurrentInstance.NavigationToolbar.PathControlDisplayText = App.CurrentInstance.FilesystemViewModel.WorkingDirectory;
            }
        }
Exemplo n.º 15
0
 private static async Task <FilesystemResult <StorageFolder> > GetStorageFolderAsync(string path)
 => await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path));
Exemplo n.º 16
0
        // TODO: If the TODO of IStorageItemWithPath is implemented, change return type to IStorageItem
        public static async Task <IStorageItem> ToStorageItem(this string path, StorageFolderWithPath parentFolder = null)
        {
            FilesystemResult <StorageFolderWithPath> fsRootFolderResult = await FilesystemTasks.Wrap(async() =>
            {
                return((StorageFolderWithPath)await Path.GetPathRoot(path).ToStorageItemWithPath());
            });

            FilesystemResult <StorageFile> fsFileResult = await FilesystemTasks.Wrap(() =>
            {
                return(StorageFileExtensions.DangerousGetFileFromPathAsync(path, fsRootFolderResult.Result, parentFolder));
            });

            if (fsFileResult)
            {
                if (!string.IsNullOrWhiteSpace(fsFileResult.Result.Path))
                {
                    return(fsFileResult.Result);
                }
                else
                {
                    FilesystemResult <StorageFileWithPath> fsFileWithPathResult = await FilesystemTasks.Wrap(() =>
                    {
                        return(StorageFileExtensions.DangerousGetFileWithPathFromPathAsync(path, fsRootFolderResult));
                    });

                    if (fsFileWithPathResult)
                    {
                        return(null); /* fsFileWithPathResult.Result */ // Could be done if IStorageItemWithPath implemented IStorageItem
                    }
                }
            }

            FilesystemResult <StorageFolder> fsFolderResult = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path));

            if (fsFolderResult)
            {
                if (!string.IsNullOrWhiteSpace(fsFolderResult.Result.Path))
                {
                    return(fsFolderResult.Result);
                }
                else
                {
                    FilesystemResult <StorageFolderWithPath> fsFolderWithPathResult = await FilesystemTasks.Wrap(() =>
                    {
                        return(StorageFileExtensions.DangerousGetFolderWithPathFromPathAsync(path, fsRootFolderResult));
                    });

                    if (fsFolderWithPathResult)
                    {
                        return(null); /* fsFolderWithPathResult.Result; */ // Could be done if IStorageItemWithPath implemented IStorageItem
                    }
                }
            }

            return(null);
        }