FileDialog.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.IO;
  5. using System.IO.Abstractions;
  6. using System.Linq;
  7. using System.Text.RegularExpressions;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using System.Text;
  11. using Terminal.Gui.Resources;
  12. using static Terminal.Gui.ConfigurationManager;
  13. namespace Terminal.Gui {
  14. /// <summary>
  15. /// Modal dialog for selecting files/directories. Has auto-complete and expandable
  16. /// navigation pane (Recent, Root drives etc).
  17. /// </summary>
  18. public partial class FileDialog : Dialog {
  19. /// <summary>
  20. /// Gets settings for controlling how visual elements behave. Style changes should
  21. /// be made before the <see cref="Dialog"/> is loaded and shown to the user for the
  22. /// first time.
  23. /// </summary>
  24. public FileDialogStyle Style { get; }
  25. /// <summary>
  26. /// The maximum number of results that will be collected
  27. /// when searching before stopping.
  28. /// </summary>
  29. /// <remarks>
  30. /// This prevents performance issues e.g. when searching
  31. /// root of file system for a common letter (e.g. 'e').
  32. /// </remarks>
  33. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  34. public static int MaxSearchResults { get; set; } = 10000;
  35. /// <summary>
  36. /// True if the file/folder must exist already to be selected.
  37. /// This prevents user from entering the name of something that
  38. /// doesn't exist. Defaults to false.
  39. /// </summary>
  40. public bool MustExist { get; set; }
  41. /// <summary>
  42. /// Gets the Path separators for the operating system
  43. /// </summary>
  44. internal static char [] Separators = new []
  45. {
  46. System.IO.Path.AltDirectorySeparatorChar,
  47. System.IO.Path.DirectorySeparatorChar,
  48. };
  49. /// <summary>
  50. /// Characters to prevent entry into <see cref="tbPath"/>. Note that this is not using
  51. /// <see cref="System.IO.Path.GetInvalidFileNameChars"/> because we do want to allow directory
  52. /// separators, arrow keys etc.
  53. /// </summary>
  54. private static char [] badChars = new []
  55. {
  56. '"','<','>','|','*','?',
  57. };
  58. /// <summary>
  59. /// The UI selected <see cref="IAllowedType"/> from combo box. May be null.
  60. /// </summary>
  61. public IAllowedType CurrentFilter { get; private set; }
  62. private bool pushingState = false;
  63. private bool loaded = false;
  64. /// <summary>
  65. /// Gets the currently open directory and known children presented in the dialog.
  66. /// </summary>
  67. internal FileDialogState State { get; private set; }
  68. /// <summary>
  69. /// Locking object for ensuring only a single <see cref="SearchState"/> executes at once.
  70. /// </summary>
  71. internal object onlyOneSearchLock = new object ();
  72. private bool disposed = false;
  73. private IFileSystem fileSystem;
  74. private TextField tbPath;
  75. private FileDialogHistory history;
  76. private TableView tableView;
  77. private TreeView<IFileSystemInfo> treeView;
  78. private TileView splitContainer;
  79. private Button btnOk;
  80. private Button btnCancel;
  81. private Button btnToggleSplitterCollapse;
  82. private Button btnForward;
  83. private Button btnBack;
  84. private Button btnUp;
  85. private string feedback;
  86. private TextField tbFind;
  87. private SpinnerView spinnerView;
  88. private MenuBar allowedTypeMenuBar;
  89. private MenuBarItem allowedTypeMenu;
  90. private MenuItem [] allowedTypeMenuItems;
  91. private int currentSortColumn;
  92. private bool currentSortIsAsc = true;
  93. private Dictionary<IDirectoryInfo,string> _treeRoots = new Dictionary<IDirectoryInfo, string>();
  94. /// <summary>
  95. /// Event fired when user attempts to confirm a selection (or multi selection).
  96. /// Allows you to cancel the selection or undertake alternative behavior e.g.
  97. /// open a dialog "File already exists, Overwrite? yes/no".
  98. /// </summary>
  99. public event EventHandler<FilesSelectedEventArgs> FilesSelected;
  100. /// <summary>
  101. /// Gets or sets behavior of the <see cref="FileDialog"/> when the user attempts
  102. /// to delete a selected file(s). Set to null to prevent deleting.
  103. /// </summary>
  104. /// <remarks>Ensure you use a try/catch block with appropriate
  105. /// error handling (e.g. showing a <see cref="MessageBox"/></remarks>
  106. public IFileOperations FileOperationsHandler { get; set; } = new DefaultFileOperations ();
  107. /// <summary>
  108. /// Initializes a new instance of the <see cref="FileDialog"/> class.
  109. /// </summary>
  110. public FileDialog () : this (new FileSystem ())
  111. {
  112. }
  113. /// <summary>
  114. /// Initializes a new instance of the <see cref="FileDialog"/> class with
  115. /// a custom <see cref="IFileSystem"/>.
  116. /// </summary>
  117. /// <remarks>This overload is mainly useful for testing.</remarks>
  118. public FileDialog (IFileSystem fileSystem)
  119. {
  120. this.fileSystem = fileSystem;
  121. Style = new FileDialogStyle (fileSystem);
  122. this.btnOk = new Button (Style.OkButtonText) {
  123. Y = Pos.AnchorEnd (1),
  124. X = Pos.Function (() =>
  125. this.Bounds.Width
  126. - btnOk.Bounds.Width
  127. // TODO: Fiddle factor, seems the Bounds are wrong for someone
  128. - 2)
  129. };
  130. this.btnOk.Clicked += (s, e) => this.Accept (true);
  131. this.btnOk.KeyPress += (s, k) => {
  132. this.NavigateIf (k, Key.CursorLeft, this.btnCancel);
  133. this.NavigateIf (k, Key.CursorUp, this.tableView);
  134. };
  135. this.btnCancel = new Button ("Cancel") {
  136. Y = Pos.AnchorEnd (1),
  137. X = Pos.Function (() =>
  138. this.Bounds.Width
  139. - btnOk.Bounds.Width
  140. - btnCancel.Bounds.Width
  141. - 1
  142. // TODO: Fiddle factor, seems the Bounds are wrong for someone
  143. - 2
  144. )
  145. };
  146. this.btnCancel.KeyPress += (s, k) => {
  147. this.NavigateIf (k, Key.CursorLeft, this.btnToggleSplitterCollapse);
  148. this.NavigateIf (k, Key.CursorUp, this.tableView);
  149. this.NavigateIf (k, Key.CursorRight, this.btnOk);
  150. };
  151. this.btnCancel.Clicked += (s, e) => {
  152. Application.RequestStop ();
  153. };
  154. this.btnUp = new Button () { X = 0, Y = 1, NoPadding = true };
  155. btnUp.Text = GetUpButtonText ();
  156. this.btnUp.Clicked += (s, e) => this.history.Up ();
  157. this.btnBack = new Button () { X = Pos.Right (btnUp) + 1, Y = 1, NoPadding = true };
  158. btnBack.Text = GetBackButtonText ();
  159. this.btnBack.Clicked += (s, e) => this.history.Back ();
  160. this.btnForward = new Button () { X = Pos.Right (btnBack) + 1, Y = 1, NoPadding = true };
  161. btnForward.Text = GetForwardButtonText ();
  162. this.btnForward.Clicked += (s, e) => this.history.Forward ();
  163. this.tbPath = new TextField {
  164. Width = Dim.Fill (0),
  165. Caption = Style.PathCaption,
  166. CaptionColor = Color.Black
  167. };
  168. this.tbPath.KeyPress += (s, k) => {
  169. ClearFeedback ();
  170. this.AcceptIf (k, Key.Enter);
  171. this.SuppressIfBadChar (k);
  172. };
  173. tbPath.Autocomplete = new AppendAutocomplete (tbPath);
  174. tbPath.Autocomplete.SuggestionGenerator = new FilepathSuggestionGenerator ();
  175. this.splitContainer = new TileView () {
  176. X = 0,
  177. Y = 2,
  178. Width = Dim.Fill (0),
  179. Height = Dim.Fill (1),
  180. };
  181. this.splitContainer.SetSplitterPos (0, 30);
  182. // this.splitContainer.Border.BorderStyle = BorderStyle.None;
  183. this.splitContainer.Tiles.ElementAt (0).ContentView.Visible = false;
  184. this.tableView = new TableView {
  185. Width = Dim.Fill (),
  186. Height = Dim.Fill (),
  187. FullRowSelect = true,
  188. CollectionNavigator = new FileDialogCollectionNavigator (this)
  189. };
  190. this.tableView.AddKeyBinding (Key.Space, Command.ToggleChecked);
  191. this.tableView.MouseClick += OnTableViewMouseClick;
  192. Style.TableStyle = tableView.Style;
  193. var nameStyle = Style.TableStyle.GetOrCreateColumnStyle (0);
  194. nameStyle.MinWidth = 10;
  195. nameStyle.ColorGetter = this.ColorGetter;
  196. var sizeStyle = Style.TableStyle.GetOrCreateColumnStyle (1);
  197. sizeStyle.MinWidth = 10;
  198. sizeStyle.ColorGetter = this.ColorGetter;
  199. var dateModifiedStyle = Style.TableStyle.GetOrCreateColumnStyle (2);
  200. dateModifiedStyle.MinWidth = 30;
  201. dateModifiedStyle.ColorGetter = this.ColorGetter;
  202. var typeStyle = Style.TableStyle.GetOrCreateColumnStyle (3);
  203. typeStyle.MinWidth = 6;
  204. typeStyle.ColorGetter = this.ColorGetter;
  205. this.tableView.KeyPress += (s, k) => {
  206. if (this.tableView.SelectedRow <= 0) {
  207. this.NavigateIf (k, Key.CursorUp, this.tbPath);
  208. }
  209. if (this.tableView.SelectedRow == this.tableView.Table.Rows - 1) {
  210. this.NavigateIf (k, Key.CursorDown, this.btnToggleSplitterCollapse);
  211. }
  212. if (splitContainer.Tiles.First ().ContentView.Visible && tableView.SelectedColumn == 0) {
  213. this.NavigateIf (k, Key.CursorLeft, this.treeView);
  214. }
  215. if (k.Handled) {
  216. return;
  217. }
  218. };
  219. this.treeView = new TreeView<IFileSystemInfo> () {
  220. Width = Dim.Fill (),
  221. Height = Dim.Fill (),
  222. };
  223. var fileDialogTreeBuilder = new FileSystemTreeBuilder ();
  224. this.treeView.TreeBuilder = fileDialogTreeBuilder;
  225. this.treeView.AspectGetter = this.AspectGetter;
  226. this.Style.TreeStyle = treeView.Style;
  227. this.treeView.SelectionChanged += this.TreeView_SelectionChanged;
  228. this.splitContainer.Tiles.ElementAt (0).ContentView.Add (this.treeView);
  229. this.splitContainer.Tiles.ElementAt (1).ContentView.Add (this.tableView);
  230. this.btnToggleSplitterCollapse = new Button (GetToggleSplitterText (false)) {
  231. Y = Pos.AnchorEnd (1),
  232. };
  233. this.btnToggleSplitterCollapse.Clicked += (s, e) => {
  234. var tile = this.splitContainer.Tiles.ElementAt (0);
  235. var newState = !tile.ContentView.Visible;
  236. tile.ContentView.Visible = newState;
  237. this.btnToggleSplitterCollapse.Text = GetToggleSplitterText (newState);
  238. this.LayoutSubviews ();
  239. };
  240. tbFind = new TextField {
  241. X = Pos.Right (this.btnToggleSplitterCollapse) + 1,
  242. Caption = Style.SearchCaption,
  243. CaptionColor = Color.Black,
  244. Width = 30,
  245. Y = Pos.AnchorEnd (1),
  246. };
  247. spinnerView = new SpinnerView () {
  248. X = Pos.Right (tbFind) + 1,
  249. Y = Pos.AnchorEnd (1),
  250. Visible = false,
  251. };
  252. tbFind.TextChanged += (s, o) => RestartSearch ();
  253. tbFind.KeyPress += (s, o) => {
  254. if (o.KeyEvent.Key == Key.Enter) {
  255. RestartSearch ();
  256. o.Handled = true;
  257. }
  258. if (o.KeyEvent.Key == Key.Esc) {
  259. if (CancelSearch ()) {
  260. o.Handled = true;
  261. }
  262. }
  263. if (tbFind.CursorIsAtEnd ()) {
  264. NavigateIf (o, Key.CursorRight, btnCancel);
  265. }
  266. if (tbFind.CursorIsAtStart ()) {
  267. NavigateIf (o, Key.CursorLeft, btnToggleSplitterCollapse);
  268. }
  269. };
  270. this.tableView.Style.ShowHorizontalHeaderOverline = true;
  271. this.tableView.Style.ShowVerticalCellLines = true;
  272. this.tableView.Style.ShowVerticalHeaderLines = true;
  273. this.tableView.Style.AlwaysShowHeaders = true;
  274. this.tableView.Style.ShowHorizontalHeaderUnderline = true;
  275. this.tableView.Style.ShowHorizontalScrollIndicators = true;
  276. this.history = new FileDialogHistory (this);
  277. this.tbPath.TextChanged += (s, e) => this.PathChanged ();
  278. this.tableView.CellActivated += this.CellActivate;
  279. this.tableView.KeyUp += (s, k) => k.Handled = this.TableView_KeyUp (k.KeyEvent);
  280. this.tableView.SelectedCellChanged += this.TableView_SelectedCellChanged;
  281. this.tableView.AddKeyBinding (Key.Home, Command.TopHome);
  282. this.tableView.AddKeyBinding (Key.End, Command.BottomEnd);
  283. this.tableView.AddKeyBinding (Key.Home | Key.ShiftMask, Command.TopHomeExtend);
  284. this.tableView.AddKeyBinding (Key.End | Key.ShiftMask, Command.BottomEndExtend);
  285. this.treeView.KeyDown += (s, k) => {
  286. var selected = treeView.SelectedObject;
  287. if (selected != null) {
  288. if (!treeView.CanExpand (selected) || treeView.IsExpanded (selected)) {
  289. this.NavigateIf (k, Key.CursorRight, this.tableView);
  290. } else
  291. if (treeView.GetObjectRow (selected) == 0) {
  292. this.NavigateIf (k, Key.CursorUp, this.tbPath);
  293. }
  294. }
  295. if (k.Handled) {
  296. return;
  297. }
  298. k.Handled = this.TreeView_KeyDown (k.KeyEvent);
  299. };
  300. this.AllowsMultipleSelection = false;
  301. this.UpdateNavigationVisibility ();
  302. // Determines tab order
  303. this.Add (this.btnToggleSplitterCollapse);
  304. this.Add (this.tbFind);
  305. this.Add (this.spinnerView);
  306. this.Add (this.btnOk);
  307. this.Add (this.btnCancel);
  308. this.Add (this.btnUp);
  309. this.Add (this.btnBack);
  310. this.Add (this.btnForward);
  311. this.Add (this.tbPath);
  312. this.Add (this.splitContainer);
  313. }
  314. private string AspectGetter (object o)
  315. {
  316. var fsi = (IFileSystemInfo)o;
  317. if(o is IDirectoryInfo dir && _treeRoots.ContainsKey(dir)) {
  318. // Directory has a special name e.g. 'Pictures'
  319. return _treeRoots [dir];
  320. }
  321. return (Style.IconProvider.GetIconWithOptionalSpace(fsi) + fsi.Name).Trim();
  322. }
  323. private void OnTableViewMouseClick (object sender, MouseEventEventArgs e)
  324. {
  325. var clickedCell = this.tableView.ScreenToCell (e.MouseEvent.X, e.MouseEvent.Y, out int? clickedCol);
  326. if (clickedCol != null) {
  327. if (e.MouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  328. // left click in a header
  329. this.SortColumn (clickedCol.Value);
  330. } else if (e.MouseEvent.Flags.HasFlag (MouseFlags.Button3Clicked)) {
  331. // right click in a header
  332. this.ShowHeaderContextMenu (clickedCol.Value, e);
  333. }
  334. } else {
  335. if (clickedCell != null && e.MouseEvent.Flags.HasFlag (MouseFlags.Button3Clicked)) {
  336. // right click in rest of table
  337. this.ShowCellContextMenu (clickedCell, e);
  338. }
  339. }
  340. }
  341. private string GetForwardButtonText ()
  342. {
  343. return "-" + CM.Glyphs.RightArrow;
  344. }
  345. private string GetBackButtonText ()
  346. {
  347. return CM.Glyphs.LeftArrow + "-";
  348. }
  349. private string GetUpButtonText ()
  350. {
  351. return Style.UseUnicodeCharacters ? "◭" : "▲";
  352. }
  353. private string GetToggleSplitterText (bool isExpanded)
  354. {
  355. return isExpanded ?
  356. new string ((char)CM.Glyphs.LeftArrow.Value, 2) :
  357. new string ((char)CM.Glyphs.RightArrow.Value, 2);
  358. }
  359. private void Delete ()
  360. {
  361. var toDelete = GetFocusedFiles ();
  362. if (toDelete != null && FileOperationsHandler.Delete (toDelete)) {
  363. RefreshState ();
  364. }
  365. }
  366. private void Rename ()
  367. {
  368. var toRename = GetFocusedFiles ();
  369. if (toRename?.Length == 1) {
  370. var newNamed = FileOperationsHandler.Rename (this.fileSystem, toRename.Single ());
  371. if (newNamed != null) {
  372. RefreshState ();
  373. RestoreSelection (newNamed);
  374. }
  375. }
  376. }
  377. private void New ()
  378. {
  379. if (State != null) {
  380. var created = FileOperationsHandler.New (this.fileSystem, State.Directory);
  381. if (created != null) {
  382. RefreshState ();
  383. RestoreSelection (created);
  384. }
  385. }
  386. }
  387. private IFileSystemInfo [] GetFocusedFiles ()
  388. {
  389. if (!tableView.HasFocus || !tableView.CanFocus || FileOperationsHandler == null) {
  390. return null;
  391. }
  392. tableView.EnsureValidSelection ();
  393. if (tableView.SelectedRow < 0) {
  394. return null;
  395. }
  396. return tableView.GetAllSelectedCells ()
  397. .Select (c => c.Y)
  398. .Distinct ()
  399. .Select (RowToStats)
  400. .Where (s => !s.IsParent)
  401. .Select (d => d.FileSystemInfo)
  402. .ToArray ();
  403. }
  404. /// <inheritdoc/>
  405. public override bool ProcessHotKey (KeyEvent keyEvent)
  406. {
  407. if (this.NavigateIf (keyEvent, Key.CtrlMask | Key.F, this.tbFind)) {
  408. return true;
  409. }
  410. ClearFeedback ();
  411. if (allowedTypeMenuBar != null &&
  412. keyEvent.Key == Key.Tab &&
  413. allowedTypeMenuBar.IsMenuOpen) {
  414. allowedTypeMenuBar.CloseMenu (false, false, false);
  415. }
  416. return base.ProcessHotKey (keyEvent);
  417. }
  418. private void RestartSearch ()
  419. {
  420. if (disposed || State?.Directory == null) {
  421. return;
  422. }
  423. if (State is SearchState oldSearch) {
  424. oldSearch.Cancel ();
  425. }
  426. // user is clearing search terms
  427. if (tbFind.Text == null || tbFind.Text.Length == 0) {
  428. // Wait for search cancellation (if any) to finish
  429. // then push the current dir state
  430. lock (onlyOneSearchLock) {
  431. PushState (new FileDialogState (State.Directory, this), false);
  432. }
  433. return;
  434. }
  435. PushState (new SearchState (State?.Directory, this, tbFind.Text), true);
  436. }
  437. /// <inheritdoc/>
  438. protected override void Dispose (bool disposing)
  439. {
  440. disposed = true;
  441. base.Dispose (disposing);
  442. CancelSearch ();
  443. }
  444. private bool CancelSearch ()
  445. {
  446. if (State is SearchState search) {
  447. return search.Cancel ();
  448. }
  449. return false;
  450. }
  451. private void ClearFeedback ()
  452. {
  453. feedback = null;
  454. }
  455. /// <summary>
  456. /// Gets or Sets which <see cref="System.IO.FileSystemInfo"/> type can be selected.
  457. /// Defaults to <see cref="OpenMode.Mixed"/> (i.e. <see cref="DirectoryInfo"/> or
  458. /// <see cref="FileInfo"/>).
  459. /// </summary>
  460. public OpenMode OpenMode { get; set; } = OpenMode.Mixed;
  461. /// <summary>
  462. /// Gets or Sets the selected path in the dialog. This is the result that should
  463. /// be used if <see cref="AllowsMultipleSelection"/> is off and <see cref="Canceled"/>
  464. /// is true.
  465. /// </summary>
  466. public string Path {
  467. get => this.tbPath.Text;
  468. set {
  469. this.tbPath.Text = value;
  470. this.tbPath.MoveEnd ();
  471. }
  472. }
  473. /// <summary>
  474. /// Defines how the dialog matches files/folders when using the search
  475. /// box. Provide a custom implementation if you want to tailor how matching
  476. /// is performed.
  477. /// </summary>
  478. public ISearchMatcher SearchMatcher { get; set; } = new DefaultSearchMatcher ();
  479. /// <summary>
  480. /// Gets or Sets a value indicating whether to allow selecting
  481. /// multiple existing files/directories. Defaults to false.
  482. /// </summary>
  483. public bool AllowsMultipleSelection {
  484. get => this.tableView.MultiSelect;
  485. set => this.tableView.MultiSelect = value;
  486. }
  487. /// <summary>
  488. /// Gets or Sets a collection of file types that the user can/must select. Only applies
  489. /// when <see cref="OpenMode"/> is <see cref="OpenMode.File"/> or <see cref="OpenMode.Mixed"/>.
  490. /// </summary>
  491. /// <remarks><see cref="AllowedTypeAny"/> adds the option to select any type (*.*). If this
  492. /// collection is empty then any type is supported and no Types drop-down is shown.</remarks>
  493. public List<IAllowedType> AllowedTypes { get; set; } = new List<IAllowedType> ();
  494. /// <summary>
  495. /// Gets a value indicating whether the <see cref="FileDialog"/> was closed
  496. /// without confirming a selection.
  497. /// </summary>
  498. public bool Canceled { get; private set; } = true;
  499. /// <summary>
  500. /// Gets all files/directories selected or an empty collection
  501. /// <see cref="AllowsMultipleSelection"/> is <see langword="false"/> or <see cref="Canceled"/>.
  502. /// </summary>
  503. /// <remarks>If selecting only a single file/directory then you should use <see cref="Path"/> instead.</remarks>
  504. public IReadOnlyList<string> MultiSelected { get; private set; }
  505. = Enumerable.Empty<string> ().ToList ().AsReadOnly ();
  506. /// <inheritdoc/>
  507. public override void OnDrawContent (Rect contentArea)
  508. {
  509. base.OnDrawContent (contentArea);
  510. if (!string.IsNullOrWhiteSpace (feedback)) {
  511. var feedbackWidth = feedback.EnumerateRunes ().Sum (c => c.GetColumns ());
  512. var feedbackPadLeft = ((Bounds.Width - feedbackWidth) / 2) - 1;
  513. feedbackPadLeft = Math.Min (Bounds.Width, feedbackPadLeft);
  514. feedbackPadLeft = Math.Max (0, feedbackPadLeft);
  515. var feedbackPadRight = Bounds.Width - (feedbackPadLeft + feedbackWidth + 2);
  516. feedbackPadRight = Math.Min (Bounds.Width, feedbackPadRight);
  517. feedbackPadRight = Math.Max (0, feedbackPadRight);
  518. Move (0, Bounds.Height / 2);
  519. Driver.SetAttribute (new Attribute (Color.Red, this.ColorScheme.Normal.Background));
  520. Driver.AddStr (new string (' ', feedbackPadLeft));
  521. Driver.AddStr (feedback);
  522. Driver.AddStr (new string (' ', feedbackPadRight));
  523. }
  524. }
  525. /// <inheritdoc/>
  526. public override void OnLoaded ()
  527. {
  528. base.OnLoaded ();
  529. if (loaded) {
  530. return;
  531. }
  532. loaded = true;
  533. // May have been updated after instance was constructed
  534. this.btnOk.Text = Style.OkButtonText;
  535. this.btnUp.Text = this.GetUpButtonText ();
  536. this.btnBack.Text = this.GetBackButtonText ();
  537. this.btnForward.Text = this.GetForwardButtonText ();
  538. this.btnToggleSplitterCollapse.Text = this.GetToggleSplitterText (false);
  539. tbPath.Autocomplete.ColorScheme.Normal = Attribute.Make (Color.Black, tbPath.ColorScheme.Normal.Background);
  540. _treeRoots = Style.TreeRootGetter ();
  541. Style.IconProvider.IsOpenGetter = treeView.IsExpanded;
  542. treeView.AddObjects (_treeRoots.Keys);
  543. // if filtering on file type is configured then create the ComboBox and establish
  544. // initial filtering by extension(s)
  545. if (this.AllowedTypes.Any ()) {
  546. this.CurrentFilter = this.AllowedTypes [0];
  547. // Fiddle factor
  548. var width = this.AllowedTypes.Max (a => a.ToString ().Length) + 6;
  549. allowedTypeMenu = new MenuBarItem ("<placeholder>",
  550. allowedTypeMenuItems = AllowedTypes.Select (
  551. (a, i) => new MenuItem (a.ToString (), null, () => {
  552. AllowedTypeMenuClicked (i);
  553. }))
  554. .ToArray ());
  555. allowedTypeMenuBar = new MenuBar (new [] { allowedTypeMenu }) {
  556. Width = width,
  557. Y = 1,
  558. X = Pos.AnchorEnd (width),
  559. // TODO: Does not work, if this worked then we could tab to it instead
  560. // of having to hit F9
  561. CanFocus = true,
  562. TabStop = true
  563. };
  564. AllowedTypeMenuClicked (0);
  565. allowedTypeMenuBar.Enter += (s, e) => {
  566. allowedTypeMenuBar.OpenMenu (0);
  567. };
  568. allowedTypeMenuBar.DrawContentComplete += (s, e) => {
  569. allowedTypeMenuBar.Move (e.Rect.Width - 1, 0);
  570. Driver.AddRune (CM.Glyphs.DownArrow);
  571. };
  572. this.Add (allowedTypeMenuBar);
  573. }
  574. // if no path has been provided
  575. if (this.tbPath.Text.Length <= 0) {
  576. this.tbPath.Text = Environment.CurrentDirectory;
  577. }
  578. // to streamline user experience and allow direct typing of paths
  579. // with zero navigation we start with focus in the text box and any
  580. // default/current path fully selected and ready to be overwritten
  581. this.tbPath.FocusFirst ();
  582. this.tbPath.SelectAll ();
  583. if (string.IsNullOrEmpty (Title)) {
  584. switch (OpenMode) {
  585. case OpenMode.File:
  586. this.Title = $"{Strings.fdOpen} {(MustExist ? Strings.fdExisting + " " : "")}{Strings.fdFile}";
  587. break;
  588. case OpenMode.Directory:
  589. this.Title = $"{Strings.fdOpen} {(MustExist ? Strings.fdExisting + " " : "")}{Strings.fdDirectory}";
  590. break;
  591. case OpenMode.Mixed:
  592. this.Title = $"{Strings.fdOpen} {(MustExist ? Strings.fdExisting : "")}";
  593. break;
  594. }
  595. }
  596. this.LayoutSubviews ();
  597. }
  598. private void AllowedTypeMenuClicked (int idx)
  599. {
  600. var allow = AllowedTypes [idx];
  601. for (int i = 0; i < AllowedTypes.Count; i++) {
  602. allowedTypeMenuItems [i].Checked = i == idx;
  603. }
  604. allowedTypeMenu.Title = allow.ToString ();
  605. this.CurrentFilter = allow;
  606. this.tbPath.ClearAllSelection ();
  607. this.tbPath.Autocomplete.ClearSuggestions ();
  608. if (this.State != null) {
  609. this.State.RefreshChildren ();
  610. this.WriteStateToTableView ();
  611. }
  612. }
  613. private void SuppressIfBadChar (KeyEventEventArgs k)
  614. {
  615. // don't let user type bad letters
  616. var ch = (char)k.KeyEvent.KeyValue;
  617. if (badChars.Contains (ch)) {
  618. k.Handled = true;
  619. }
  620. }
  621. private bool TreeView_KeyDown (KeyEvent keyEvent)
  622. {
  623. if (this.treeView.HasFocus && Separators.Contains ((char)keyEvent.KeyValue)) {
  624. this.tbPath.FocusFirst ();
  625. // let that keystroke go through on the tbPath instead
  626. return true;
  627. }
  628. return false;
  629. }
  630. private void AcceptIf (KeyEventEventArgs keyEvent, Key isKey)
  631. {
  632. if (!keyEvent.Handled && keyEvent.KeyEvent.Key == isKey) {
  633. keyEvent.Handled = true;
  634. // User hit Enter in text box so probably wants the
  635. // contents of the text box as their selection not
  636. // whatever lingering selection is in TableView
  637. this.Accept (false);
  638. }
  639. }
  640. private void Accept (IEnumerable<FileSystemInfoStats> toMultiAccept)
  641. {
  642. if (!this.AllowsMultipleSelection) {
  643. return;
  644. }
  645. // Don't include ".." (IsParent) in multiselections
  646. this.MultiSelected = toMultiAccept
  647. .Where (s => !s.IsParent)
  648. .Select (s => s.FileSystemInfo.FullName)
  649. .ToList ().AsReadOnly ();
  650. this.tbPath.Text = this.MultiSelected.Count == 1 ? this.MultiSelected [0] : string.Empty;
  651. FinishAccept ();
  652. }
  653. private void Accept (IFileInfo f)
  654. {
  655. if (!this.IsCompatibleWithOpenMode (f.FullName, out var reason)) {
  656. feedback = reason;
  657. SetNeedsDisplay ();
  658. return;
  659. }
  660. this.tbPath.Text = f.FullName;
  661. if (AllowsMultipleSelection) {
  662. this.MultiSelected = new List<string> { f.FullName }.AsReadOnly ();
  663. }
  664. FinishAccept ();
  665. }
  666. private void Accept (bool allowMulti)
  667. {
  668. if (allowMulti && TryAcceptMulti ()) {
  669. return;
  670. }
  671. if (!this.IsCompatibleWithOpenMode (this.tbPath.Text, out string reason)) {
  672. if (reason != null) {
  673. feedback = reason;
  674. SetNeedsDisplay ();
  675. }
  676. return;
  677. }
  678. FinishAccept ();
  679. }
  680. private void FinishAccept ()
  681. {
  682. var e = new FilesSelectedEventArgs (this);
  683. this.FilesSelected?.Invoke (this, e);
  684. if (e.Cancel) {
  685. return;
  686. }
  687. // if user uses Path selection mode (e.g. Enter in text box)
  688. // then also copy to MultiSelected
  689. if (AllowsMultipleSelection && (!MultiSelected.Any ())) {
  690. MultiSelected = string.IsNullOrWhiteSpace (Path) ?
  691. Enumerable.Empty<string> ().ToList ().AsReadOnly () :
  692. new List<string> () { Path }.AsReadOnly ();
  693. }
  694. this.Canceled = false;
  695. Application.RequestStop ();
  696. }
  697. private void NavigateIf (KeyEventEventArgs keyEvent, Key isKey, View to)
  698. {
  699. if (!keyEvent.Handled) {
  700. if (NavigateIf (keyEvent.KeyEvent, isKey, to)) {
  701. keyEvent.Handled = true;
  702. }
  703. }
  704. }
  705. private bool NavigateIf (KeyEvent keyEvent, Key isKey, View to)
  706. {
  707. if (keyEvent.Key == isKey) {
  708. to.FocusFirst ();
  709. if (to == tbPath) {
  710. tbPath.MoveEnd ();
  711. }
  712. return true;
  713. }
  714. return false;
  715. }
  716. private void TreeView_SelectionChanged (object sender, SelectionChangedEventArgs<IFileSystemInfo> e)
  717. {
  718. if (e.NewValue == null) {
  719. return;
  720. }
  721. this.tbPath.Text = e.NewValue.FullName;
  722. }
  723. private void UpdateNavigationVisibility ()
  724. {
  725. this.btnBack.Visible = this.history.CanBack ();
  726. this.btnForward.Visible = this.history.CanForward ();
  727. this.btnUp.Visible = this.history.CanUp ();
  728. }
  729. private void TableView_SelectedCellChanged (object sender, SelectedCellChangedEventArgs obj)
  730. {
  731. if (!this.tableView.HasFocus || obj.NewRow == -1 || obj.Table.Rows == 0) {
  732. return;
  733. }
  734. if (this.tableView.MultiSelect && this.tableView.MultiSelectedRegions.Any ()) {
  735. return;
  736. }
  737. var stats = this.RowToStats (obj.NewRow);
  738. if (stats == null) {
  739. return;
  740. }
  741. IFileSystemInfo dest;
  742. if (stats.IsParent) {
  743. dest = State.Directory;
  744. } else {
  745. dest = stats.FileSystemInfo;
  746. }
  747. try {
  748. this.pushingState = true;
  749. this.tbPath.Text = dest.FullName;
  750. this.State.Selected = stats;
  751. this.tbPath.Autocomplete.ClearSuggestions ();
  752. } finally {
  753. this.pushingState = false;
  754. }
  755. }
  756. private bool TableView_KeyUp (KeyEvent keyEvent)
  757. {
  758. if (keyEvent.Key == Key.Backspace) {
  759. return this.history.Back ();
  760. }
  761. if (keyEvent.Key == (Key.ShiftMask | Key.Backspace)) {
  762. return this.history.Forward ();
  763. }
  764. if (keyEvent.Key == Key.DeleteChar) {
  765. Delete ();
  766. return true;
  767. }
  768. if (keyEvent.Key == (Key.CtrlMask | Key.R)) {
  769. Rename ();
  770. return true;
  771. }
  772. if (keyEvent.Key == (Key.CtrlMask | Key.N)) {
  773. New ();
  774. return true;
  775. }
  776. return false;
  777. }
  778. private void CellActivate (object sender, CellActivatedEventArgs obj)
  779. {
  780. if (TryAcceptMulti ()) {
  781. return;
  782. }
  783. var stats = this.RowToStats (obj.Row);
  784. if (stats.FileSystemInfo is IDirectoryInfo d) {
  785. this.PushState (d, true);
  786. return;
  787. }
  788. if (stats.FileSystemInfo is IFileInfo f) {
  789. this.Accept (f);
  790. }
  791. }
  792. private bool TryAcceptMulti ()
  793. {
  794. var multi = this.MultiRowToStats ();
  795. string reason = null;
  796. if (!multi.Any ()) {
  797. return false;
  798. }
  799. if (multi.All (m => this.IsCompatibleWithOpenMode (
  800. m.FileSystemInfo.FullName, out reason))) {
  801. this.Accept (multi);
  802. return true;
  803. } else {
  804. if (reason != null) {
  805. feedback = reason;
  806. SetNeedsDisplay ();
  807. }
  808. return false;
  809. }
  810. }
  811. /// <summary>
  812. /// Returns true if there are no <see cref="AllowedTypes"/> or one of them agrees
  813. /// that <paramref name="file"/> <see cref="IAllowedType.IsAllowed(string)"/>.
  814. /// </summary>
  815. /// <param name="file"></param>
  816. /// <returns></returns>
  817. public bool IsCompatibleWithAllowedExtensions (IFileInfo file)
  818. {
  819. // no restrictions
  820. if (!this.AllowedTypes.Any ()) {
  821. return true;
  822. }
  823. return this.MatchesAllowedTypes (file);
  824. }
  825. private bool IsCompatibleWithAllowedExtensions (string path)
  826. {
  827. // no restrictions
  828. if (!this.AllowedTypes.Any ()) {
  829. return true;
  830. }
  831. return this.AllowedTypes.Any (t => t.IsAllowed (path));
  832. }
  833. /// <summary>
  834. /// Returns true if any <see cref="AllowedTypes"/> matches <paramref name="file"/>.
  835. /// </summary>
  836. /// <param name="file"></param>
  837. /// <returns></returns>
  838. private bool MatchesAllowedTypes (IFileInfo file)
  839. {
  840. return this.AllowedTypes.Any (t => t.IsAllowed (file.FullName));
  841. }
  842. private bool IsCompatibleWithOpenMode (string s, out string reason)
  843. {
  844. reason = null;
  845. if (string.IsNullOrWhiteSpace (s)) {
  846. return false;
  847. }
  848. if (!this.IsCompatibleWithAllowedExtensions (s)) {
  849. reason = Style.WrongFileTypeFeedback;
  850. return false;
  851. }
  852. switch (this.OpenMode) {
  853. case OpenMode.Directory:
  854. if (MustExist && !Directory.Exists (s)) {
  855. reason = Style.DirectoryMustExistFeedback;
  856. return false;
  857. }
  858. if (File.Exists (s)) {
  859. reason = Style.FileAlreadyExistsFeedback;
  860. return false;
  861. }
  862. return true;
  863. case OpenMode.File:
  864. if (MustExist && !File.Exists (s)) {
  865. reason = Style.FileMustExistFeedback;
  866. return false;
  867. }
  868. if (Directory.Exists (s)) {
  869. reason = Style.DirectoryAlreadyExistsFeedback;
  870. return false;
  871. }
  872. return true;
  873. case OpenMode.Mixed:
  874. if (MustExist && !File.Exists (s) && !Directory.Exists (s)) {
  875. reason = Style.FileOrDirectoryMustExistFeedback;
  876. return false;
  877. }
  878. return true;
  879. default: throw new ArgumentOutOfRangeException (nameof (this.OpenMode));
  880. }
  881. }
  882. /// <summary>
  883. /// Changes the dialog such that <paramref name="d"/> is being explored.
  884. /// </summary>
  885. /// <param name="d"></param>
  886. /// <param name="addCurrentStateToHistory"></param>
  887. /// <param name="setPathText"></param>
  888. /// <param name="clearForward"></param>
  889. /// <param name="pathText">Optional alternate string to set path to.</param>
  890. internal void PushState (IDirectoryInfo d, bool addCurrentStateToHistory, bool setPathText = true, bool clearForward = true, string pathText = null)
  891. {
  892. // no change of state
  893. if (d == this.State?.Directory) {
  894. return;
  895. }
  896. if (d.FullName == this.State?.Directory.FullName) {
  897. return;
  898. }
  899. PushState (new FileDialogState (d, this), addCurrentStateToHistory, setPathText, clearForward, pathText);
  900. }
  901. private void RefreshState ()
  902. {
  903. State.RefreshChildren ();
  904. PushState (State, false, false, false);
  905. }
  906. private void PushState (FileDialogState newState, bool addCurrentStateToHistory, bool setPathText = true, bool clearForward = true, string pathText = null)
  907. {
  908. if (State is SearchState search) {
  909. search.Cancel ();
  910. }
  911. try {
  912. this.pushingState = true;
  913. // push the old state to history
  914. if (addCurrentStateToHistory) {
  915. this.history.Push (this.State, clearForward);
  916. }
  917. this.tbPath.Autocomplete.ClearSuggestions ();
  918. if (pathText != null) {
  919. this.tbPath.Text = pathText;
  920. this.tbPath.MoveEnd ();
  921. } else
  922. if (setPathText) {
  923. this.tbPath.Text = newState.Directory.FullName;
  924. this.tbPath.MoveEnd ();
  925. }
  926. this.State = newState;
  927. this.tbPath.Autocomplete.GenerateSuggestions (
  928. new AutocompleteFilepathContext (tbPath.Text, tbPath.CursorPosition, this.State));
  929. this.WriteStateToTableView ();
  930. if (clearForward) {
  931. this.history.ClearForward ();
  932. }
  933. this.tableView.RowOffset = 0;
  934. this.tableView.SelectedRow = 0;
  935. this.SetNeedsDisplay ();
  936. this.UpdateNavigationVisibility ();
  937. } finally {
  938. this.pushingState = false;
  939. }
  940. ClearFeedback ();
  941. }
  942. private void WriteStateToTableView ()
  943. {
  944. if (this.State == null) {
  945. return;
  946. }
  947. this.tableView.Table = new FileDialogTableSource (this, this.State, this.Style, currentSortColumn, currentSortIsAsc);
  948. this.ApplySort ();
  949. this.tableView.Update ();
  950. }
  951. private ColorScheme ColorGetter (CellColorGetterArgs args)
  952. {
  953. var stats = this.RowToStats (args.RowIndex);
  954. if (!Style.UseColors) {
  955. return tableView.ColorScheme;
  956. }
  957. var color = Style.ColorProvider.GetTrueColor(stats.FileSystemInfo)
  958. ?? TrueColor.FromConsoleColor(Color.White);
  959. var black = TrueColor.FromConsoleColor(Color.Black);
  960. // TODO: Add some kind of cache for this
  961. return new ColorScheme{
  962. Normal = new Attribute (color,black),
  963. HotNormal = new Attribute (color, black),
  964. Focus = new Attribute (black, color),
  965. HotFocus = new Attribute (black, color),
  966. };
  967. }
  968. /// <summary>
  969. /// If <see cref="TableView.MultiSelect"/> is this returns a union of all
  970. /// <see cref="FileSystemInfoStats"/> in the selection.
  971. /// </summary>
  972. /// <returns></returns>
  973. private IEnumerable<FileSystemInfoStats> MultiRowToStats ()
  974. {
  975. var toReturn = new HashSet<FileSystemInfoStats> ();
  976. if (this.AllowsMultipleSelection && this.tableView.MultiSelectedRegions.Any ()) {
  977. foreach (var p in this.tableView.GetAllSelectedCells ()) {
  978. var add = this.State?.Children [p.Y];
  979. if (add != null) {
  980. toReturn.Add (add);
  981. }
  982. }
  983. }
  984. return toReturn;
  985. }
  986. private FileSystemInfoStats RowToStats (int rowIndex)
  987. {
  988. return this.State?.Children [rowIndex];
  989. }
  990. private void PathChanged ()
  991. {
  992. // avoid re-entry
  993. if (this.pushingState) {
  994. return;
  995. }
  996. var path = this.tbPath.Text;
  997. if (string.IsNullOrWhiteSpace (path)) {
  998. return;
  999. }
  1000. var dir = this.StringToDirectoryInfo (path);
  1001. if (dir.Exists) {
  1002. this.PushState (dir, true, false);
  1003. } else
  1004. if (dir.Parent?.Exists ?? false) {
  1005. this.PushState (dir.Parent, true, false);
  1006. }
  1007. tbPath.Autocomplete.GenerateSuggestions (new AutocompleteFilepathContext (tbPath.Text, tbPath.CursorPosition, State));
  1008. }
  1009. private IDirectoryInfo StringToDirectoryInfo (string path)
  1010. {
  1011. // if you pass new DirectoryInfo("C:") you get a weird object
  1012. // where the FullName is in fact the current working directory.
  1013. // really not what most users would expect
  1014. if (Regex.IsMatch (path, "^\\w:$")) {
  1015. return fileSystem.DirectoryInfo.New (path + System.IO.Path.DirectorySeparatorChar);
  1016. }
  1017. return fileSystem.DirectoryInfo.New (path);
  1018. }
  1019. /// <summary>
  1020. /// Select <paramref name="toRestore"/> in the table view (if present)
  1021. /// </summary>
  1022. /// <param name="toRestore"></param>
  1023. internal void RestoreSelection (IFileSystemInfo toRestore)
  1024. {
  1025. tableView.SelectedRow = State.Children.IndexOf (r => r.FileSystemInfo == toRestore);
  1026. tableView.EnsureSelectedCellIsVisible ();
  1027. }
  1028. internal void ApplySort ()
  1029. {
  1030. var stats = State?.Children ?? new FileSystemInfoStats [0];
  1031. // This portion is never reordered (aways .. at top then folders)
  1032. var forcedOrder = stats
  1033. .OrderByDescending (f => f.IsParent)
  1034. .ThenBy (f => f.IsDir () ? -1 : 100);
  1035. // This portion is flexible based on the column clicked (e.g. alphabetical)
  1036. var ordered =
  1037. this.currentSortIsAsc ?
  1038. forcedOrder.ThenBy (f => FileDialogTableSource.GetRawColumnValue (currentSortColumn, f)) :
  1039. forcedOrder.ThenByDescending (f => FileDialogTableSource.GetRawColumnValue (currentSortColumn, f));
  1040. State.Children = ordered.ToArray ();
  1041. this.tableView.Update ();
  1042. }
  1043. private void SortColumn (int clickedCol)
  1044. {
  1045. this.GetProposedNewSortOrder (clickedCol, out var isAsc);
  1046. this.SortColumn (clickedCol, isAsc);
  1047. this.tableView.Table = new FileDialogTableSource (this, State, Style, currentSortColumn, currentSortIsAsc);
  1048. }
  1049. internal void SortColumn (int col, bool isAsc)
  1050. {
  1051. // set a sort order
  1052. this.currentSortColumn = col;
  1053. this.currentSortIsAsc = isAsc;
  1054. this.ApplySort ();
  1055. }
  1056. private string GetProposedNewSortOrder (int clickedCol, out bool isAsc)
  1057. {
  1058. // work out new sort order
  1059. if (this.currentSortColumn == clickedCol && this.currentSortIsAsc) {
  1060. isAsc = false;
  1061. return $"{tableView.Table.ColumnNames [clickedCol]} DESC";
  1062. } else {
  1063. isAsc = true;
  1064. return $"{tableView.Table.ColumnNames [clickedCol]} ASC";
  1065. }
  1066. }
  1067. private void ShowHeaderContextMenu (int clickedCol, MouseEventEventArgs e)
  1068. {
  1069. var sort = this.GetProposedNewSortOrder (clickedCol, out var isAsc);
  1070. var contextMenu = new ContextMenu (
  1071. e.MouseEvent.X + 1,
  1072. e.MouseEvent.Y + 1,
  1073. new MenuBarItem (new MenuItem []
  1074. {
  1075. new MenuItem($"Hide {StripArrows(tableView.Table.ColumnNames[clickedCol])}", string.Empty, () => this.HideColumn(clickedCol)),
  1076. new MenuItem($"Sort {StripArrows(sort)}",string.Empty, ()=> this.SortColumn(clickedCol,isAsc)),
  1077. })
  1078. );
  1079. contextMenu.Show ();
  1080. }
  1081. private static string StripArrows (string columnName)
  1082. {
  1083. return columnName.Replace (" (▼)", string.Empty).Replace (" (▲)", string.Empty);
  1084. }
  1085. private void ShowCellContextMenu (Point? clickedCell, MouseEventEventArgs e)
  1086. {
  1087. if (clickedCell == null) {
  1088. return;
  1089. }
  1090. var contextMenu = new ContextMenu (
  1091. e.MouseEvent.X + 1,
  1092. e.MouseEvent.Y + 1,
  1093. new MenuBarItem (new MenuItem []
  1094. {
  1095. new MenuItem($"New", string.Empty, () => New()),
  1096. new MenuItem($"Rename",string.Empty, ()=> Rename()),
  1097. new MenuItem($"Delete",string.Empty, ()=> Delete()),
  1098. })
  1099. );
  1100. tableView.SetSelection (clickedCell.Value.X, clickedCell.Value.Y, false);
  1101. contextMenu.Show ();
  1102. }
  1103. private void HideColumn (int clickedCol)
  1104. {
  1105. var style = this.tableView.Style.GetOrCreateColumnStyle (clickedCol);
  1106. style.Visible = false;
  1107. this.tableView.Update ();
  1108. }
  1109. /// <summary>
  1110. /// State representing a recursive search from <see cref="FileDialogState.Directory"/>
  1111. /// downwards.
  1112. /// </summary>
  1113. internal class SearchState : FileDialogState {
  1114. bool cancel = false;
  1115. bool finished = false;
  1116. // TODO: Add thread safe child adding
  1117. List<FileSystemInfoStats> found = new List<FileSystemInfoStats> ();
  1118. object oLockFound = new object ();
  1119. CancellationTokenSource token = new CancellationTokenSource ();
  1120. public SearchState (IDirectoryInfo dir, FileDialog parent, string searchTerms) : base (dir, parent)
  1121. {
  1122. parent.SearchMatcher.Initialize (searchTerms);
  1123. Children = new FileSystemInfoStats [0];
  1124. BeginSearch ();
  1125. }
  1126. private void BeginSearch ()
  1127. {
  1128. Task.Run (() => {
  1129. RecursiveFind (Directory);
  1130. finished = true;
  1131. });
  1132. Task.Run (() => {
  1133. UpdateChildren ();
  1134. });
  1135. }
  1136. private void UpdateChildren ()
  1137. {
  1138. lock (Parent.onlyOneSearchLock) {
  1139. while (!cancel && !finished) {
  1140. try {
  1141. Task.Delay (250).Wait (token.Token);
  1142. } catch (OperationCanceledException) {
  1143. cancel = true;
  1144. }
  1145. if (cancel || finished) {
  1146. break;
  1147. }
  1148. UpdateChildrenToFound ();
  1149. }
  1150. if (finished && !cancel) {
  1151. UpdateChildrenToFound ();
  1152. }
  1153. Application.MainLoop.Invoke (() => {
  1154. Parent.spinnerView.Visible = false;
  1155. });
  1156. }
  1157. }
  1158. private void UpdateChildrenToFound ()
  1159. {
  1160. lock (oLockFound) {
  1161. Children = found.ToArray ();
  1162. }
  1163. Application.MainLoop.Invoke (() => {
  1164. Parent.tbPath.Autocomplete.GenerateSuggestions (
  1165. new AutocompleteFilepathContext (Parent.tbPath.Text, Parent.tbPath.CursorPosition, this)
  1166. );
  1167. Parent.WriteStateToTableView ();
  1168. Parent.spinnerView.Visible = true;
  1169. Parent.spinnerView.SetNeedsDisplay ();
  1170. });
  1171. }
  1172. private void RecursiveFind (IDirectoryInfo directory)
  1173. {
  1174. foreach (var f in GetChildren (directory)) {
  1175. if (cancel) {
  1176. return;
  1177. }
  1178. if (f.IsParent) {
  1179. continue;
  1180. }
  1181. lock (oLockFound) {
  1182. if (found.Count >= FileDialog.MaxSearchResults) {
  1183. finished = true;
  1184. return;
  1185. }
  1186. }
  1187. if (Parent.SearchMatcher.IsMatch (f.FileSystemInfo)) {
  1188. lock (oLockFound) {
  1189. found.Add (f);
  1190. }
  1191. }
  1192. if (f.FileSystemInfo is IDirectoryInfo sub) {
  1193. RecursiveFind (sub);
  1194. }
  1195. }
  1196. }
  1197. internal override void RefreshChildren ()
  1198. {
  1199. }
  1200. /// <summary>
  1201. /// Cancels the current search (if any). Returns true if a search
  1202. /// was running and cancellation was successfully set.
  1203. /// </summary>
  1204. /// <returns></returns>
  1205. internal bool Cancel ()
  1206. {
  1207. var alreadyCancelled = token.IsCancellationRequested || cancel;
  1208. cancel = true;
  1209. token.Cancel ();
  1210. return !alreadyCancelled;
  1211. }
  1212. }
  1213. internal class FileDialogCollectionNavigator : CollectionNavigatorBase {
  1214. private FileDialog fileDialog;
  1215. public FileDialogCollectionNavigator (FileDialog fileDialog)
  1216. {
  1217. this.fileDialog = fileDialog;
  1218. }
  1219. protected override object ElementAt (int idx)
  1220. {
  1221. var val = FileDialogTableSource.GetRawColumnValue (fileDialog.tableView.SelectedColumn, fileDialog.State?.Children [idx]);
  1222. if (val == null) {
  1223. return string.Empty;
  1224. }
  1225. return val.ToString ().Trim ('.');
  1226. }
  1227. protected override int GetCollectionLength ()
  1228. {
  1229. return fileDialog.State?.Children.Length ?? 0;
  1230. }
  1231. }
  1232. }
  1233. }