FileDialog.cs 40 KB

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