FileDialog.cs 50 KB

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