FileDialog.cs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652
  1. using System.IO.Abstractions;
  2. using System.Text.RegularExpressions;
  3. #nullable enable
  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 alignmentGroupInput = 32;
  11. private const int alignmentGroupComplete = 55;
  12. /// <summary>Gets the Path separators for the operating system</summary>
  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 _btnToggleSplitterCollapse;
  31. private readonly Button _btnUp;
  32. private readonly IFileSystem _fileSystem;
  33. private readonly FileDialogHistory _history;
  34. private readonly SpinnerView _spinnerView;
  35. private readonly View _leftPanel;
  36. private readonly View _rightPanel;
  37. private readonly TableView _tableView;
  38. private readonly TextField _tbFind;
  39. private readonly TextField _tbPath;
  40. private readonly TreeView<IFileSystemInfo> _treeView;
  41. private MenuBarItem _allowedTypeMenu;
  42. private MenuBar _allowedTypeMenuBar;
  43. private MenuItem [] _allowedTypeMenuItems;
  44. private int _currentSortColumn;
  45. private bool _currentSortIsAsc = true;
  46. private bool _disposed;
  47. private string _feedback;
  48. private bool _loaded;
  49. private bool _pushingState;
  50. private Dictionary<IDirectoryInfo, string> _treeRoots = new ();
  51. /// <summary>Initializes a new instance of the <see cref="FileDialog"/> class.</summary>
  52. public FileDialog () : this (new FileSystem ()) { }
  53. /// <summary>Initializes a new instance of the <see cref="FileDialog"/> class with a custom <see cref="IFileSystem"/>.</summary>
  54. /// <remarks>This overload is mainly useful for testing.</remarks>
  55. internal FileDialog (IFileSystem fileSystem)
  56. {
  57. Height = Dim.Percent (80);
  58. Width = Dim.Percent (80);
  59. // Assume canceled
  60. Canceled = true;
  61. _fileSystem = fileSystem;
  62. Style = new (fileSystem);
  63. _btnOk = new ()
  64. {
  65. X = Pos.Align (Alignment.End, AlignmentModes.AddSpaceBetweenItems, alignmentGroupComplete),
  66. Y = Pos.AnchorEnd (),
  67. IsDefault = true, Text = Style.OkButtonText
  68. };
  69. _btnOk.Accepting += (s, e) =>
  70. {
  71. if (e.Handled)
  72. {
  73. return;
  74. }
  75. Accept (true);
  76. };
  77. _btnCancel = new ()
  78. {
  79. X = Pos.Align (Alignment.End, AlignmentModes.AddSpaceBetweenItems, alignmentGroupComplete),
  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. _btnUp = new () { X = 0, Y = 1, NoPadding = true };
  96. _btnUp.Text = GetUpButtonText ();
  97. _btnUp.Accepting += (s, e) =>
  98. {
  99. _history?.Up ();
  100. e.Handled = true;
  101. };
  102. _btnBack = new () { X = Pos.Right (_btnUp) + 1, Y = 1, NoPadding = true };
  103. _btnBack.Text = GetBackButtonText ();
  104. _btnBack.Accepting += (s, e) =>
  105. {
  106. _history?.Back ();
  107. e.Handled = true;
  108. };
  109. _btnForward = new () { X = Pos.Right (_btnBack) + 1, Y = 1, NoPadding = true };
  110. _btnForward.Text = GetForwardButtonText ();
  111. _btnForward.Accepting += (s, e) =>
  112. {
  113. _history?.Forward ();
  114. e.Handled = true;
  115. };
  116. _tbPath = new () { Width = Dim.Fill (), CaptionColor = new (Color.Black) };
  117. _tbPath.KeyDown += (s, k) =>
  118. {
  119. ClearFeedback ();
  120. AcceptIf (k, KeyCode.Enter);
  121. SuppressIfBadChar (k);
  122. };
  123. _tbPath.Autocomplete = new AppendAutocomplete (_tbPath);
  124. _tbPath.Autocomplete.SuggestionGenerator = new FilepathSuggestionGenerator ();
  125. // Left panel for tree view
  126. _leftPanel = new ()
  127. {
  128. Id = "leftPanel",
  129. X = 0,
  130. Y = Pos.Bottom (_btnBack),
  131. Width = 30,
  132. Height = Dim.Fill (Dim.Func (_ => IsInitialized ? _btnOk.Frame.Height : 1)),
  133. Visible = false,
  134. CanFocus = false,
  135. TabStop = TabBehavior.NoStop,
  136. Arrangement = ViewArrangement.Resizable
  137. };
  138. // Right panel for table view
  139. _rightPanel = new ()
  140. {
  141. Id = "rightPanel",
  142. X = Pos.Right (_leftPanel),
  143. Y = Pos.Bottom (_btnBack),
  144. Width = Dim.Fill (),
  145. Height = Dim.Fill (Dim.Func (_ => IsInitialized ? _btnOk.Frame.Height : 1)),
  146. CanFocus = false,
  147. TabStop = TabBehavior.NoStop
  148. };
  149. // this.splitContainer.Border.BorderStyle = BorderStyle.None;
  150. _tableView = new ()
  151. {
  152. Width = Dim.Fill (),
  153. Height = Dim.Fill (),
  154. FullRowSelect = true,
  155. };
  156. _tableView.CollectionNavigator = new FileDialogCollectionNavigator (this, _tableView);
  157. _tableView.KeyBindings.ReplaceCommands (Key.Space, Command.Select);
  158. _tableView.MouseClick += OnTableViewMouseClick;
  159. _tableView.Style.InvertSelectedCellFirstCharacter = true;
  160. Style.TableStyle = _tableView.Style;
  161. ColumnStyle nameStyle = Style.TableStyle.GetOrCreateColumnStyle (0);
  162. nameStyle.MinWidth = 10;
  163. nameStyle.ColorGetter = ColorGetter;
  164. ColumnStyle sizeStyle = Style.TableStyle.GetOrCreateColumnStyle (1);
  165. sizeStyle.MinWidth = 10;
  166. sizeStyle.ColorGetter = ColorGetter;
  167. ColumnStyle dateModifiedStyle = Style.TableStyle.GetOrCreateColumnStyle (2);
  168. dateModifiedStyle.MinWidth = 30;
  169. dateModifiedStyle.ColorGetter = ColorGetter;
  170. ColumnStyle typeStyle = Style.TableStyle.GetOrCreateColumnStyle (3);
  171. typeStyle.MinWidth = 6;
  172. typeStyle.ColorGetter = ColorGetter;
  173. _treeView = new () { Width = Dim.Fill (), Height = Dim.Fill () };
  174. var fileDialogTreeBuilder = new FileSystemTreeBuilder ();
  175. _treeView.TreeBuilder = fileDialogTreeBuilder;
  176. _treeView.AspectGetter = AspectGetter;
  177. Style.TreeStyle = _treeView.Style;
  178. _treeView.SelectionChanged += TreeView_SelectionChanged;
  179. _leftPanel.Add (_treeView);
  180. _rightPanel.Add (_tableView);
  181. _btnToggleSplitterCollapse = new ()
  182. {
  183. X = Pos.Align (Alignment.Start, AlignmentModes.AddSpaceBetweenItems, alignmentGroupInput),
  184. Y = Pos.AnchorEnd (), Text = GetToggleSplitterText (false)
  185. };
  186. _btnToggleSplitterCollapse.Accepting += (s, e) =>
  187. {
  188. // Required otherwise the Save button clicks itself
  189. e.Handled = true;
  190. bool newState = !_leftPanel.Visible;
  191. _leftPanel.Visible = newState;
  192. _btnToggleSplitterCollapse.Text = GetToggleSplitterText (newState);
  193. SetNeedsLayout ();
  194. };
  195. _tbFind = new ()
  196. {
  197. X = Pos.Align (Alignment.Start, AlignmentModes.AddSpaceBetweenItems, alignmentGroupInput),
  198. CaptionColor = new (Color.Black),
  199. Width = 30,
  200. Y = Pos.Top (_btnToggleSplitterCollapse),
  201. HotKey = Key.F.WithAlt
  202. };
  203. _spinnerView = new ()
  204. { X = Pos.Align (Alignment.Start, AlignmentModes.AddSpaceBetweenItems, alignmentGroupInput), Y = Pos.AnchorEnd (1), Visible = false };
  205. _tbFind.TextChanged += (s, o) => RestartSearch ();
  206. _tbFind.KeyDown += (s, o) =>
  207. {
  208. if (o.KeyCode == KeyCode.Enter)
  209. {
  210. RestartSearch ();
  211. o.Handled = true;
  212. }
  213. if (o.KeyCode == KeyCode.Esc)
  214. {
  215. if (CancelSearch ())
  216. {
  217. o.Handled = true;
  218. }
  219. }
  220. };
  221. _tableView.Style.ShowHorizontalHeaderOverline = true;
  222. _tableView.Style.ShowVerticalCellLines = true;
  223. _tableView.Style.ShowVerticalHeaderLines = true;
  224. _tableView.Style.AlwaysShowHeaders = true;
  225. _tableView.Style.ShowHorizontalHeaderUnderline = true;
  226. _tableView.Style.ShowHorizontalScrollIndicators = true;
  227. _history = new (this);
  228. _tbPath.TextChanged += (s, e) => PathChanged ();
  229. _tableView.CellActivated += CellActivate;
  230. _tableView.KeyDown += (s, k) => k.Handled = TableView_KeyUp (k);
  231. _tableView.SelectedCellChanged += TableView_SelectedCellChanged;
  232. _tableView.KeyBindings.ReplaceCommands (Key.Home, Command.Start);
  233. _tableView.KeyBindings.ReplaceCommands (Key.End, Command.End);
  234. _tableView.KeyBindings.ReplaceCommands (Key.Home.WithShift, Command.StartExtend);
  235. _tableView.KeyBindings.ReplaceCommands (Key.End.WithShift, Command.EndExtend);
  236. AllowsMultipleSelection = false;
  237. UpdateNavigationVisibility ();
  238. Add (_tbPath);
  239. Add (_btnUp);
  240. Add (_btnBack);
  241. Add (_btnForward);
  242. Add (_leftPanel);
  243. Add (_rightPanel);
  244. Add (_btnToggleSplitterCollapse);
  245. Add (_tbFind);
  246. Add (_spinnerView);
  247. Add (_btnOk);
  248. Add (_btnCancel);
  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. Driver.AddStr (new (' ', feedbackPadLeft));
  359. Driver.AddStr (_feedback);
  360. Driver.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. _loaded = true;
  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. _btnToggleSplitterCollapse.Text = GetToggleSplitterText (false);
  380. _tbPath.Caption = Style.PathCaption;
  381. _tbFind.Caption = 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. Driver.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. SetNeedsDraw ();
  447. SetNeedsLayout ();
  448. }
  449. /// <inheritdoc/>
  450. protected override void Dispose (bool disposing)
  451. {
  452. _disposed = true;
  453. base.Dispose (disposing);
  454. CancelSearch ();
  455. }
  456. /// <summary>
  457. /// Gets a default dialog title, when <see cref="View.Title"/> is not set or empty, result of the function will be
  458. /// shown.
  459. /// </summary>
  460. protected virtual string GetDefaultTitle ()
  461. {
  462. List<string> titleParts = [Strings.fdOpen];
  463. if (MustExist)
  464. {
  465. titleParts.Add (Strings.fdExisting);
  466. }
  467. switch (OpenMode)
  468. {
  469. case OpenMode.File:
  470. titleParts.Add (Strings.fdFile);
  471. break;
  472. case OpenMode.Directory:
  473. titleParts.Add (Strings.fdDirectory);
  474. break;
  475. }
  476. return string.Join (' ', titleParts);
  477. }
  478. internal void ApplySort ()
  479. {
  480. FileSystemInfoStats [] stats = State?.Children ?? new FileSystemInfoStats [0];
  481. // This portion is never reordered (always .. at top then folders)
  482. IOrderedEnumerable<FileSystemInfoStats> forcedOrder = stats
  483. .OrderByDescending (f => f.IsParent)
  484. .ThenBy (f => f.IsDir ? -1 : 100);
  485. // This portion is flexible based on the column clicked (e.g. alphabetical)
  486. IOrderedEnumerable<FileSystemInfoStats> ordered =
  487. _currentSortIsAsc
  488. ? forcedOrder.ThenBy (
  489. f =>
  490. FileDialogTableSource.GetRawColumnValue (_currentSortColumn, f)
  491. )
  492. : forcedOrder.ThenByDescending (
  493. f =>
  494. FileDialogTableSource.GetRawColumnValue (_currentSortColumn, f)
  495. );
  496. State.Children = ordered.ToArray ();
  497. _tableView.Update ();
  498. }
  499. /// <summary>Changes the dialog such that <paramref name="d"/> is being explored.</summary>
  500. /// <param name="d"></param>
  501. /// <param name="addCurrentStateToHistory"></param>
  502. /// <param name="setPathText"></param>
  503. /// <param name="clearForward"></param>
  504. /// <param name="pathText">Optional alternate string to set path to.</param>
  505. internal void PushState (
  506. IDirectoryInfo d,
  507. bool addCurrentStateToHistory,
  508. bool setPathText = true,
  509. bool clearForward = true,
  510. string? pathText = null
  511. )
  512. {
  513. // no change of state
  514. if (d == State?.Directory)
  515. {
  516. return;
  517. }
  518. if (d.FullName == State?.Directory.FullName)
  519. {
  520. return;
  521. }
  522. PushState (
  523. new FileDialogState (d, this),
  524. addCurrentStateToHistory,
  525. setPathText,
  526. clearForward,
  527. pathText
  528. );
  529. }
  530. /// <summary>Select <paramref name="toRestore"/> in the table view (if present)</summary>
  531. /// <param name="toRestore"></param>
  532. internal void RestoreSelection (IFileSystemInfo toRestore)
  533. {
  534. _tableView.SelectedRow = State.Children.IndexOf (r => r.FileSystemInfo == toRestore);
  535. _tableView.EnsureSelectedCellIsVisible ();
  536. }
  537. internal void SortColumn (int col, bool isAsc)
  538. {
  539. // set a sort order
  540. _currentSortColumn = col;
  541. _currentSortIsAsc = isAsc;
  542. ApplySort ();
  543. }
  544. private void Accept (IEnumerable<FileSystemInfoStats> toMultiAccept)
  545. {
  546. if (!AllowsMultipleSelection)
  547. {
  548. return;
  549. }
  550. // Don't include ".." (IsParent) in multi-selections
  551. MultiSelected = toMultiAccept
  552. .Where (s => !s.IsParent)
  553. .Select (s => s.FileSystemInfo.FullName)
  554. .ToList ()
  555. .AsReadOnly ();
  556. Path = MultiSelected.Count == 1 ? MultiSelected [0] : string.Empty;
  557. FinishAccept ();
  558. }
  559. private void Accept (IFileInfo f)
  560. {
  561. if (!IsCompatibleWithOpenMode (f.FullName, out string reason))
  562. {
  563. _feedback = reason;
  564. SetNeedsDraw ();
  565. return;
  566. }
  567. Path = f.FullName;
  568. if (AllowsMultipleSelection)
  569. {
  570. MultiSelected = new List<string> { f.FullName }.AsReadOnly ();
  571. }
  572. FinishAccept ();
  573. }
  574. private void Accept (bool allowMulti)
  575. {
  576. if (allowMulti && TryAcceptMulti ())
  577. {
  578. return;
  579. }
  580. if (!IsCompatibleWithOpenMode (_tbPath.Text, out string reason))
  581. {
  582. if (reason is { })
  583. {
  584. _feedback = reason;
  585. SetNeedsDraw ();
  586. }
  587. return;
  588. }
  589. FinishAccept ();
  590. }
  591. private void AcceptIf (Key key, KeyCode isKey)
  592. {
  593. if (!key.Handled && key.KeyCode == isKey)
  594. {
  595. key.Handled = true;
  596. // User hit Enter in text box so probably wants the
  597. // contents of the text box as their selection not
  598. // whatever lingering selection is in TableView
  599. Accept (false);
  600. }
  601. }
  602. private void AllowedTypeMenuClicked (int idx)
  603. {
  604. IAllowedType allow = AllowedTypes [idx];
  605. for (var i = 0; i < AllowedTypes.Count; i++)
  606. {
  607. _allowedTypeMenuItems [i].Checked = i == idx;
  608. }
  609. _allowedTypeMenu.Title = allow.ToString ();
  610. CurrentFilter = allow;
  611. _tbPath.ClearAllSelection ();
  612. _tbPath.Autocomplete.ClearSuggestions ();
  613. if (State is { })
  614. {
  615. State.RefreshChildren ();
  616. WriteStateToTableView ();
  617. }
  618. }
  619. private string AspectGetter (object o)
  620. {
  621. var fsi = (IFileSystemInfo)o;
  622. if (o is IDirectoryInfo dir && _treeRoots.ContainsKey (dir))
  623. {
  624. // Directory has a special name e.g. 'Pictures'
  625. return _treeRoots [dir];
  626. }
  627. return (Style.IconProvider.GetIconWithOptionalSpace (fsi) + fsi.Name).Trim ();
  628. }
  629. private int CalculateOkButtonPosX (View? _)
  630. {
  631. if (!IsInitialized || !_btnOk.IsInitialized || !_btnCancel.IsInitialized)
  632. {
  633. return 0;
  634. }
  635. return Viewport.Width
  636. - _btnOk.Viewport.Width
  637. - _btnCancel.Viewport.Width
  638. - 1
  639. // TODO: Fiddle factor, seems the Viewport are wrong for someone
  640. - 2;
  641. }
  642. private bool CancelSearch ()
  643. {
  644. if (State is SearchState search)
  645. {
  646. return search.Cancel ();
  647. }
  648. return false;
  649. }
  650. private void CellActivate (object sender, CellActivatedEventArgs obj)
  651. {
  652. if (TryAcceptMulti ())
  653. {
  654. return;
  655. }
  656. FileSystemInfoStats stats = RowToStats (obj.Row);
  657. if (stats.FileSystemInfo is IDirectoryInfo d)
  658. {
  659. PushState (d, true);
  660. //if (d == State?.Directory || d.FullName == State?.Directory.FullName)
  661. //{
  662. // FinishAccept ();
  663. //}
  664. return;
  665. }
  666. if (stats.FileSystemInfo is IFileInfo f)
  667. {
  668. Accept (f);
  669. }
  670. }
  671. private void ClearFeedback () { _feedback = null; }
  672. private Scheme ColorGetter (CellColorGetterArgs args)
  673. {
  674. FileSystemInfoStats stats = RowToStats (args.RowIndex);
  675. if (!Style.UseColors)
  676. {
  677. return _tableView.GetScheme ();
  678. }
  679. Color color = Style.ColorProvider.GetColor (stats.FileSystemInfo) ?? new Color (Color.White);
  680. var black = new Color (Color.Black);
  681. // TODO: Add some kind of cache for this
  682. return new ()
  683. {
  684. Normal = new (color, black),
  685. HotNormal = new (color, black),
  686. Focus = new (black, color),
  687. HotFocus = new (black, color)
  688. };
  689. }
  690. private void Delete ()
  691. {
  692. IFileSystemInfo [] toDelete = GetFocusedFiles ();
  693. if (toDelete is { } && FileOperationsHandler.Delete (toDelete))
  694. {
  695. RefreshState ();
  696. }
  697. }
  698. private void FinishAccept ()
  699. {
  700. var e = new FilesSelectedEventArgs (this);
  701. FilesSelected?.Invoke (this, e);
  702. if (e.Cancel)
  703. {
  704. return;
  705. }
  706. // if user uses Path selection mode (e.g. Enter in text box)
  707. // then also copy to MultiSelected
  708. if (AllowsMultipleSelection && !MultiSelected.Any ())
  709. {
  710. MultiSelected = string.IsNullOrWhiteSpace (Path)
  711. ? Enumerable.Empty<string> ().ToList ().AsReadOnly ()
  712. : new List<string> { Path }.AsReadOnly ();
  713. }
  714. Canceled = false;
  715. if (Modal)
  716. {
  717. Application.RequestStop ();
  718. }
  719. }
  720. private string GetBackButtonText () { return Glyphs.LeftArrow + "-"; }
  721. private IFileSystemInfo [] GetFocusedFiles ()
  722. {
  723. if (!_tableView.HasFocus || !_tableView.CanFocus || FileOperationsHandler is null)
  724. {
  725. return null;
  726. }
  727. _tableView.EnsureValidSelection ();
  728. if (_tableView.SelectedRow < 0)
  729. {
  730. return null;
  731. }
  732. return _tableView.GetAllSelectedCells ()
  733. .Select (c => c.Y)
  734. .Distinct ()
  735. .Select (RowToStats)
  736. .Where (s => !s.IsParent)
  737. .Select (d => d.FileSystemInfo)
  738. .ToArray ();
  739. }
  740. private string GetForwardButtonText () { return "-" + Glyphs.RightArrow; }
  741. private string GetProposedNewSortOrder (int clickedCol, out bool isAsc)
  742. {
  743. // work out new sort order
  744. if (_currentSortColumn == clickedCol && _currentSortIsAsc)
  745. {
  746. isAsc = false;
  747. return string.Format (Strings.fdCtxSortDesc, _tableView.Table.ColumnNames [clickedCol]);
  748. }
  749. isAsc = true;
  750. return string.Format (Strings.fdCtxSortAsc, _tableView.Table.ColumnNames [clickedCol]);
  751. }
  752. private string GetToggleSplitterText (bool isExpanded)
  753. {
  754. return isExpanded
  755. ? new ((char)Glyphs.LeftArrow.Value, 2)
  756. : new string ((char)Glyphs.RightArrow.Value, 2);
  757. }
  758. private string GetUpButtonText () { return Style.UseUnicodeCharacters ? "◭" : "▲"; }
  759. private void HideColumn (int clickedCol)
  760. {
  761. ColumnStyle style = _tableView.Style.GetOrCreateColumnStyle (clickedCol);
  762. style.Visible = false;
  763. _tableView.Update ();
  764. }
  765. private bool IsCompatibleWithAllowedExtensions (string path)
  766. {
  767. // no restrictions
  768. if (!AllowedTypes.Any ())
  769. {
  770. return true;
  771. }
  772. return AllowedTypes.Any (t => t.IsAllowed (path));
  773. }
  774. private bool IsCompatibleWithOpenMode (string s, out string reason)
  775. {
  776. reason = null;
  777. if (string.IsNullOrWhiteSpace (s))
  778. {
  779. return false;
  780. }
  781. if (!IsCompatibleWithAllowedExtensions (s))
  782. {
  783. reason = Style.WrongFileTypeFeedback;
  784. return false;
  785. }
  786. switch (OpenMode)
  787. {
  788. case OpenMode.Directory:
  789. if (MustExist && !Directory.Exists (s))
  790. {
  791. reason = Style.DirectoryMustExistFeedback;
  792. return false;
  793. }
  794. if (File.Exists (s))
  795. {
  796. reason = Style.FileAlreadyExistsFeedback;
  797. return false;
  798. }
  799. return true;
  800. case OpenMode.File:
  801. if (MustExist && !File.Exists (s))
  802. {
  803. reason = Style.FileMustExistFeedback;
  804. return false;
  805. }
  806. if (Directory.Exists (s))
  807. {
  808. reason = Style.DirectoryAlreadyExistsFeedback;
  809. return false;
  810. }
  811. return true;
  812. case OpenMode.Mixed:
  813. if (MustExist && !File.Exists (s) && !Directory.Exists (s))
  814. {
  815. reason = Style.FileOrDirectoryMustExistFeedback;
  816. return false;
  817. }
  818. return true;
  819. default: throw new ArgumentOutOfRangeException (nameof (OpenMode));
  820. }
  821. }
  822. /// <summary>Returns true if any <see cref="AllowedTypes"/> matches <paramref name="file"/>.</summary>
  823. /// <param name="file"></param>
  824. /// <returns></returns>
  825. private bool MatchesAllowedTypes (IFileInfo file) { return AllowedTypes.Any (t => t.IsAllowed (file.FullName)); }
  826. /// <summary>
  827. /// If <see cref="TableView.MultiSelect"/> is this returns a union of all <see cref="FileSystemInfoStats"/> in the
  828. /// selection.
  829. /// </summary>
  830. /// <returns></returns>
  831. private IEnumerable<FileSystemInfoStats> MultiRowToStats ()
  832. {
  833. HashSet<FileSystemInfoStats> toReturn = new ();
  834. if (AllowsMultipleSelection && _tableView.MultiSelectedRegions.Any ())
  835. {
  836. foreach (Point p in _tableView.GetAllSelectedCells ())
  837. {
  838. FileSystemInfoStats add = State?.Children [p.Y];
  839. if (add is { })
  840. {
  841. toReturn.Add (add);
  842. }
  843. }
  844. }
  845. return toReturn;
  846. }
  847. private void New ()
  848. {
  849. if (State is { })
  850. {
  851. IFileSystemInfo created = FileOperationsHandler.New (_fileSystem, State.Directory);
  852. if (created is { })
  853. {
  854. RefreshState ();
  855. RestoreSelection (created);
  856. }
  857. }
  858. }
  859. private void OnTableViewMouseClick (object sender, MouseEventArgs e)
  860. {
  861. Point? clickedCell = _tableView.ScreenToCell (e.Position.X, e.Position.Y, out int? clickedCol);
  862. if (clickedCol is { })
  863. {
  864. if (e.Flags.HasFlag (MouseFlags.Button1Clicked))
  865. {
  866. // left click in a header
  867. SortColumn (clickedCol.Value);
  868. }
  869. else if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
  870. {
  871. // right click in a header
  872. ShowHeaderContextMenu (clickedCol.Value, e);
  873. }
  874. }
  875. else
  876. {
  877. if (clickedCell is { } && e.Flags.HasFlag (MouseFlags.Button3Clicked))
  878. {
  879. // right click in rest of table
  880. ShowCellContextMenu (clickedCell, e);
  881. }
  882. }
  883. }
  884. private void PathChanged ()
  885. {
  886. // avoid re-entry
  887. if (_pushingState)
  888. {
  889. return;
  890. }
  891. string path = _tbPath.Text;
  892. if (string.IsNullOrWhiteSpace (path))
  893. {
  894. return;
  895. }
  896. IDirectoryInfo dir = StringToDirectoryInfo (path);
  897. if (dir.Exists)
  898. {
  899. PushState (dir, true, false);
  900. }
  901. else if (dir.Parent?.Exists ?? false)
  902. {
  903. PushState (dir.Parent, true, false);
  904. }
  905. _tbPath.Autocomplete.GenerateSuggestions (
  906. new AutocompleteFilepathContext (_tbPath.Text, _tbPath.CursorPosition, State)
  907. );
  908. }
  909. private void PushState (
  910. FileDialogState newState,
  911. bool addCurrentStateToHistory,
  912. bool setPathText = true,
  913. bool clearForward = true,
  914. string? pathText = null
  915. )
  916. {
  917. if (State is SearchState search)
  918. {
  919. search.Cancel ();
  920. }
  921. try
  922. {
  923. _pushingState = true;
  924. // push the old state to history
  925. if (addCurrentStateToHistory)
  926. {
  927. _history.Push (State, clearForward);
  928. }
  929. _tbPath.Autocomplete.ClearSuggestions ();
  930. if (pathText is { })
  931. {
  932. Path = pathText;
  933. }
  934. else if (setPathText)
  935. {
  936. SetPathToSelectedObject (newState.Directory);
  937. }
  938. State = newState;
  939. _tbPath.Autocomplete.GenerateSuggestions (
  940. new AutocompleteFilepathContext (_tbPath.Text, _tbPath.CursorPosition, State)
  941. );
  942. WriteStateToTableView ();
  943. if (clearForward)
  944. {
  945. _history.ClearForward ();
  946. }
  947. _tableView.RowOffset = 0;
  948. _tableView.SelectedRow = 0;
  949. SetNeedsDraw ();
  950. UpdateNavigationVisibility ();
  951. }
  952. finally
  953. {
  954. _pushingState = false;
  955. }
  956. ClearFeedback ();
  957. }
  958. private void RefreshState ()
  959. {
  960. State.RefreshChildren ();
  961. PushState (State, false, false, false);
  962. }
  963. private void Rename ()
  964. {
  965. IFileSystemInfo [] toRename = GetFocusedFiles ();
  966. if (toRename?.Length == 1)
  967. {
  968. IFileSystemInfo newNamed = FileOperationsHandler.Rename (_fileSystem, toRename.Single ());
  969. if (newNamed is { })
  970. {
  971. RefreshState ();
  972. RestoreSelection (newNamed);
  973. }
  974. }
  975. }
  976. // /// <inheritdoc/>
  977. // public override bool OnHotKey (KeyEventArgs keyEvent)
  978. // {
  979. //#if BROKE_IN_2927
  980. // // BUGBUG: Ctrl-F is forward in a TextField.
  981. // if (this.NavigateIf (keyEvent, Key.Alt | Key.F, this.tbFind)) {
  982. // return true;
  983. // }
  984. //#endif
  985. // ClearFeedback ();
  986. // if (allowedTypeMenuBar is { } &&
  987. // keyEvent.ConsoleDriverKey == Key.Tab &&
  988. // allowedTypeMenuBar.IsMenuOpen) {
  989. // allowedTypeMenuBar.CloseMenu (false, false, false);
  990. // }
  991. // return base.OnHotKey (keyEvent);
  992. // }
  993. private void RestartSearch ()
  994. {
  995. if (_disposed || State?.Directory is null)
  996. {
  997. return;
  998. }
  999. if (State is SearchState oldSearch)
  1000. {
  1001. oldSearch.Cancel ();
  1002. }
  1003. // user is clearing search terms
  1004. if (_tbFind.Text is null || _tbFind.Text.Length == 0)
  1005. {
  1006. // Wait for search cancellation (if any) to finish
  1007. // then push the current dir state
  1008. lock (_onlyOneSearchLock)
  1009. {
  1010. PushState (new FileDialogState (State.Directory, this), false);
  1011. }
  1012. return;
  1013. }
  1014. PushState (new SearchState (State?.Directory, this, _tbFind.Text), true);
  1015. }
  1016. private FileSystemInfoStats RowToStats (int rowIndex) { return State?.Children [rowIndex]; }
  1017. private void ShowCellContextMenu (Point? clickedCell, MouseEventArgs e)
  1018. {
  1019. if (clickedCell is null)
  1020. {
  1021. return;
  1022. }
  1023. PopoverMenu? contextMenu = new (
  1024. [
  1025. new (Strings.fdCtxNew, string.Empty, New),
  1026. new (Strings.fdCtxRename, string.Empty, Rename),
  1027. new (Strings.fdCtxDelete, string.Empty, Delete)
  1028. ]);
  1029. _tableView.SetSelection (clickedCell.Value.X, clickedCell.Value.Y, false);
  1030. // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
  1031. // and the context menu is disposed when it is closed.
  1032. Application.Popover?.Register (contextMenu);
  1033. contextMenu?.MakeVisible (e.ScreenPosition);
  1034. }
  1035. private void ShowHeaderContextMenu (int clickedCol, MouseEventArgs e)
  1036. {
  1037. string sort = GetProposedNewSortOrder (clickedCol, out bool isAsc);
  1038. PopoverMenu? contextMenu = new (
  1039. [
  1040. new (
  1041. string.Format (
  1042. Strings.fdCtxHide,
  1043. StripArrows (_tableView.Table.ColumnNames [clickedCol])
  1044. ),
  1045. string.Empty,
  1046. () => HideColumn (clickedCol)
  1047. ),
  1048. new (
  1049. StripArrows (sort),
  1050. string.Empty,
  1051. () => SortColumn (clickedCol, isAsc))
  1052. ]
  1053. );
  1054. // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
  1055. // and the context menu is disposed when it is closed.
  1056. Application.Popover?.Register (contextMenu);
  1057. contextMenu?.MakeVisible (e.ScreenPosition);
  1058. }
  1059. private void SortColumn (int clickedCol)
  1060. {
  1061. GetProposedNewSortOrder (clickedCol, out bool isAsc);
  1062. SortColumn (clickedCol, isAsc);
  1063. _tableView.Table =
  1064. new FileDialogTableSource (this, State, Style, _currentSortColumn, _currentSortIsAsc);
  1065. }
  1066. private IDirectoryInfo StringToDirectoryInfo (string path)
  1067. {
  1068. // if you pass new DirectoryInfo("C:") you get a weird object
  1069. // where the FullName is in fact the current working directory.
  1070. // really not what most users would expect
  1071. if (Regex.IsMatch (path, "^\\w:$"))
  1072. {
  1073. return _fileSystem.DirectoryInfo.New (path + _fileSystem.Path.DirectorySeparatorChar);
  1074. }
  1075. return _fileSystem.DirectoryInfo.New (path);
  1076. }
  1077. private static string StripArrows (string columnName) { return columnName.Replace (" (▼)", string.Empty).Replace (" (▲)", string.Empty); }
  1078. private void SuppressIfBadChar (Key k)
  1079. {
  1080. // don't let user type bad letters
  1081. var ch = (char)k;
  1082. if (_badChars.Contains (ch))
  1083. {
  1084. k.Handled = true;
  1085. }
  1086. }
  1087. private bool TableView_KeyUp (Key keyEvent)
  1088. {
  1089. if (keyEvent.KeyCode == KeyCode.Backspace)
  1090. {
  1091. return _history.Back ();
  1092. }
  1093. if (keyEvent.KeyCode == (KeyCode.ShiftMask | KeyCode.Backspace))
  1094. {
  1095. return _history.Forward ();
  1096. }
  1097. if (keyEvent.KeyCode == KeyCode.Delete)
  1098. {
  1099. Delete ();
  1100. return true;
  1101. }
  1102. if (keyEvent.KeyCode == (KeyCode.CtrlMask | KeyCode.R))
  1103. {
  1104. Rename ();
  1105. return true;
  1106. }
  1107. if (keyEvent.KeyCode == (KeyCode.CtrlMask | KeyCode.N))
  1108. {
  1109. New ();
  1110. return true;
  1111. }
  1112. return false;
  1113. }
  1114. private void TableView_SelectedCellChanged (object sender, SelectedCellChangedEventArgs obj)
  1115. {
  1116. if (!_tableView.HasFocus || obj.NewRow == -1 || obj.Table.Rows == 0)
  1117. {
  1118. return;
  1119. }
  1120. if (_tableView.MultiSelect && _tableView.MultiSelectedRegions.Any ())
  1121. {
  1122. return;
  1123. }
  1124. FileSystemInfoStats stats = RowToStats (obj.NewRow);
  1125. if (stats is null)
  1126. {
  1127. return;
  1128. }
  1129. IFileSystemInfo dest;
  1130. if (stats.IsParent)
  1131. {
  1132. dest = State.Directory;
  1133. }
  1134. else
  1135. {
  1136. dest = stats.FileSystemInfo;
  1137. }
  1138. try
  1139. {
  1140. _pushingState = true;
  1141. SetPathToSelectedObject (dest);
  1142. State.Selected = stats;
  1143. _tbPath.Autocomplete.ClearSuggestions ();
  1144. }
  1145. finally
  1146. {
  1147. _pushingState = false;
  1148. }
  1149. }
  1150. private void TreeView_SelectionChanged (object sender, SelectionChangedEventArgs<IFileSystemInfo> e)
  1151. {
  1152. SetPathToSelectedObject (e.NewValue);
  1153. }
  1154. private void SetPathToSelectedObject (IFileSystemInfo? selected)
  1155. {
  1156. if (selected is null)
  1157. {
  1158. return;
  1159. }
  1160. if (selected is IDirectoryInfo && Style.PreserveFilenameOnDirectoryChanges)
  1161. {
  1162. if (!string.IsNullOrWhiteSpace (Path) && !_fileSystem.Directory.Exists (Path))
  1163. {
  1164. var currentFile = _fileSystem.Path.GetFileName (Path);
  1165. if (!string.IsNullOrWhiteSpace (currentFile))
  1166. {
  1167. Path = _fileSystem.Path.Combine (selected.FullName, currentFile);
  1168. return;
  1169. }
  1170. }
  1171. }
  1172. Path = selected.FullName;
  1173. }
  1174. private bool TryAcceptMulti ()
  1175. {
  1176. IEnumerable<FileSystemInfoStats> multi = MultiRowToStats ();
  1177. string reason = null;
  1178. if (!multi.Any ())
  1179. {
  1180. return false;
  1181. }
  1182. if (multi.All (
  1183. m => IsCompatibleWithOpenMode (
  1184. m.FileSystemInfo.FullName,
  1185. out reason
  1186. )
  1187. ))
  1188. {
  1189. Accept (multi);
  1190. return true;
  1191. }
  1192. if (reason is { })
  1193. {
  1194. _feedback = reason;
  1195. SetNeedsDraw ();
  1196. }
  1197. return false;
  1198. }
  1199. private void UpdateNavigationVisibility ()
  1200. {
  1201. _btnBack.Visible = _history.CanBack ();
  1202. _btnForward.Visible = _history.CanForward ();
  1203. _btnUp.Visible = _history.CanUp ();
  1204. }
  1205. private void WriteStateToTableView ()
  1206. {
  1207. if (State is null)
  1208. {
  1209. return;
  1210. }
  1211. _tableView.Table =
  1212. new FileDialogTableSource (this, State, Style, _currentSortColumn, _currentSortIsAsc);
  1213. ApplySort ();
  1214. _tableView.Update ();
  1215. }
  1216. /// <summary>State representing a recursive search from <see cref="FileDialogState.Directory"/> downwards.</summary>
  1217. internal class SearchState : FileDialogState
  1218. {
  1219. // TODO: Add thread safe child adding
  1220. private readonly List<FileSystemInfoStats> _found = [];
  1221. private readonly object _oLockFound = new ();
  1222. private readonly CancellationTokenSource _token = new ();
  1223. private bool _cancel;
  1224. private bool _finished;
  1225. public SearchState (IDirectoryInfo dir, FileDialog parent, string searchTerms) : base (dir, parent)
  1226. {
  1227. parent.SearchMatcher.Initialize (searchTerms);
  1228. Children = new FileSystemInfoStats [0];
  1229. BeginSearch ();
  1230. }
  1231. /// <summary>
  1232. /// Cancels the current search (if any). Returns true if a search was running and cancellation was successfully
  1233. /// set.
  1234. /// </summary>
  1235. /// <returns></returns>
  1236. internal bool Cancel ()
  1237. {
  1238. bool alreadyCancelled = _token.IsCancellationRequested || _cancel;
  1239. _cancel = true;
  1240. _token.Cancel ();
  1241. return !alreadyCancelled;
  1242. }
  1243. internal override void RefreshChildren () { }
  1244. private void BeginSearch ()
  1245. {
  1246. Task.Run (
  1247. () =>
  1248. {
  1249. RecursiveFind (Directory);
  1250. _finished = true;
  1251. }
  1252. );
  1253. Task.Run (() => { UpdateChildren (); });
  1254. }
  1255. private void RecursiveFind (IDirectoryInfo directory)
  1256. {
  1257. foreach (FileSystemInfoStats f in GetChildren (directory))
  1258. {
  1259. if (_cancel)
  1260. {
  1261. return;
  1262. }
  1263. if (f.IsParent)
  1264. {
  1265. continue;
  1266. }
  1267. lock (_oLockFound)
  1268. {
  1269. if (_found.Count >= MaxSearchResults)
  1270. {
  1271. _finished = true;
  1272. return;
  1273. }
  1274. }
  1275. if (Parent.SearchMatcher.IsMatch (f.FileSystemInfo))
  1276. {
  1277. lock (_oLockFound)
  1278. {
  1279. _found.Add (f);
  1280. }
  1281. }
  1282. if (f.FileSystemInfo is IDirectoryInfo sub)
  1283. {
  1284. RecursiveFind (sub);
  1285. }
  1286. }
  1287. }
  1288. private void UpdateChildren ()
  1289. {
  1290. lock (Parent._onlyOneSearchLock)
  1291. {
  1292. while (!_cancel && !_finished)
  1293. {
  1294. try
  1295. {
  1296. Task.Delay (250).Wait (_token.Token);
  1297. }
  1298. catch (OperationCanceledException)
  1299. {
  1300. _cancel = true;
  1301. }
  1302. if (_cancel || _finished)
  1303. {
  1304. break;
  1305. }
  1306. UpdateChildrenToFound ();
  1307. }
  1308. if (_finished && !_cancel)
  1309. {
  1310. UpdateChildrenToFound ();
  1311. }
  1312. Application.Invoke (() => { Parent._spinnerView.Visible = false; });
  1313. }
  1314. }
  1315. private void UpdateChildrenToFound ()
  1316. {
  1317. lock (_oLockFound)
  1318. {
  1319. Children = _found.ToArray ();
  1320. }
  1321. Application.Invoke (
  1322. () =>
  1323. {
  1324. Parent._tbPath.Autocomplete.GenerateSuggestions (
  1325. new AutocompleteFilepathContext (
  1326. Parent._tbPath.Text,
  1327. Parent._tbPath.CursorPosition,
  1328. this
  1329. )
  1330. );
  1331. Parent.WriteStateToTableView ();
  1332. Parent._spinnerView.Visible = true;
  1333. Parent._spinnerView.SetNeedsDraw ();
  1334. }
  1335. );
  1336. }
  1337. }
  1338. bool IDesignable.EnableForDesign ()
  1339. {
  1340. Modal = false;
  1341. OnLoaded ();
  1342. return true;
  1343. }
  1344. }