Example #1
0
        public SettingsViewModel()
        {
            _roamingSettings = ApplicationData.Current.RoamingSettings;

            DetectOneDrivePreference();
            DetectAcrylicPreference();
            DetectDateTimeFormat();
            PinSidebarLocationItems();
            DetectRecycleBinPreference();
            DetectQuickLook();
            DetectGridViewSize();

            DrivesManager = new DrivesManager();

            //DetectWSLDistros();
            LoadTerminalApps();

            // Send analytics
            Analytics.TrackEvent("DisplayedTimeStyle " + DisplayedTimeStyle.ToString());
            Analytics.TrackEvent("ThemeValue " + ThemeHelper.RootTheme.ToString());
            Analytics.TrackEvent("PinOneDriveToSideBar " + PinOneDriveToSideBar.ToString());
            Analytics.TrackEvent("PinRecycleBinToSideBar " + PinRecycleBinToSideBar.ToString());
            Analytics.TrackEvent("DoubleTapToRenameFiles " + DoubleTapToRenameFiles.ToString());
            Analytics.TrackEvent("ShowFileExtensions " + ShowFileExtensions.ToString());
            Analytics.TrackEvent("ShowConfirmDeleteDialog " + ShowConfirmDeleteDialog.ToString());
            Analytics.TrackEvent("AcrylicSidebar " + AcrylicEnabled.ToString());
        }
Example #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)ItemViewModel.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);
            }
        }
Example #3
0
        public static async Task LoadOtherStuffAsync()
        {
            // Start off a list of tasks we need to run before we can continue startup
            await StartAppCenter();

            await Task.Run(async() =>
            {
                await Task.WhenAll(
                    DrivesManager.EnumerateDrivesAsync(),
                    CloudDrivesManager.EnumerateDrivesAsync(),
                    LibraryManager.EnumerateLibrariesAsync(),
                    NetworkDrivesManager.EnumerateDrivesAsync(),
                    WSLDistroManager.EnumerateDrivesAsync(),
                    SidebarPinnedController.InitializeAsync()
                    );
                await Task.WhenAll(
                    AppSettings.DetectQuickLook(),
                    TerminalController.InitializeAsync(),
                    JumpList.InitializeAsync(),
                    ExternalResourcesHelper.LoadOtherThemesAsync(),
                    ContextFlyoutItemHelper.CachedNewContextMenuEntries
                    );
            });

            // Check for required updates
            new AppUpdater().CheckForUpdatesAsync();
        }
Example #4
0
        private static async Task InitializeAppComponentsAsync()
        {
            var userSettingsService = Ioc.Default.GetRequiredService <IUserSettingsService>();

            // Start off a list of tasks we need to run before we can continue startup
            await Task.Run(async() =>
            {
                await Task.WhenAll(
                    StartAppCenter(),
                    DrivesManager.EnumerateDrivesAsync(),
                    CloudDrivesManager.EnumerateDrivesAsync(),
                    LibraryManager.EnumerateLibrariesAsync(),
                    NetworkDrivesManager.EnumerateDrivesAsync(),
                    WSLDistroManager.EnumerateDrivesAsync(),
                    FileTagsManager.EnumerateFileTagsAsync(),
                    SidebarPinnedController.InitializeAsync()
                    );
                await Task.WhenAll(
                    AppSettings.DetectQuickLook(),
                    TerminalController.InitializeAsync(),
                    JumpList.InitializeAsync(),
                    ExternalResourcesHelper.LoadOtherThemesAsync(),
                    ContextFlyoutItemHelper.CachedNewContextMenuEntries
                    );

                userSettingsService.ReportToAppCenter();
            });

            // Check for required updates
            var updateService = Ioc.Default.GetRequiredService <IUpdateService>();
            await updateService.CheckForUpdates();

            await updateService.DownloadMandatoryUpdates();
        }
