FileDialog.cs 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  1. using System.IO.Abstractions;
  2. using System.Text.RegularExpressions;
  3. namespace Terminal.Gui.Views;
  4. /// <summary>
  5. /// The base-class for <see cref="OpenDialog"/> and <see cref="SaveDialog"/>
  6. /// </summary>
  7. public class FileDialog : Dialog, IDesignable
  8. {
  9. private const int ALIGNMENT_GROUP_COMPLETE = 55;
  10. /// <summary>Gets the Path separators for the operating system</summary>
  11. // ReSharper disable once InconsistentNaming
  12. internal static char [] Separators =
  13. [
  14. System.IO.Path.AltDirectorySeparatorChar,
  15. System.IO.Path.DirectorySeparatorChar
  16. ];
  17. /// <summary>
  18. /// Characters to prevent entry into <see cref="_tbPath"/>. Note that this is not using
  19. /// <see cref="System.IO.Path.GetInvalidFileNameChars"/> because we do want to allow directory separators, arrow keys
  20. /// etc.
  21. /// </summary>
  22. private static readonly char [] _badChars = ['"', '<', '>', '|', '*', '?'];
  23. /// <summary>Locking object for ensuring only a single <see cref="SearchState"/> executes at once.</summary>
  24. internal object _onlyOneSearchLock = new ();
  25. private readonly Button _btnBack;
  26. private readonly Button _btnCancel;
  27. private readonly Button _btnForward;
  28. private readonly Button _btnOk;
  29. private readonly Button _btnUp;
  30. private readonly Button _btnTreeToggle;
  31. private readonly IFileSystem? _fileSystem;
  32. private readonly FileDialogHistory _history;
  33. private readonly SpinnerView _spinnerView;
  34. private readonly View _tableViewContainer;
  35. private readonly TableView _tableView;
  36. private readonly TextField _tbFind;
  37. private readonly TextField _tbPath;
  38. private readonly TreeView<IFileSystemInfo> _treeView;
  39. #if MENU_V1
  40. private MenuBarItem? _allowedTypeMenu;
  41. private MenuBar? _allowedTypeMenuBar;
  42. private MenuItem []? _allowedTypeMenuItems;
  43. #endif
  44. private int _currentSortColumn;
  45. private bool _currentSortIsAsc = true;
  46. private bool _disposed;
  47. private string? _feedback;
  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 (IsModal)
  91. {
  92. (s as View)?.App?.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.Selecting += OnTableViewSelecting;
  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 (DrawContext? context)
  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. protected override void OnIsRunningChanged (bool newIsRunning)
  366. {
  367. base.OnIsRunningChanged (newIsRunning);
  368. if (!newIsRunning)
  369. {
  370. return;
  371. }
  372. Arrangement |= ViewArrangement.Resizable;
  373. // May have been updated after instance was constructed
  374. _btnOk.Text = Style.OkButtonText;
  375. _btnCancel.Text = Style.CancelButtonText;
  376. _btnUp.Text = GetUpButtonText ();
  377. _btnBack.Text = GetBackButtonText ();
  378. _btnForward.Text = GetForwardButtonText ();
  379. _tbPath.Title = Style.PathCaption;
  380. _tbFind.Title = Style.SearchCaption;
  381. _tbPath.Autocomplete.Scheme = new (_tbPath.GetScheme ())
  382. {
  383. Normal = new (Color.Black, _tbPath.GetAttributeForRole (VisualRole.Normal).Background)
  384. };
  385. _treeRoots = Style.TreeRootGetter ();
  386. Style.IconProvider.IsOpenGetter = _treeView.IsExpanded;
  387. _treeView.AddObjects (_treeRoots.Keys);
  388. // if filtering on file type is configured then create the ComboBox and establish
  389. // initial filtering by extension(s)
  390. if (AllowedTypes.Any ())
  391. {
  392. CurrentFilter = AllowedTypes [0];
  393. // Fiddle factor
  394. int width = AllowedTypes.Max (a => a.ToString ()!.Length) + 6;
  395. #if MENU_V1
  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. #endif
  426. }
  427. // if no path has been provided
  428. if (_tbPath.Text.Length <= 0)
  429. {
  430. Path = _fileSystem!.Directory.GetCurrentDirectory ();
  431. }
  432. // to streamline user experience and allow direct typing of paths
  433. // with zero navigation we start with focus in the text box and any
  434. // default/current path fully selected and ready to be overwritten
  435. _tbPath.SetFocus ();
  436. _tbPath.SelectAll ();
  437. if (string.IsNullOrEmpty (Title))
  438. {
  439. Title = GetDefaultTitle ();
  440. }
  441. if (Style.FlipOkCancelButtonLayoutOrder)
  442. {
  443. _btnCancel.X = Pos.Func (CalculateOkButtonPosX);
  444. _btnOk.X = Pos.Right (_btnCancel) + 1;
  445. MoveSubViewTowardsStart (_btnCancel);
  446. }
  447. // Ensure toggle button text matches current state after sizing
  448. SetTreeVisible (false);
  449. SetNeedsDraw ();
  450. SetNeedsLayout ();
  451. }
  452. /// <inheritdoc/>
  453. protected override void Dispose (bool disposing)
  454. {
  455. _disposed = true;
  456. base.Dispose (disposing);
  457. CancelSearch ();
  458. }
  459. /// <summary>
  460. /// Gets a default dialog title, when <see cref="View.Title"/> is not set or empty, result of the function will be
  461. /// shown.
  462. /// </summary>
  463. protected virtual string GetDefaultTitle ()
  464. {
  465. List<string> titleParts = [Strings.fdOpen];
  466. if (MustExist)
  467. {
  468. titleParts.Add (Strings.fdExisting);
  469. }
  470. switch (OpenMode)
  471. {
  472. case OpenMode.File:
  473. titleParts.Add (Strings.fdFile);
  474. break;
  475. case OpenMode.Directory:
  476. titleParts.Add (Strings.fdDirectory);
  477. break;
  478. }
  479. return string.Join (' ', titleParts);
  480. }
  481. internal void ApplySort ()
  482. {
  483. FileSystemInfoStats [] stats = State?.Children ?? [];
  484. // This portion is never reordered (always .. at top then folders)
  485. IOrderedEnumerable<FileSystemInfoStats> forcedOrder = stats
  486. .OrderByDescending (f => f.IsParent)
  487. .ThenBy (f => f.IsDir ? -1 : 100);
  488. // This portion is flexible based on the column clicked (e.g. alphabetical)
  489. IOrderedEnumerable<FileSystemInfoStats> ordered =
  490. _currentSortIsAsc
  491. ? forcedOrder.ThenBy (
  492. f =>
  493. FileDialogTableSource.GetRawColumnValue (_currentSortColumn, f)
  494. )
  495. : forcedOrder.ThenByDescending (
  496. f =>
  497. FileDialogTableSource.GetRawColumnValue (_currentSortColumn, f)
  498. );
  499. if (State is { })
  500. {
  501. State.Children = ordered.ToArray ();
  502. }
  503. _tableView.Update ();
  504. }
  505. /// <summary>Changes the dialog such that <paramref name="d"/> is being explored.</summary>
  506. /// <param name="d"></param>
  507. /// <param name="addCurrentStateToHistory"></param>
  508. /// <param name="setPathText"></param>
  509. /// <param name="clearForward"></param>
  510. /// <param name="pathText">Optional alternate string to set path to.</param>
  511. internal void PushState (
  512. IDirectoryInfo d,
  513. bool addCurrentStateToHistory,
  514. bool setPathText = true,
  515. bool clearForward = true,
  516. string? pathText = null
  517. )
  518. {
  519. // no change of state
  520. if (d == State?.Directory)
  521. {
  522. return;
  523. }
  524. if (d.FullName == State?.Directory.FullName)
  525. {
  526. return;
  527. }
  528. PushState (
  529. new FileDialogState (d, this),
  530. addCurrentStateToHistory,
  531. setPathText,
  532. clearForward,
  533. pathText
  534. );
  535. }
  536. /// <summary>Select <paramref name="toRestore"/> in the table view (if present)</summary>
  537. /// <param name="toRestore"></param>
  538. internal void RestoreSelection (IFileSystemInfo toRestore)
  539. {
  540. _tableView.SelectedRow = State!.Children.IndexOf (r => r.FileSystemInfo == toRestore);
  541. _tableView.EnsureSelectedCellIsVisible ();
  542. }
  543. internal void SortColumn (int col, bool isAsc)
  544. {
  545. // set a sort order
  546. _currentSortColumn = col;
  547. _currentSortIsAsc = isAsc;
  548. ApplySort ();
  549. }
  550. private void Accept (IEnumerable<FileSystemInfoStats> toMultiAccept)
  551. {
  552. if (!AllowsMultipleSelection)
  553. {
  554. return;
  555. }
  556. // Don't include ".." (IsParent) in multi-selections
  557. MultiSelected = toMultiAccept
  558. .Where (s => !s.IsParent)
  559. .Select (s => s.FileSystemInfo!.FullName)
  560. .ToList ()
  561. .AsReadOnly ();
  562. Path = MultiSelected.Count == 1 ? MultiSelected [0] : string.Empty;
  563. FinishAccept ();
  564. }
  565. private void Accept (IFileInfo f)
  566. {
  567. if (!IsCompatibleWithOpenMode (f.FullName, out string reason))
  568. {
  569. _feedback = reason;
  570. SetNeedsDraw ();
  571. return;
  572. }
  573. Path = f.FullName;
  574. if (AllowsMultipleSelection)
  575. {
  576. MultiSelected = new List<string> { f.FullName }.AsReadOnly ();
  577. }
  578. FinishAccept ();
  579. }
  580. private void Accept (bool allowMulti)
  581. {
  582. if (allowMulti && TryAcceptMulti ())
  583. {
  584. return;
  585. }
  586. if (!IsCompatibleWithOpenMode (_tbPath.Text, out string reason))
  587. {
  588. _feedback = reason;
  589. SetNeedsDraw ();
  590. return;
  591. }
  592. FinishAccept ();
  593. }
  594. private void AcceptIf (Key key, KeyCode isKey)
  595. {
  596. if (!key.Handled && key.KeyCode == isKey)
  597. {
  598. key.Handled = true;
  599. // User hit Enter in text box so probably wants the
  600. // contents of the text box as their selection not
  601. // whatever lingering selection is in TableView
  602. Accept (false);
  603. }
  604. }
  605. #if MENU_V1
  606. private void AllowedTypeMenuClicked (int idx)
  607. {
  608. IAllowedType allow = AllowedTypes [idx];
  609. for (var i = 0; i < AllowedTypes.Count; i++)
  610. {
  611. _allowedTypeMenuItems! [i].Checked = i == idx;
  612. }
  613. _allowedTypeMenu!.Title = allow.ToString ()!;
  614. CurrentFilter = allow;
  615. _tbPath.ClearAllSelection ();
  616. _tbPath.Autocomplete.ClearSuggestions ();
  617. State?.RefreshChildren ();
  618. WriteStateToTableView ();
  619. }
  620. #endif
  621. private string AspectGetter (object o)
  622. {
  623. var fsi = (IFileSystemInfo)o;
  624. if (o is IDirectoryInfo dir && _treeRoots.ContainsKey (dir))
  625. {
  626. // Directory has a special name e.g. 'Pictures'
  627. return _treeRoots [dir];
  628. }
  629. return (Style.IconProvider.GetIconWithOptionalSpace (fsi) + fsi.Name).Trim ();
  630. }
  631. private int CalculateOkButtonPosX (View? _)
  632. {
  633. if (!IsInitialized || !_btnOk.IsInitialized || !_btnCancel.IsInitialized)
  634. {
  635. return 0;
  636. }
  637. return Viewport.Width
  638. - _btnOk.Viewport.Width
  639. - _btnCancel.Viewport.Width
  640. - 1
  641. // TODO: Fiddle factor, seems the Viewport are wrong for someone
  642. - 2;
  643. }
  644. private bool CancelSearch ()
  645. {
  646. if (State is SearchState search)
  647. {
  648. return search.Cancel ();
  649. }
  650. return false;
  651. }
  652. private void CellActivate (object? sender, CellActivatedEventArgs obj)
  653. {
  654. if (TryAcceptMulti ())
  655. {
  656. return;
  657. }
  658. FileSystemInfoStats stats = RowToStats (obj.Row);
  659. if (stats.FileSystemInfo is IDirectoryInfo d)
  660. {
  661. PushState (d, true);
  662. //if (d == State?.Directory || d.FullName == State?.Directory.FullName)
  663. //{
  664. // FinishAccept ();
  665. //}
  666. return;
  667. }
  668. if (stats.FileSystemInfo is IFileInfo f)
  669. {
  670. Accept (f);
  671. }
  672. }
  673. private void ClearFeedback () { _feedback = null; }
  674. private Scheme ColorGetter (CellColorGetterArgs args)
  675. {
  676. FileSystemInfoStats stats = RowToStats (args.RowIndex);
  677. if (!Style.UseColors)
  678. {
  679. return _tableView.GetScheme ();
  680. }
  681. Color color = Style.ColorProvider.GetColor (stats.FileSystemInfo!) ?? new Color (Color.White);
  682. var black = new Color (Color.Black);
  683. // TODO: Add some kind of cache for this
  684. return new ()
  685. {
  686. Normal = new (color, black),
  687. HotNormal = new (color, black),
  688. Focus = new (black, color),
  689. HotFocus = new (black, color)
  690. };
  691. }
  692. private void Delete ()
  693. {
  694. IFileSystemInfo [] toDelete = GetFocusedFiles ()!;
  695. if (FileOperationsHandler.Delete (App, toDelete))
  696. {
  697. RefreshState ();
  698. }
  699. }
  700. private void FinishAccept ()
  701. {
  702. var e = new FilesSelectedEventArgs (this);
  703. FilesSelected?.Invoke (this, e);
  704. if (e.Cancel)
  705. {
  706. return;
  707. }
  708. // if user uses Path selection mode (e.g. Enter in text box)
  709. // then also copy to MultiSelected
  710. if (AllowsMultipleSelection && !MultiSelected.Any ())
  711. {
  712. MultiSelected = string.IsNullOrWhiteSpace (Path)
  713. ? Enumerable.Empty<string> ().ToList ().AsReadOnly ()
  714. : new List<string> { Path }.AsReadOnly ();
  715. }
  716. Canceled = false;
  717. if (IsModal)
  718. {
  719. App?.RequestStop ();
  720. }
  721. }
  722. private string GetBackButtonText () { return Glyphs.LeftArrow + "-"; }
  723. private IFileSystemInfo? []? GetFocusedFiles ()
  724. {
  725. if (!_tableView.HasFocus || !_tableView.CanFocus)
  726. {
  727. return null;
  728. }
  729. _tableView.EnsureValidSelection ();
  730. if (_tableView.SelectedRow < 0)
  731. {
  732. return null;
  733. }
  734. return _tableView.GetAllSelectedCells ()
  735. .Select (c => c.Y)
  736. .Distinct ()
  737. .Select (RowToStats)
  738. .Where (s => !s.IsParent)
  739. .Select (d => d.FileSystemInfo)
  740. .ToArray ();
  741. }
  742. private string GetForwardButtonText () { return "-" + Glyphs.RightArrow; }
  743. private string GetProposedNewSortOrder (int clickedCol, out bool isAsc)
  744. {
  745. // work out new sort order
  746. if (_currentSortColumn == clickedCol && _currentSortIsAsc)
  747. {
  748. isAsc = false;
  749. return string.Format (Strings.fdCtxSortDesc, _tableView.Table.ColumnNames [clickedCol]);
  750. }
  751. isAsc = true;
  752. return string.Format (Strings.fdCtxSortAsc, _tableView.Table.ColumnNames [clickedCol]);
  753. }
  754. private string GetUpButtonText () { return Style.UseUnicodeCharacters ? "◭" : "▲"; }
  755. private void HideColumn (int clickedCol)
  756. {
  757. ColumnStyle style = _tableView.Style.GetOrCreateColumnStyle (clickedCol);
  758. style.Visible = false;
  759. _tableView.Update ();
  760. }
  761. private bool IsCompatibleWithAllowedExtensions (string path)
  762. {
  763. // no restrictions
  764. if (!AllowedTypes.Any ())
  765. {
  766. return true;
  767. }
  768. return AllowedTypes.Any (t => t.IsAllowed (path));
  769. }
  770. private bool IsCompatibleWithOpenMode (string s, out string reason)
  771. {
  772. reason = string.Empty;
  773. if (string.IsNullOrWhiteSpace (s))
  774. {
  775. return false;
  776. }
  777. if (!IsCompatibleWithAllowedExtensions (s))
  778. {
  779. reason = Style.WrongFileTypeFeedback;
  780. return false;
  781. }
  782. switch (OpenMode)
  783. {
  784. case OpenMode.Directory:
  785. if (MustExist && !Directory.Exists (s))
  786. {
  787. reason = Style.DirectoryMustExistFeedback;
  788. return false;
  789. }
  790. if (File.Exists (s))
  791. {
  792. reason = Style.FileAlreadyExistsFeedback;
  793. return false;
  794. }
  795. return true;
  796. case OpenMode.File:
  797. if (MustExist && !File.Exists (s))
  798. {
  799. reason = Style.FileMustExistFeedback;
  800. return false;
  801. }
  802. if (Directory.Exists (s))
  803. {
  804. reason = Style.DirectoryAlreadyExistsFeedback;
  805. return false;
  806. }
  807. return true;
  808. case OpenMode.Mixed:
  809. if (MustExist && !File.Exists (s) && !Directory.Exists (s))
  810. {
  811. reason = Style.FileOrDirectoryMustExistFeedback;
  812. return false;
  813. }
  814. return true;
  815. default: throw new ArgumentOutOfRangeException (nameof (OpenMode));
  816. }
  817. }
  818. /// <summary>Returns true if any <see cref="AllowedTypes"/> matches <paramref name="file"/>.</summary>
  819. /// <param name="file"></param>
  820. /// <returns></returns>
  821. private bool MatchesAllowedTypes (IFileInfo file) { return AllowedTypes.Any (t => t.IsAllowed (file.FullName)); }
  822. /// <summary>
  823. /// If <see cref="TableView.MultiSelect"/> is this returns a union of all <see cref="FileSystemInfoStats"/> in the
  824. /// selection.
  825. /// </summary>
  826. /// <returns></returns>
  827. private IEnumerable<FileSystemInfoStats> MultiRowToStats ()
  828. {
  829. HashSet<FileSystemInfoStats> toReturn = new ();
  830. if (AllowsMultipleSelection && _tableView.MultiSelectedRegions.Any ())
  831. {
  832. foreach (Point p in _tableView.GetAllSelectedCells ())
  833. {
  834. FileSystemInfoStats add = State?.Children [p.Y]!;
  835. toReturn.Add (add);
  836. }
  837. }
  838. return toReturn;
  839. }
  840. private void New ()
  841. {
  842. {
  843. IFileSystemInfo created = FileOperationsHandler.New (App, _fileSystem!, State!.Directory);
  844. if (created is { })
  845. {
  846. RefreshState ();
  847. RestoreSelection (created);
  848. }
  849. }
  850. }
  851. private void OnTableViewSelecting (object? sender, CommandEventArgs e)
  852. {
  853. // Only handle mouse clicks, not keyboard selections
  854. if (e.Context is not CommandContext<MouseBinding> { Binding.MouseEventArgs: { } mouseArgs })
  855. {
  856. return;
  857. }
  858. Point? clickedCell = _tableView.ScreenToCell (mouseArgs.Position.X, mouseArgs.Position.Y, out int? clickedCol);
  859. if (clickedCol is { })
  860. {
  861. if (mouseArgs.Flags.HasFlag (MouseFlags.Button1Clicked))
  862. {
  863. // left click in a header
  864. SortColumn (clickedCol.Value);
  865. }
  866. else if (mouseArgs.Flags.HasFlag (MouseFlags.Button3Clicked))
  867. {
  868. // right click in a header
  869. ShowHeaderContextMenu (clickedCol.Value, mouseArgs);
  870. }
  871. }
  872. else
  873. {
  874. if (clickedCell is { } && mouseArgs.Flags.HasFlag (MouseFlags.Button3Clicked))
  875. {
  876. // right click in rest of table
  877. ShowCellContextMenu (clickedCell, mouseArgs);
  878. }
  879. }
  880. }
  881. private void PathChanged ()
  882. {
  883. // avoid re-entry
  884. if (_pushingState)
  885. {
  886. return;
  887. }
  888. string path = _tbPath.Text;
  889. if (string.IsNullOrWhiteSpace (path))
  890. {
  891. return;
  892. }
  893. IDirectoryInfo dir = StringToDirectoryInfo (path);
  894. if (dir.Exists)
  895. {
  896. PushState (dir, true, false);
  897. }
  898. else if (dir.Parent?.Exists ?? false)
  899. {
  900. PushState (dir.Parent, true, false);
  901. }
  902. _tbPath.Autocomplete.GenerateSuggestions (
  903. new AutocompleteFilepathContext (_tbPath.Text, _tbPath.CursorPosition, State)
  904. );
  905. }
  906. private void PushState (
  907. FileDialogState newState,
  908. bool addCurrentStateToHistory,
  909. bool setPathText = true,
  910. bool clearForward = true,
  911. string? pathText = null
  912. )
  913. {
  914. if (State is SearchState search)
  915. {
  916. search.Cancel ();
  917. }
  918. try
  919. {
  920. _pushingState = true;
  921. // push the old state to history
  922. if (addCurrentStateToHistory)
  923. {
  924. _history.Push (State, clearForward);
  925. }
  926. _tbPath.Autocomplete.ClearSuggestions ();
  927. if (pathText is { })
  928. {
  929. Path = pathText;
  930. }
  931. else if (setPathText)
  932. {
  933. SetPathToSelectedObject (newState.Directory);
  934. }
  935. State = newState;
  936. _tbPath.Autocomplete.GenerateSuggestions (
  937. new AutocompleteFilepathContext (_tbPath.Text, _tbPath.CursorPosition, State)
  938. );
  939. WriteStateToTableView ();
  940. if (clearForward)
  941. {
  942. _history.ClearForward ();
  943. }
  944. _tableView.RowOffset = 0;
  945. _tableView.SelectedRow = 0;
  946. SetNeedsDraw ();
  947. UpdateNavigationVisibility ();
  948. }
  949. finally
  950. {
  951. _pushingState = false;
  952. }
  953. ClearFeedback ();
  954. }
  955. private void RefreshState ()
  956. {
  957. State!.RefreshChildren ();
  958. PushState (State, false, false, false);
  959. }
  960. private void Rename (IApplication? app)
  961. {
  962. IFileSystemInfo [] toRename = GetFocusedFiles ()!;
  963. if (toRename?.Length == 1)
  964. {
  965. IFileSystemInfo newNamed = FileOperationsHandler.Rename (app, _fileSystem!, toRename.Single ());
  966. if (newNamed is { })
  967. {
  968. RefreshState ();
  969. RestoreSelection (newNamed);
  970. }
  971. }
  972. }
  973. private void RestartSearch ()
  974. {
  975. if (_disposed || State?.Directory is null)
  976. {
  977. return;
  978. }
  979. if (State is SearchState oldSearch)
  980. {
  981. oldSearch.Cancel ();
  982. }
  983. // user is clearing search terms
  984. if (_tbFind.Text is null || _tbFind.Text.Length == 0)
  985. {
  986. // Wait for search cancellation (if any) to finish
  987. // then push the current dir state
  988. lock (_onlyOneSearchLock)
  989. {
  990. PushState (new FileDialogState (State.Directory, this), false);
  991. }
  992. return;
  993. }
  994. PushState (new SearchState (State?.Directory!, this, _tbFind.Text), true);
  995. }
  996. private FileSystemInfoStats RowToStats (int rowIndex) { return State?.Children [rowIndex]!; }
  997. private void ShowCellContextMenu (Point? clickedCell, MouseEventArgs e)
  998. {
  999. if (clickedCell is null)
  1000. {
  1001. return;
  1002. }
  1003. PopoverMenu? contextMenu = new (
  1004. [
  1005. new (Strings.fdCtxNew, string.Empty, New),
  1006. new (Strings.fdCtxRename, string.Empty, () => Rename (App)),
  1007. new (Strings.fdCtxDelete, string.Empty, Delete)
  1008. ]);
  1009. _tableView.SetSelection (clickedCell.Value.X, clickedCell.Value.Y, false);
  1010. // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
  1011. // and the context menu is disposed when it is closed.
  1012. App!.Popover?.Register (contextMenu);
  1013. contextMenu?.MakeVisible (e.ScreenPosition);
  1014. }
  1015. private void ShowHeaderContextMenu (int clickedCol, MouseEventArgs e)
  1016. {
  1017. string sort = GetProposedNewSortOrder (clickedCol, out bool isAsc);
  1018. PopoverMenu? contextMenu = new (
  1019. [
  1020. new (
  1021. string.Format (
  1022. Strings.fdCtxHide,
  1023. StripArrows (_tableView.Table.ColumnNames [clickedCol])
  1024. ),
  1025. string.Empty,
  1026. () => HideColumn (clickedCol)
  1027. ),
  1028. new (
  1029. StripArrows (sort),
  1030. string.Empty,
  1031. () => SortColumn (clickedCol, isAsc))
  1032. ]
  1033. );
  1034. // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
  1035. // and the context menu is disposed when it is closed.
  1036. App!.Popover?.Register (contextMenu);
  1037. contextMenu?.MakeVisible (e.ScreenPosition);
  1038. }
  1039. private void SortColumn (int clickedCol)
  1040. {
  1041. GetProposedNewSortOrder (clickedCol, out bool isAsc);
  1042. SortColumn (clickedCol, isAsc);
  1043. _tableView.Table =
  1044. new FileDialogTableSource (this, State, Style, _currentSortColumn, _currentSortIsAsc);
  1045. }
  1046. private IDirectoryInfo StringToDirectoryInfo (string path)
  1047. {
  1048. // if you pass new DirectoryInfo("C:") you get a weird object
  1049. // where the FullName is in fact the current working directory.
  1050. // really not what most users would expect
  1051. if (Regex.IsMatch (path, "^\\w:$"))
  1052. {
  1053. return _fileSystem!.DirectoryInfo.New (path + _fileSystem.Path.DirectorySeparatorChar);
  1054. }
  1055. return _fileSystem!.DirectoryInfo.New (path);
  1056. }
  1057. private static string StripArrows (string columnName) { return columnName.Replace (" (▼)", string.Empty).Replace (" (▲)", string.Empty); }
  1058. private void SuppressIfBadChar (Key k)
  1059. {
  1060. // don't let user type bad letters
  1061. var ch = (char)k;
  1062. if (_badChars.Contains (ch))
  1063. {
  1064. k.Handled = true;
  1065. }
  1066. }
  1067. private bool TableView_KeyUp (Key keyEvent)
  1068. {
  1069. if (keyEvent.KeyCode == KeyCode.Backspace)
  1070. {
  1071. return _history.Back ();
  1072. }
  1073. if (keyEvent.KeyCode == (KeyCode.ShiftMask | KeyCode.Backspace))
  1074. {
  1075. return _history.Forward ();
  1076. }
  1077. if (keyEvent.KeyCode == KeyCode.Delete)
  1078. {
  1079. Delete ();
  1080. return true;
  1081. }
  1082. if (keyEvent.KeyCode == (KeyCode.CtrlMask | KeyCode.R))
  1083. {
  1084. Rename (App);
  1085. return true;
  1086. }
  1087. if (keyEvent.KeyCode == (KeyCode.CtrlMask | KeyCode.N))
  1088. {
  1089. New ();
  1090. return true;
  1091. }
  1092. return false;
  1093. }
  1094. private void TableView_SelectedCellChanged (object? sender, SelectedCellChangedEventArgs obj)
  1095. {
  1096. if (!_tableView.HasFocus || obj.NewRow == -1 || obj.Table.Rows == 0)
  1097. {
  1098. return;
  1099. }
  1100. if (_tableView.MultiSelect && _tableView.MultiSelectedRegions.Any ())
  1101. {
  1102. return;
  1103. }
  1104. FileSystemInfoStats? stats = RowToStats (obj.NewRow);
  1105. IFileSystemInfo? dest;
  1106. if (stats.IsParent)
  1107. {
  1108. dest = State!.Directory;
  1109. }
  1110. else
  1111. {
  1112. dest = stats.FileSystemInfo;
  1113. }
  1114. try
  1115. {
  1116. _pushingState = true;
  1117. SetPathToSelectedObject (dest);
  1118. State!.Selected = stats;
  1119. _tbPath.Autocomplete.ClearSuggestions ();
  1120. }
  1121. finally
  1122. {
  1123. _pushingState = false;
  1124. }
  1125. }
  1126. private void TreeView_SelectionChanged (object? sender, SelectionChangedEventArgs<IFileSystemInfo> e)
  1127. {
  1128. SetPathToSelectedObject (e.NewValue);
  1129. }
  1130. private void SetPathToSelectedObject (IFileSystemInfo? selected)
  1131. {
  1132. if (selected is null)
  1133. {
  1134. return;
  1135. }
  1136. if (selected is IDirectoryInfo && Style.PreserveFilenameOnDirectoryChanges)
  1137. {
  1138. if (!string.IsNullOrWhiteSpace (Path) && !_fileSystem!.Directory.Exists (Path))
  1139. {
  1140. var currentFile = _fileSystem.Path.GetFileName (Path);
  1141. if (!string.IsNullOrWhiteSpace (currentFile))
  1142. {
  1143. Path = _fileSystem.Path.Combine (selected.FullName, currentFile);
  1144. return;
  1145. }
  1146. }
  1147. }
  1148. Path = selected.FullName;
  1149. }
  1150. private bool TryAcceptMulti ()
  1151. {
  1152. IEnumerable<FileSystemInfoStats> multi = MultiRowToStats ();
  1153. string? reason = null;
  1154. IEnumerable<FileSystemInfoStats> fileSystemInfoStatsEnumerable = multi as FileSystemInfoStats [] ?? multi.ToArray ();
  1155. if (!fileSystemInfoStatsEnumerable.Any ())
  1156. {
  1157. return false;
  1158. }
  1159. if (fileSystemInfoStatsEnumerable.All (
  1160. m => m.FileSystemInfo is { } && IsCompatibleWithOpenMode (
  1161. m.FileSystemInfo.FullName,
  1162. out reason
  1163. )
  1164. ))
  1165. {
  1166. Accept (fileSystemInfoStatsEnumerable);
  1167. return true;
  1168. }
  1169. if (reason is { })
  1170. {
  1171. _feedback = reason;
  1172. SetNeedsDraw ();
  1173. }
  1174. return false;
  1175. }
  1176. private void UpdateNavigationVisibility ()
  1177. {
  1178. _btnBack.Visible = _history.CanBack ();
  1179. _btnForward.Visible = _history.CanForward ();
  1180. _btnUp.Visible = _history.CanUp ();
  1181. }
  1182. private void WriteStateToTableView ()
  1183. {
  1184. _tableView.Table =
  1185. new FileDialogTableSource (this, State, Style, _currentSortColumn, _currentSortIsAsc);
  1186. ApplySort ();
  1187. _tableView.Update ();
  1188. }
  1189. // --- Tree visibility management ---
  1190. private void ToggleTreeVisibility ()
  1191. {
  1192. SetTreeVisible (!_treeView.Visible);
  1193. }
  1194. private void SetTreeVisible (bool visible)
  1195. {
  1196. _treeView.Enabled = visible;
  1197. _treeView.Visible = visible;
  1198. if (visible)
  1199. {
  1200. // When visible, the table view's left edge is a splitter next to the tree
  1201. _treeView.Width = Dim.Fill (Dim.Func (_ => IsInitialized ? _tableViewContainer!.Frame.Width - 30 : 30));
  1202. _tableViewContainer.X = 30;
  1203. _tableViewContainer.Arrangement = ViewArrangement.LeftResizable;
  1204. _tableViewContainer.Border!.Thickness = new (1, 0, 0, 0);
  1205. }
  1206. else
  1207. {
  1208. // When hidden, table occupies full width and splitter is hidden/disabled
  1209. _treeView.Width = 0;
  1210. _tableViewContainer.X = 0;
  1211. _tableViewContainer.Width = Dim.Fill ();
  1212. _tableViewContainer.Arrangement = ViewArrangement.Fixed;
  1213. _tableViewContainer.Border!.Thickness = new (0, 0, 0, 0);
  1214. }
  1215. _btnTreeToggle.Text = GetTreeToggleText (visible);
  1216. SetNeedsLayout ();
  1217. SetNeedsDraw ();
  1218. }
  1219. private string GetTreeToggleText (bool visible)
  1220. {
  1221. return visible
  1222. ? $"{Glyphs.LeftArrow}{Strings.fdTree}"
  1223. : $"{Glyphs.RightArrow}{Strings.fdTree}";
  1224. }
  1225. /// <summary>State representing a recursive search from <see cref="FileDialogState.Directory"/> downwards.</summary>
  1226. internal class SearchState : FileDialogState
  1227. {
  1228. // TODO: Add thread safe child adding
  1229. private readonly List<FileSystemInfoStats> _found = [];
  1230. private readonly object _oLockFound = new ();
  1231. private readonly CancellationTokenSource _token = new ();
  1232. private bool _cancel;
  1233. private bool _finished;
  1234. public SearchState (IDirectoryInfo dir, FileDialog parent, string searchTerms) : base (dir, parent)
  1235. {
  1236. parent.SearchMatcher.Initialize (searchTerms);
  1237. Children = [];
  1238. BeginSearch ();
  1239. }
  1240. /// <summary>
  1241. /// Cancels the current search (if any). Returns true if a search was running and cancellation was successfully
  1242. /// set.
  1243. /// </summary>
  1244. /// <returns></returns>
  1245. internal bool Cancel ()
  1246. {
  1247. bool alreadyCancelled = _token.IsCancellationRequested || _cancel;
  1248. _cancel = true;
  1249. _token.Cancel ();
  1250. return !alreadyCancelled;
  1251. }
  1252. internal override void RefreshChildren () { }
  1253. private void BeginSearch ()
  1254. {
  1255. Task.Run (
  1256. () =>
  1257. {
  1258. RecursiveFind (Directory);
  1259. _finished = true;
  1260. }
  1261. );
  1262. Task.Run (UpdateChildren);
  1263. }
  1264. private void RecursiveFind (IDirectoryInfo directory)
  1265. {
  1266. foreach (FileSystemInfoStats f in GetChildren (directory))
  1267. {
  1268. if (_cancel)
  1269. {
  1270. return;
  1271. }
  1272. if (f.IsParent)
  1273. {
  1274. continue;
  1275. }
  1276. lock (_oLockFound)
  1277. {
  1278. if (_found.Count >= MaxSearchResults)
  1279. {
  1280. _finished = true;
  1281. return;
  1282. }
  1283. }
  1284. if (Parent.SearchMatcher.IsMatch (f.FileSystemInfo!))
  1285. {
  1286. lock (_oLockFound)
  1287. {
  1288. _found.Add (f);
  1289. }
  1290. }
  1291. if (f.FileSystemInfo is IDirectoryInfo sub)
  1292. {
  1293. RecursiveFind (sub);
  1294. }
  1295. }
  1296. }
  1297. private void UpdateChildren ()
  1298. {
  1299. lock (Parent._onlyOneSearchLock)
  1300. {
  1301. while (!_cancel && !_finished)
  1302. {
  1303. try
  1304. {
  1305. Task.Delay (250).Wait (_token.Token);
  1306. }
  1307. catch (OperationCanceledException)
  1308. {
  1309. _cancel = true;
  1310. }
  1311. if (_cancel || _finished)
  1312. {
  1313. break;
  1314. }
  1315. UpdateChildrenToFound ();
  1316. }
  1317. if (_finished && !_cancel)
  1318. {
  1319. UpdateChildrenToFound ();
  1320. }
  1321. Application.Invoke ((_) => { Parent._spinnerView.Visible = false; });
  1322. }
  1323. }
  1324. private void UpdateChildrenToFound ()
  1325. {
  1326. lock (_oLockFound)
  1327. {
  1328. Children = _found.ToArray ();
  1329. }
  1330. Application.Invoke (
  1331. (_) =>
  1332. {
  1333. Parent._tbPath.Autocomplete.GenerateSuggestions (
  1334. new AutocompleteFilepathContext (
  1335. Parent._tbPath.Text,
  1336. Parent._tbPath.CursorPosition,
  1337. this
  1338. )
  1339. );
  1340. Parent.WriteStateToTableView ();
  1341. Parent._spinnerView.Visible = true;
  1342. Parent._spinnerView.SetNeedsDraw ();
  1343. }
  1344. );
  1345. }
  1346. }
  1347. bool IDesignable.EnableForDesign ()
  1348. {
  1349. OnIsRunningChanged (true);
  1350. return true;
  1351. }
  1352. }