FileDialog.cs 52 KB

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