Example #5
0
        public static async Task <IStorageItemWithPath> ToStorageItemWithPath(this string path, StorageFolderWithPath parentFolder = null)
        {
            StorageFolderWithPath rootFolder = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            FilesystemResult <StorageFileWithPath> fsFileWithPathResult = await FilesystemTasks.Wrap(() =>
            {
                return(StorageFileExtensions.DangerousGetFileWithPathFromPathAsync(path, rootFolder, parentFolder));
            });

            if (fsFileWithPathResult)
            {
                return(fsFileWithPathResult.Result);
            }

            FilesystemResult <StorageFolderWithPath> fsFolderWithPathResult = await FilesystemTasks.Wrap(() =>
            {
                return(StorageFileExtensions.DangerousGetFolderWithPathFromPathAsync(path, rootFolder));
            });

            if (fsFolderWithPathResult)
            {
                return(fsFolderWithPathResult.Result);
            }

            return(null);
        }
Example #6
0
        private async Task <SettingsViewModel> Initialize()
        {
            DetectDateTimeFormat();
            PinSidebarLocationItems();
            DetectRecycleBinPreference();
            DetectQuickLook();

            // Load the supported languages
            var supportedLang = ApplicationLanguages.ManifestLanguages;

            DefaultLanguages = new ObservableCollection <DefaultLanguageModel> {
                new DefaultLanguageModel(null)
            };
            foreach (var lang in supportedLang)
            {
                DefaultLanguages.Add(new DefaultLanguageModel(lang));
            }

            DrivesManager = await DrivesManager.CreateInstance();

            //Initialise cloud drives in the background
            CloudDrivesManager = await CloudDrivesManager.CreateInstance();

            //DetectWSLDistros();
            TerminalController = await TerminalController.CreateInstance();

            // Send analytics to AppCenter
            TrackAnalytics();

            return(this);
        }
Example #7
0
        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            // Save application state and stop any background activity
            var deferral = e.SuspendingOperation.GetDeferral();

            SaveSessionTabs();

            if (OutputPath != null)
            {
                await Common.Extensions.IgnoreExceptions(async() =>
                {
                    var instance = MainPageViewModel.AppInstances.FirstOrDefault(x => x.Control.TabItemContent.IsCurrentInstance);
                    if (instance == null)
                    {
                        return;
                    }
                    var items = (instance.Control.TabItemContent as PaneHolderPage)?.ActivePane?.SlimContentPage?.SelectedItems;
                    if (items == null)
                    {
                        return;
                    }
                    await FileIO.WriteLinesAsync(await StorageFile.GetFileFromPathAsync(OutputPath), items.Select(x => x.ItemPath));
                }, Logger);
            }

            DrivesManager?.Dispose();
            deferral.Complete();
        }
Example #8
0
        private void PopulateDrives()
        {
            var selectedDrives = UserSettings.Instance.SelectedDrives;

            Drives = new ObservableCollection <DriveInfo>();

            var filterDir = CmdArgumentsParser.FilterDirPath;

            foreach (var driveInfo in DrivesManager.GetDrives())
            {
                var drive     = driveInfo.Name;
                var isChecked = selectedDrives == null || selectedDrives.Count == 0 || selectedDrives.Contains(drive) ||
                                (!string.IsNullOrEmpty(filterDir) && filterDir[0] == drive);

                var di = new DriveInfo(drive, driveInfo.Label, isChecked);
                Drives.Add(di);
            }

            //DrivesManager.OnDeviceInserted += info => AddDrive(new DriveInfo(info.Name, info.Label));
            //DrivesManager.OnDeviceRemoved += driveName =>
            //    {
            //        var old = Drives.SingleOrDefault(d => d.Name == driveName);
            //        RemoveDrive(old);
            //    };
        }
