A game framework written with osu! in mind.
at master 83 lines 2.6 kB view raw
1// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. 2// See the LICENCE file in the repository root for full licence text. 3 4using System; 5using System.Collections.Generic; 6using System.IO; 7using System.Linq; 8using osu.Framework.Allocation; 9using osu.Framework.Bindables; 10using osu.Framework.Extensions.EnumExtensions; 11using osu.Framework.Input.Events; 12 13namespace osu.Framework.Graphics.UserInterface 14{ 15 /// <summary> 16 /// A component which allows a user to select a file. 17 /// </summary> 18 public abstract class FileSelector : DirectorySelector 19 { 20 private readonly string[] validFileExtensions; 21 protected abstract DirectoryListingFile CreateFileItem(FileInfo file); 22 23 [Cached] 24 public readonly Bindable<FileInfo> CurrentFile = new Bindable<FileInfo>(); 25 26 protected FileSelector(string initialPath = null, string[] validFileExtensions = null) 27 : base(initialPath) 28 { 29 this.validFileExtensions = validFileExtensions ?? Array.Empty<string>(); 30 } 31 32 protected override bool TryGetEntriesForPath(DirectoryInfo path, out ICollection<DirectorySelectorItem> items) 33 { 34 items = new List<DirectorySelectorItem>(); 35 36 if (!base.TryGetEntriesForPath(path, out var directories)) 37 return false; 38 39 items = directories; 40 41 try 42 { 43 IEnumerable<FileInfo> files = path.GetFiles(); 44 45 if (validFileExtensions.Length > 0) 46 files = files.Where(f => validFileExtensions.Contains(f.Extension)); 47 48 foreach (var file in files.OrderBy(d => d.Name)) 49 { 50 if (!file.Attributes.HasFlagFast(FileAttributes.Hidden)) 51 items.Add(CreateFileItem(file)); 52 } 53 54 return true; 55 } 56 catch 57 { 58 return false; 59 } 60 } 61 62 protected abstract class DirectoryListingFile : DirectorySelectorItem 63 { 64 protected readonly FileInfo File; 65 66 [Resolved] 67 private Bindable<FileInfo> currentFile { get; set; } 68 69 protected DirectoryListingFile(FileInfo file) 70 { 71 File = file; 72 } 73 74 protected override bool OnClick(ClickEvent e) 75 { 76 currentFile.Value = File; 77 return true; 78 } 79 80 protected override string FallbackName => File.Name; 81 } 82 } 83}