Example #9
0
        private static async Task EnsureSettingsAndConfigurationAreBootstrapped()
        {
            if (AppSettings == null)
            {
                AppSettings = await SettingsViewModel.CreateInstance();
            }

            ExternalResourcesHelper ??= new ExternalResourcesHelper();
            await ExternalResourcesHelper.LoadSelectedTheme();

            InteractionViewModel ??= new InteractionViewModel();
            SidebarPinnedController ??= await SidebarPinnedController.CreateInstance();

            LibraryManager ??= new LibraryManager();
            DrivesManager ??= new DrivesManager();
            NetworkDrivesManager ??= new NetworkDrivesManager();
            CloudDrivesManager ??= new CloudDrivesManager();
            WSLDistroManager ??= new WSLDistroManager();

            // Start off a list of tasks we need to run before we can continue startup
            _ = Task.Factory.StartNew(async() =>
            {
                await LibraryManager.EnumerateLibrariesAsync();
                await DrivesManager.EnumerateDrivesAsync();
                await CloudDrivesManager.EnumerateDrivesAsync();
                await NetworkDrivesManager.EnumerateDrivesAsync();
                await WSLDistroManager.EnumerateDrivesAsync();
            });
        }
        /// <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);
            }
        }
Example #11
0
        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
                };
                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);
            }
        }
Example #12
0
        public SettingsViewModel()
        {
            DetectDateTimeFormat();
            PinSidebarLocationItems();
            DetectRecycleBinPreference();
            DetectQuickLook();
            DrivesManager = new DrivesManager();

            //DetectWSLDistros();
            TerminalController = new TerminalController();

            // Send analytics to AppCenter
            TrackAnalytics();

            // Load the supported languages
            var supportedLang = ApplicationLanguages.ManifestLanguages;

            DefaultLanguages = new ObservableCollection <DefaultLanguageModel> {
                new DefaultLanguageModel(null)
            };
            foreach (var lang in supportedLang)
            {
                DefaultLanguages.Add(new DefaultLanguageModel(lang));
            }
        }
Example #13
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);
        }
Example #14
0
        private async Task LoadPreviewAndDetailsAsync()
        {
            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
            string returnformat = Enum.Parse <TimeStyle>(localSettings.Values[Constants.LocalSettings.DateTimeFormat].ToString()) == TimeStyle.Application ? "D" : "g";

            var rootItem = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(Item.ItemPath));

            Folder = await StorageFileExtensions.DangerousGetFolderFromPathAsync(Item.ItemPath, rootItem);

            var items = await Folder.GetItemsAsync();

            var iconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(Folder, 400, ThumbnailMode.SingleItem);

            iconData ??= await FileThumbnailHelper.LoadIconWithoutOverlayAsync(Item.ItemPath, 400);

            if (iconData != null)
            {
                Thumbnail = await iconData.ToBitmapAsync();
            }

            var info = await Folder.GetBasicPropertiesAsync();

            Item.FileDetails = new ObservableCollection <FileProperty>()
            {
                new FileProperty()
                {
                    NameResource = "PropertyItemCount",
                    Value        = items.Count,
                },
                new FileProperty()
                {
                    NameResource = "PropertyDateModified",
                    Value        = Extensions.DateTimeExtensions.GetFriendlyDateFromFormat(info.DateModified, returnformat, true)
                },
                new FileProperty()
                {
                    NameResource = "PropertyDateCreated",
                    Value        = Extensions.DateTimeExtensions.GetFriendlyDateFromFormat(info.ItemDate, returnformat, true)
                },
                new FileProperty()
                {
                    NameResource = "PropertyItemPathDisplay",
                    Value        = Folder.Path,
                }
            };

            if (UserSettingsService.PreferencesSettingsService.AreFileTagsEnabled)
            {
                Item.FileDetails.Add(new FileProperty()
                {
                    NameResource = "DetailsViewHeaderFlyout_ShowFileTag/Text",
                    Value        = Item.FileTagUI?.TagName
                });
            }
        }
Example #15
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));
            }
        }
Example #16
0
        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            SaveSessionTabs();

            var deferral = e.SuspendingOperation.GetDeferral();

            //TODO: Save application state and stop any background activity

            DrivesManager?.Dispose();
            deferral.Complete();
        }
Example #17
0
        public SettingsViewModel()
        {
            DetectCustomLocations();
            DetectApplicationTheme();
            DetectDateTimeFormat();
            DetectSidebarOpacity();
            PinSidebarLocationItems();
            DetectOneDrivePreference();
            DrivesManager = new DrivesManager();

            foundDrives = DrivesManager.Drives;
            //DetectWSLDistros();
            LoadTerminalApps();
        }
        public SettingsViewModel()
        {
            _roamingSettings = ApplicationData.Current.RoamingSettings;

            DetectApplicationTheme();
            DetectOneDrivePreference();
            DetectDateTimeFormat();
            PinSidebarLocationItems();
            DetectQuickLook();

            DrivesManager = new DrivesManager();

            //DetectWSLDistros();
            LoadTerminalApps();
        }
Example #19
0
        public async override void GetSpecialProperties()
        {
            ViewModel.ItemAttributesVisibility = Visibility.Collapsed;
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(Drive.Path));

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

            if (ViewModel.LoadFileIcon)
            {
                if (diskRoot != null)
                {
                    using var thumbnail = await diskRoot.GetThumbnailAsync(ThumbnailMode.SingleItem, 80, ThumbnailOptions.UseCurrentScale);

                    ViewModel.IconData = await thumbnail.ToByteArrayAsync();
                }
                else
                {
                    var fileIconData = await FileThumbnailHelper.LoadIconWithoutOverlayAsync(Drive.Path, 80);

                    ViewModel.IconData = fileIconData;
                }
            }

            if (diskRoot == null)
            {
                ViewModel.LastSeparatorVisibility = Visibility.Collapsed;
                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 = Visibility.Collapsed;
                App.Logger.Warn(e, e.Message);
            }
        }
Example #20
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);
            }
        }
Example #21
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);
            }
        }
Example #22
0
        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            // Save application state and stop any background activity
            var deferral = e.SuspendingOperation.GetDeferral();

            SaveSessionTabs();

            if (OutputPath != null)
            {
                await SafetyExtensions.IgnoreExceptions(async() =>
                {
                    var instance = MainPageViewModel.AppInstances.FirstOrDefault(x => x.Control.TabItemContent.IsCurrentInstance);
                    if (instance == null)
                    {
                        return;
                    }
                    var items = (instance.Control.TabItemContent as PaneHolderPage)?.ActivePane?.SlimContentPage?.SelectedItems;
                    if (items == null)
                    {
                        return;
                    }
                    await FileIO.WriteLinesAsync(await StorageFile.GetFileFromPathAsync(OutputPath), items.Select(x => x.ItemPath));
                }, Logger);
            }

            DrivesManager?.Dispose();
            PaneViewModel?.Dispose();
            PreviewPaneViewModel?.Dispose();

            // Try to maintain clipboard data after app close
            SafetyExtensions.IgnoreExceptions(() =>
            {
                var dataPackage = Clipboard.GetContent();
                if (dataPackage.Properties.PackageFamilyName == Package.Current.Id.FamilyName)
                {
                    if (dataPackage.Contains(StandardDataFormats.StorageItems))
                    {
                        Clipboard.Flush();
                    }
                }
            }, Logger);

            deferral.Complete();
        }
Example #23
0
        public static async Task LoadOtherStuffAsync()
        {
            ExternalResourcesHelper.LoadOtherThemesAsync();

            // Start off a list of tasks we need to run before we can continue startup
            _ = Task.Run(async() =>
            {
                await Task.WhenAll(
                    SidebarPinnedController.InitializeAsync(),
                    DrivesManager.EnumerateDrivesAsync(),
                    CloudDrivesManager.EnumerateDrivesAsync(),
                    LibraryManager.EnumerateLibrariesAsync(),
                    NetworkDrivesManager.EnumerateDrivesAsync(),
                    WSLDistroManager.EnumerateDrivesAsync()
                    );
            });

            ExternalResourcesHelper.LoadOtherThemesAsync();
        }
        public SettingsViewModel()
        {
            _roamingSettings = ApplicationData.Current.RoamingSettings;

            DetectOneDrivePreference();
            DetectAcrylicPreference();
            DetectDateTimeFormat();
            PinSidebarLocationItems();
            DetectRecycleBinPreference();
            DetectQuickLook();
            DetectGridViewSize();
            DrivesManager = new DrivesManager();

            //DetectWSLDistros();
            TerminalController = new TerminalController();

            // Send analytics
            Analytics.TrackEvent("DisplayedTimeStyle " + DisplayedTimeStyle.ToString());
            Analytics.TrackEvent("ThemeValue " + ThemeHelper.RootTheme.ToString());
            Analytics.TrackEvent("PinOneDriveToSideBar " + PinOneDriveToSideBar.ToString());
            Analytics.TrackEvent("PinRecycleBinToSideBar " + PinRecycleBinToSideBar.ToString());
            Analytics.TrackEvent("DoubleTapToRenameFiles " + DoubleTapToRenameFiles.ToString());
            Analytics.TrackEvent("ShowFileExtensions " + ShowFileExtensions.ToString());
            Analytics.TrackEvent("ShowConfirmDeleteDialog " + ShowConfirmDeleteDialog.ToString());
            Analytics.TrackEvent("AcrylicSidebar " + AcrylicEnabled.ToString());
            Analytics.TrackEvent("ShowFileOwner " + ShowFileOwner.ToString());
            Analytics.TrackEvent("IsHorizontalTabStripVisible " + IsHorizontalTabStripVisible.ToString());
            Analytics.TrackEvent("IsMultitaskingControlVisible " + IsMultitaskingControlVisible.ToString());
            // Load the supported languages

            var supportedLang = ApplicationLanguages.ManifestLanguages;

            DefaultLanguages = new ObservableCollection <DefaultLanguageModel> {
                new DefaultLanguageModel(null)
            };
            foreach (var lang in supportedLang)
            {
                DefaultLanguages.Add(new DefaultLanguageModel(lang));
            }
        }
Example #25
0
        internal static async Task EnsureSettingsAndConfigurationAreBootstrapped()
        {
            if (AppSettings == null)
            {
                //We can't create AppSettings at the same time as everything else as other dependencies depend on AppSettings
                AppSettings = await SettingsViewModel.CreateInstance();

                if (App.AppSettings?.AcrylicTheme == null)
                {
                    Helpers.ThemeHelper.Initialize();
                }
            }

            if (CloudDrivesManager == null)
            {
                //Enumerate cloud drives on in the background. It will update the UI itself when finished
                _ = Files.Filesystem.CloudDrivesManager.Instance.ContinueWith(o =>
                {
                    CloudDrivesManager = o.Result;
                });
            }

            //Start off a list of tasks we need to run before we can continue startup
            var tasksToRun = new List <Task>();

            if (SidebarPinnedController == null)
            {
                tasksToRun.Add(Files.Controllers.SidebarPinnedController.CreateInstance().ContinueWith(o => SidebarPinnedController = o.Result));
            }

            if (DrivesManager == null)
            {
                tasksToRun.Add(Files.Filesystem.DrivesManager.Instance.ContinueWith(o => DrivesManager = o.Result));
            }

            if (InteractionViewModel == null)
            {
                InteractionViewModel = new InteractionViewModel();
            }

            if (tasksToRun.Any())
            {
                //Only proceed when all tasks are completed
                await Task.WhenAll(tasksToRun);
            }
        }
Example #26
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;
            }
        }
Example #27
0
 private void OnLeavingBackground(object sender, LeavingBackgroundEventArgs e)
 {
     DrivesManager?.ResumeDeviceWatcher();
 }
Example #28
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;
            }
        }