2
0

FileDialog.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. //
  2. // FileDialog.cs: File system dialogs for open and save
  3. //
  4. // TODO:
  5. // * Add directory selector
  6. // * Implement subclasses
  7. // * Figure out why message text does not show
  8. // * Remove the extra space when message does not show
  9. // * Use a line separator to show the file listing, so we can use same colors as the rest
  10. // * DirListView: Add mouse support
  11. using System;
  12. using System.Collections.Generic;
  13. using NStack;
  14. using System.IO;
  15. using System.Linq;
  16. using Terminal.Gui.Resources;
  17. namespace Terminal.Gui {
  18. internal class DirListView : View {
  19. int top, selected;
  20. DirectoryInfo dirInfo;
  21. FileSystemWatcher watcher;
  22. List<(string, bool, bool)> infos;
  23. internal bool canChooseFiles = true;
  24. internal bool canChooseDirectories = false;
  25. internal bool allowsMultipleSelection = false;
  26. FileDialog host;
  27. public DirListView (FileDialog host)
  28. {
  29. infos = new List<(string, bool, bool)> ();
  30. CanFocus = true;
  31. this.host = host;
  32. }
  33. bool IsAllowed (FileSystemInfo fsi)
  34. {
  35. if (fsi.Attributes.HasFlag (FileAttributes.Directory))
  36. return true;
  37. if (allowedFileTypes == null)
  38. return true;
  39. foreach (var ft in allowedFileTypes)
  40. if (fsi.Name.EndsWith (ft, StringComparison.InvariantCultureIgnoreCase) || ft == ".*")
  41. return true;
  42. return false;
  43. }
  44. internal bool Reload (ustring value = null)
  45. {
  46. bool valid = false;
  47. try {
  48. dirInfo = new DirectoryInfo (value == null ? directory.ToString () : value.ToString ());
  49. // Dispose of the old watcher
  50. watcher?.Dispose ();
  51. watcher = new FileSystemWatcher (dirInfo.FullName);
  52. watcher.NotifyFilter = NotifyFilters.Attributes
  53. | NotifyFilters.CreationTime
  54. | NotifyFilters.DirectoryName
  55. | NotifyFilters.FileName
  56. | NotifyFilters.LastAccess
  57. | NotifyFilters.LastWrite
  58. | NotifyFilters.Security
  59. | NotifyFilters.Size;
  60. watcher.Changed += Watcher_Changed;
  61. watcher.Created += Watcher_Changed;
  62. watcher.Deleted += Watcher_Changed;
  63. watcher.Renamed += Watcher_Changed;
  64. watcher.Error += Watcher_Error;
  65. watcher.EnableRaisingEvents = true;
  66. infos = (from x in dirInfo.GetFileSystemInfos ()
  67. where IsAllowed (x) && (!canChooseFiles ? x.Attributes.HasFlag (FileAttributes.Directory) : true)
  68. orderby (!x.Attributes.HasFlag (FileAttributes.Directory)) + x.Name
  69. select (x.Name, x.Attributes.HasFlag (FileAttributes.Directory), false)).ToList ();
  70. infos.Insert (0, ("..", true, false));
  71. top = 0;
  72. selected = 0;
  73. valid = true;
  74. } catch (Exception ex) {
  75. switch (ex) {
  76. case DirectoryNotFoundException _:
  77. case ArgumentException _:
  78. dirInfo = null;
  79. watcher = null;
  80. infos.Clear ();
  81. valid = true;
  82. break;
  83. default:
  84. valid = false;
  85. break;
  86. }
  87. } finally {
  88. if (valid) {
  89. SetNeedsDisplay ();
  90. }
  91. }
  92. return valid;
  93. }
  94. private bool _disposedValue;
  95. protected override void Dispose (bool disposing)
  96. {
  97. if (!_disposedValue) {
  98. if (disposing) {
  99. watcher?.Dispose ();
  100. }
  101. _disposedValue = true;
  102. }
  103. // Call base class implementation.
  104. base.Dispose (disposing);
  105. }
  106. void Watcher_Error (object sender, ErrorEventArgs e)
  107. {
  108. Application.MainLoop.Invoke (() => Reload ());
  109. }
  110. void Watcher_Changed (object sender, FileSystemEventArgs e)
  111. {
  112. Application.MainLoop.Invoke (() => Reload ());
  113. }
  114. ustring directory;
  115. public ustring Directory {
  116. get => directory;
  117. set {
  118. if (directory == value) {
  119. return;
  120. }
  121. if (Reload (value)) {
  122. directory = value;
  123. }
  124. }
  125. }
  126. public override void PositionCursor ()
  127. {
  128. Move (0, selected - top);
  129. }
  130. int lastSelected;
  131. bool shiftOnWheel;
  132. public override bool MouseEvent (MouseEvent me)
  133. {
  134. if ((me.Flags & (MouseFlags.Button1Clicked | MouseFlags.Button1DoubleClicked |
  135. MouseFlags.WheeledUp | MouseFlags.WheeledDown)) == 0)
  136. return false;
  137. if (!HasFocus)
  138. SetFocus ();
  139. if (infos == null)
  140. return false;
  141. if (me.Y + top >= infos.Count)
  142. return true;
  143. int lastSelectedCopy = shiftOnWheel ? lastSelected : selected;
  144. switch (me.Flags) {
  145. case MouseFlags.Button1Clicked:
  146. SetSelected (me);
  147. OnSelectionChanged ();
  148. SetNeedsDisplay ();
  149. break;
  150. case MouseFlags.Button1DoubleClicked:
  151. UnMarkAll ();
  152. SetSelected (me);
  153. if (ExecuteSelection ()) {
  154. host.canceled = false;
  155. Application.RequestStop ();
  156. }
  157. return true;
  158. case MouseFlags.Button1Clicked | MouseFlags.ButtonShift:
  159. SetSelected (me);
  160. if (shiftOnWheel)
  161. lastSelected = lastSelectedCopy;
  162. shiftOnWheel = false;
  163. PerformMultipleSelection (lastSelected);
  164. return true;
  165. case MouseFlags.Button1Clicked | MouseFlags.ButtonCtrl:
  166. SetSelected (me);
  167. PerformMultipleSelection ();
  168. return true;
  169. case MouseFlags.WheeledUp:
  170. SetSelected (me);
  171. selected = lastSelected;
  172. MoveUp ();
  173. return true;
  174. case MouseFlags.WheeledDown:
  175. SetSelected (me);
  176. selected = lastSelected;
  177. MoveDown ();
  178. return true;
  179. case MouseFlags.WheeledUp | MouseFlags.ButtonShift:
  180. SetSelected (me);
  181. selected = lastSelected;
  182. lastSelected = lastSelectedCopy;
  183. shiftOnWheel = true;
  184. MoveUp ();
  185. return true;
  186. case MouseFlags.WheeledDown | MouseFlags.ButtonShift:
  187. SetSelected (me);
  188. selected = lastSelected;
  189. lastSelected = lastSelectedCopy;
  190. shiftOnWheel = true;
  191. MoveDown ();
  192. return true;
  193. }
  194. return true;
  195. }
  196. void UnMarkAll ()
  197. {
  198. for (int i = 0; i < infos.Count; i++) {
  199. if (infos [i].Item3) {
  200. infos [i] = (infos [i].Item1, infos [i].Item2, false);
  201. }
  202. }
  203. }
  204. void SetSelected (MouseEvent me)
  205. {
  206. lastSelected = selected;
  207. selected = top + me.Y;
  208. }
  209. void DrawString (int line, string str)
  210. {
  211. var f = Frame;
  212. var width = f.Width;
  213. var ustr = ustring.Make (str);
  214. Move (allowsMultipleSelection ? 3 : 2, line);
  215. int byteLen = ustr.Length;
  216. int used = allowsMultipleSelection ? 2 : 1;
  217. for (int i = 0; i < byteLen;) {
  218. (var rune, var size) = Utf8.DecodeRune (ustr, i, i - byteLen);
  219. var count = Rune.ColumnWidth (rune);
  220. if (used + count >= width)
  221. break;
  222. Driver.AddRune (rune);
  223. used += count;
  224. i += size;
  225. }
  226. for (; used < width - 1; used++) {
  227. Driver.AddRune (' ');
  228. }
  229. }
  230. public override void Redraw (Rect bounds)
  231. {
  232. var current = ColorScheme.Focus;
  233. Driver.SetAttribute (current);
  234. Move (0, 0);
  235. var f = Frame;
  236. var item = top;
  237. bool focused = HasFocus;
  238. var width = bounds.Width;
  239. for (int row = 0; row < f.Height; row++, item++) {
  240. bool isSelected = item == selected;
  241. Move (0, row);
  242. var newcolor = focused ? (isSelected ? ColorScheme.HotNormal : ColorScheme.Focus)
  243. : Enabled ? ColorScheme.Focus : ColorScheme.Disabled;
  244. if (newcolor != current) {
  245. Driver.SetAttribute (newcolor);
  246. current = newcolor;
  247. }
  248. if (item >= infos.Count) {
  249. for (int c = 0; c < f.Width; c++)
  250. Driver.AddRune (' ');
  251. continue;
  252. }
  253. var fi = infos [item];
  254. Driver.AddRune (isSelected ? '>' : ' ');
  255. if (allowsMultipleSelection)
  256. Driver.AddRune (fi.Item3 ? '*' : ' ');
  257. if (fi.Item2)
  258. Driver.AddRune ('/');
  259. else
  260. Driver.AddRune (' ');
  261. DrawString (row, fi.Item1);
  262. }
  263. }
  264. public Action<(string, bool)> SelectedChanged { get; set; }
  265. public Action<ustring> DirectoryChanged { get; set; }
  266. public Action<ustring> FileChanged { get; set; }
  267. string splitString = ",";
  268. void OnSelectionChanged ()
  269. {
  270. if (allowsMultipleSelection) {
  271. if (FilePaths.Count > 0) {
  272. FileChanged?.Invoke (string.Join (splitString, GetFilesName (FilePaths)));
  273. } else {
  274. FileChanged?.Invoke (infos [selected].Item2 && !canChooseDirectories ? "" : Path.GetFileName (infos [selected].Item1));
  275. }
  276. } else {
  277. var sel = infos [selected];
  278. SelectedChanged?.Invoke ((sel.Item1, sel.Item2));
  279. }
  280. }
  281. List<string> GetFilesName (IReadOnlyList<string> files)
  282. {
  283. List<string> filesName = new List<string> ();
  284. foreach (var file in files) {
  285. filesName.Add (Path.GetFileName (file));
  286. }
  287. return filesName;
  288. }
  289. public bool GetValidFilesName (string files, out string result)
  290. {
  291. result = string.Empty;
  292. if (infos?.Count == 0) {
  293. return false;
  294. }
  295. var valid = true;
  296. IReadOnlyList<string> filesList = new List<string> (files.Split (splitString.ToArray (), StringSplitOptions.None));
  297. var filesName = new List<string> ();
  298. UnMarkAll ();
  299. foreach (var file in filesList) {
  300. if (!allowsMultipleSelection && filesName.Count > 0) {
  301. break;
  302. }
  303. var idx = infos.IndexOf (x => x.Item1.IndexOf (file, StringComparison.OrdinalIgnoreCase) >= 0);
  304. if (idx > -1 && string.Equals (infos [idx].Item1, file, StringComparison.OrdinalIgnoreCase)) {
  305. if (canChooseDirectories && !canChooseFiles && !infos [idx].Item2) {
  306. valid = false;
  307. }
  308. if (allowsMultipleSelection && !infos [idx].Item3) {
  309. infos [idx] = (infos [idx].Item1, infos [idx].Item2, true);
  310. }
  311. if (!allowsMultipleSelection) {
  312. selected = idx;
  313. }
  314. filesName.Add (Path.GetFileName (infos [idx].Item1));
  315. } else if (idx > -1) {
  316. valid = false;
  317. filesName.Add (Path.GetFileName (file));
  318. }
  319. }
  320. result = string.Join (splitString, filesName);
  321. if (string.IsNullOrEmpty (result)) {
  322. valid = false;
  323. }
  324. return valid;
  325. }
  326. public override bool ProcessKey (KeyEvent keyEvent)
  327. {
  328. switch (keyEvent.Key) {
  329. case Key.CursorUp:
  330. case Key.P | Key.CtrlMask:
  331. MoveUp ();
  332. return true;
  333. case Key.CursorDown:
  334. case Key.N | Key.CtrlMask:
  335. MoveDown ();
  336. return true;
  337. case Key.V | Key.CtrlMask:
  338. case Key.PageDown:
  339. var n = (selected + Frame.Height);
  340. if (n > infos.Count)
  341. n = infos.Count - 1;
  342. if (n != selected) {
  343. selected = n;
  344. if (infos.Count >= Frame.Height)
  345. top = selected;
  346. else
  347. top = 0;
  348. OnSelectionChanged ();
  349. SetNeedsDisplay ();
  350. }
  351. return true;
  352. case Key.Enter:
  353. UnMarkAll ();
  354. if (ExecuteSelection ())
  355. return false;
  356. else
  357. return true;
  358. case Key.PageUp:
  359. n = (selected - Frame.Height);
  360. if (n < 0)
  361. n = 0;
  362. if (n != selected) {
  363. selected = n;
  364. top = selected;
  365. OnSelectionChanged ();
  366. SetNeedsDisplay ();
  367. }
  368. return true;
  369. case Key.Space:
  370. case Key.T | Key.CtrlMask:
  371. PerformMultipleSelection ();
  372. return true;
  373. case Key.Home:
  374. MoveFirst ();
  375. return true;
  376. case Key.End:
  377. MoveLast ();
  378. return true;
  379. }
  380. return base.ProcessKey (keyEvent);
  381. }
  382. void MoveLast ()
  383. {
  384. selected = infos.Count - 1;
  385. top = infos.Count () - 1;
  386. OnSelectionChanged ();
  387. SetNeedsDisplay ();
  388. }
  389. void MoveFirst ()
  390. {
  391. selected = 0;
  392. top = 0;
  393. OnSelectionChanged ();
  394. SetNeedsDisplay ();
  395. }
  396. void MoveDown ()
  397. {
  398. if (selected + 1 < infos.Count) {
  399. selected++;
  400. if (selected >= top + Frame.Height)
  401. top++;
  402. OnSelectionChanged ();
  403. SetNeedsDisplay ();
  404. }
  405. }
  406. void MoveUp ()
  407. {
  408. if (selected > 0) {
  409. selected--;
  410. if (selected < top)
  411. top = selected;
  412. OnSelectionChanged ();
  413. SetNeedsDisplay ();
  414. }
  415. }
  416. internal bool ExecuteSelection (bool navigateFolder = true)
  417. {
  418. if (infos.Count == 0) {
  419. return false;
  420. }
  421. var isDir = infos [selected].Item2;
  422. if (isDir) {
  423. Directory = Path.GetFullPath (Path.Combine (Path.GetFullPath (Directory.ToString ()), infos [selected].Item1));
  424. DirectoryChanged?.Invoke (Directory);
  425. if (canChooseDirectories && !navigateFolder) {
  426. return true;
  427. }
  428. } else {
  429. OnSelectionChanged ();
  430. if (canChooseFiles) {
  431. // Ensures that at least one file is selected.
  432. if (FilePaths.Count == 0)
  433. PerformMultipleSelection ();
  434. // Let the OK handler take it over
  435. return true;
  436. }
  437. // No files allowed, do not let the default handler take it.
  438. }
  439. return false;
  440. }
  441. void PerformMultipleSelection (int? firstSelected = null)
  442. {
  443. if (allowsMultipleSelection) {
  444. int first = Math.Min (firstSelected ?? selected, selected);
  445. int last = Math.Max (selected, firstSelected ?? selected);
  446. for (int i = first; i <= last; i++) {
  447. if ((canChooseFiles && infos [i].Item2 == false) ||
  448. (canChooseDirectories && infos [i].Item2 &&
  449. infos [i].Item1 != "..")) {
  450. infos [i] = (infos [i].Item1, infos [i].Item2, !infos [i].Item3);
  451. }
  452. }
  453. OnSelectionChanged ();
  454. SetNeedsDisplay ();
  455. }
  456. }
  457. string [] allowedFileTypes;
  458. public string [] AllowedFileTypes {
  459. get => allowedFileTypes;
  460. set {
  461. allowedFileTypes = value;
  462. Reload ();
  463. }
  464. }
  465. public string MakePath (string relativePath)
  466. {
  467. var dir = Directory.ToString ();
  468. return string.IsNullOrEmpty (dir) ? "" : Path.GetFullPath (Path.Combine (dir, relativePath));
  469. }
  470. public IReadOnlyList<string> FilePaths {
  471. get {
  472. if (allowsMultipleSelection) {
  473. var res = new List<string> ();
  474. foreach (var item in infos) {
  475. if (item.Item3)
  476. res.Add (MakePath (item.Item1));
  477. }
  478. if (res.Count == 0 && infos.Count > 0 && infos [selected].Item1 != "..") {
  479. res.Add (MakePath (infos [selected].Item1));
  480. }
  481. return res;
  482. } else {
  483. if (infos.Count == 0) {
  484. return null;
  485. }
  486. if (infos [selected].Item2) {
  487. if (canChooseDirectories) {
  488. var sel = infos [selected].Item1;
  489. return sel == ".." ? new List<string> () : new List<string> () { MakePath (infos [selected].Item1) };
  490. }
  491. return Array.Empty<string> ();
  492. } else {
  493. if (canChooseFiles) {
  494. return new List<string> () { MakePath (infos [selected].Item1) };
  495. }
  496. return Array.Empty<string> ();
  497. }
  498. }
  499. }
  500. }
  501. ///<inheritdoc/>
  502. public override bool OnEnter (View view)
  503. {
  504. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  505. return base.OnEnter (view);
  506. }
  507. }
  508. /// <summary>
  509. /// Base class for the <see cref="OpenDialog"/> and the <see cref="SaveDialog"/>
  510. /// </summary>
  511. public class FileDialog : Dialog {
  512. Button prompt, cancel;
  513. Label nameFieldLabel, message, nameDirLabel;
  514. TextField dirEntry, nameEntry;
  515. internal DirListView dirListView;
  516. ComboBox cmbAllowedTypes;
  517. /// <summary>
  518. /// Initializes a new <see cref="FileDialog"/>.
  519. /// </summary>
  520. public FileDialog () : this (title: string.Empty, prompt: string.Empty,
  521. nameFieldLabel: string.Empty, message: string.Empty)
  522. { }
  523. /// <summary>
  524. /// Initializes a new instance of <see cref="FileDialog"/>
  525. /// </summary>
  526. /// <param name="title">The title.</param>
  527. /// <param name="prompt">The prompt.</param>
  528. /// <param name="nameFieldLabel">The name of the file field label..</param>
  529. /// <param name="message">The message.</param>
  530. /// <param name="allowedTypes">The allowed types.</param>
  531. public FileDialog (ustring title, ustring prompt, ustring nameFieldLabel, ustring message, List<string> allowedTypes = null)
  532. : this (title, prompt, ustring.Empty, nameFieldLabel, message, allowedTypes) { }
  533. /// <summary>
  534. /// Initializes a new instance of <see cref="FileDialog"/>
  535. /// </summary>
  536. /// <param name="title">The title.</param>
  537. /// <param name="prompt">The prompt.</param>
  538. /// <param name="message">The message.</param>
  539. /// <param name="allowedTypes">The allowed types.</param>
  540. public FileDialog (ustring title, ustring prompt, ustring message, List<string> allowedTypes)
  541. : this (title, prompt, ustring.Empty, message, allowedTypes) { }
  542. /// <summary>
  543. /// Initializes a new instance of <see cref="FileDialog"/>
  544. /// </summary>
  545. /// <param name="title">The title.</param>
  546. /// <param name="prompt">The prompt.</param>
  547. /// <param name="nameDirLabel">The name of the directory field label.</param>
  548. /// <param name="nameFieldLabel">The name of the file field label..</param>
  549. /// <param name="message">The message.</param>
  550. /// <param name="allowedTypes">The allowed types.</param>
  551. public FileDialog (ustring title, ustring prompt, ustring nameDirLabel, ustring nameFieldLabel, ustring message,
  552. List<string> allowedTypes = null) : base (title)//, Driver.Cols - 20, Driver.Rows - 5, null)
  553. {
  554. this.message = new Label (message) {
  555. X = 1,
  556. Y = 0,
  557. };
  558. Add (this.message);
  559. var msgLines = TextFormatter.MaxLines (message, Driver.Cols - 20);
  560. this.nameDirLabel = new Label (nameDirLabel.IsEmpty ? $"{Strings.fdDirectory}: " : $"{nameDirLabel}: ") {
  561. X = 1,
  562. Y = 1 + msgLines,
  563. AutoSize = true
  564. };
  565. dirEntry = new TextField ("") {
  566. X = Pos.Right (this.nameDirLabel),
  567. Y = 1 + msgLines,
  568. Width = Dim.Fill () - 1,
  569. };
  570. dirEntry.TextChanged += (e) => {
  571. DirectoryPath = dirEntry.Text;
  572. nameEntry.Text = ustring.Empty;
  573. };
  574. Add (this.nameDirLabel, dirEntry);
  575. this.nameFieldLabel = new Label (nameFieldLabel.IsEmpty ? $"{Strings.fdFile}: " : $"{nameFieldLabel}: ") {
  576. X = 1,
  577. Y = 3 + msgLines,
  578. AutoSize = true
  579. };
  580. nameEntry = new TextField ("") {
  581. X = Pos.Left (dirEntry),
  582. Y = 3 + msgLines,
  583. Width = Dim.Percent (70, true)
  584. };
  585. Add (this.nameFieldLabel, nameEntry);
  586. cmbAllowedTypes = new ComboBox () {
  587. X = Pos.Right (nameEntry) + 2,
  588. Y = Pos.Top (nameEntry),
  589. Width = Dim.Fill (1),
  590. Height = allowedTypes != null ? allowedTypes.Count + 1 : 1,
  591. Text = allowedTypes?.Count > 0 ? allowedTypes [0] : string.Empty,
  592. ReadOnly = true
  593. };
  594. cmbAllowedTypes.SetSource (allowedTypes ?? new List<string> ());
  595. cmbAllowedTypes.OpenSelectedItem += (e) => AllowedFileTypes = cmbAllowedTypes.Text.ToString ().Split (';');
  596. Add (cmbAllowedTypes);
  597. dirListView = new DirListView (this) {
  598. X = 1,
  599. Y = 3 + msgLines + 2,
  600. Width = Dim.Fill () - 1,
  601. Height = Dim.Fill () - 2,
  602. };
  603. DirectoryPath = Path.GetFullPath (Environment.CurrentDirectory);
  604. Add (dirListView);
  605. AllowedFileTypes = cmbAllowedTypes.Text.ToString ().Split (';');
  606. dirListView.DirectoryChanged = (dir) => { nameEntry.Text = ustring.Empty; dirEntry.Text = dir; };
  607. dirListView.FileChanged = (file) => nameEntry.Text = file == ".." ? "" : file;
  608. dirListView.SelectedChanged = (file) => nameEntry.Text = file.Item1 == ".." ? "" : file.Item1;
  609. this.cancel = new Button ("Cancel");
  610. this.cancel.Clicked += () => {
  611. Cancel ();
  612. };
  613. AddButton (cancel);
  614. this.prompt = new Button (prompt.IsEmpty ? "Ok" : prompt) {
  615. IsDefault = true,
  616. Enabled = nameEntry.Text.IsEmpty ? false : true
  617. };
  618. this.prompt.Clicked += () => {
  619. if (this is OpenDialog) {
  620. if (!dirListView.GetValidFilesName (nameEntry.Text.ToString (), out string res)) {
  621. nameEntry.Text = res;
  622. dirListView.SetNeedsDisplay ();
  623. return;
  624. }
  625. if (!dirListView.canChooseDirectories && !dirListView.ExecuteSelection (false)) {
  626. return;
  627. }
  628. } else if (this is SaveDialog) {
  629. var name = nameEntry.Text.ToString ();
  630. if (FilePath.IsEmpty || name.Split (',').Length > 1) {
  631. return;
  632. }
  633. var ext = name.EndsWith (cmbAllowedTypes.Text.ToString ())
  634. ? "" : cmbAllowedTypes.Text.ToString ();
  635. FilePath = Path.Combine (FilePath.ToString (), $"{name}{ext}");
  636. }
  637. canceled = false;
  638. Application.RequestStop ();
  639. };
  640. AddButton (this.prompt);
  641. nameEntry.TextChanged += (e) => {
  642. if (nameEntry.Text.IsEmpty) {
  643. this.prompt.Enabled = false;
  644. } else {
  645. this.prompt.Enabled = true;
  646. }
  647. };
  648. Width = Dim.Percent (80);
  649. Height = Dim.Percent (80);
  650. // On success, we will set this to false.
  651. canceled = true;
  652. KeyPress += (e) => {
  653. if (e.KeyEvent.Key == Key.Esc) {
  654. Cancel ();
  655. e.Handled = true;
  656. }
  657. };
  658. void Cancel ()
  659. {
  660. canceled = true;
  661. Application.RequestStop ();
  662. }
  663. }
  664. internal bool canceled;
  665. ///<inheritdoc/>
  666. public override void WillPresent ()
  667. {
  668. base.WillPresent ();
  669. dirListView.SetFocus ();
  670. }
  671. //protected override void Dispose (bool disposing)
  672. //{
  673. // message?.Dispose ();
  674. // base.Dispose (disposing);
  675. //}
  676. /// <summary>
  677. /// Gets or sets the prompt label for the <see cref="Button"/> displayed to the user
  678. /// </summary>
  679. /// <value>The prompt.</value>
  680. public ustring Prompt {
  681. get => prompt.Text;
  682. set {
  683. prompt.Text = value;
  684. }
  685. }
  686. /// <summary>
  687. /// Gets or sets the name of the directory field label.
  688. /// </summary>
  689. /// <value>The name of the directory field label.</value>
  690. public ustring NameDirLabel {
  691. get => nameDirLabel.Text;
  692. set {
  693. nameDirLabel.Text = $"{value}: ";
  694. }
  695. }
  696. /// <summary>
  697. /// Gets or sets the name field label.
  698. /// </summary>
  699. /// <value>The name field label.</value>
  700. public ustring NameFieldLabel {
  701. get => nameFieldLabel.Text;
  702. set {
  703. nameFieldLabel.Text = $"{value}: ";
  704. }
  705. }
  706. /// <summary>
  707. /// Gets or sets the message displayed to the user, defaults to nothing
  708. /// </summary>
  709. /// <value>The message.</value>
  710. public ustring Message {
  711. get => message.Text;
  712. set {
  713. message.Text = value;
  714. }
  715. }
  716. /// <summary>
  717. /// Gets or sets a value indicating whether this <see cref="FileDialog"/> can create directories.
  718. /// </summary>
  719. /// <value><c>true</c> if can create directories; otherwise, <c>false</c>.</value>
  720. public bool CanCreateDirectories { get; set; }
  721. /// <summary>
  722. /// Gets or sets a value indicating whether this <see cref="FileDialog"/> is extension hidden.
  723. /// </summary>
  724. /// <value><c>true</c> if is extension hidden; otherwise, <c>false</c>.</value>
  725. public bool IsExtensionHidden { get; set; }
  726. /// <summary>
  727. /// Gets or sets the directory path for this panel
  728. /// </summary>
  729. /// <value>The directory path.</value>
  730. public ustring DirectoryPath {
  731. get => dirEntry.Text;
  732. set {
  733. dirEntry.Text = value;
  734. dirListView.Directory = value;
  735. }
  736. }
  737. /// <summary>
  738. /// The array of filename extensions allowed, or null if all file extensions are allowed.
  739. /// </summary>
  740. /// <value>The allowed file types.</value>
  741. public string [] AllowedFileTypes {
  742. get => dirListView.AllowedFileTypes;
  743. set => dirListView.AllowedFileTypes = value;
  744. }
  745. /// <summary>
  746. /// Gets or sets a value indicating whether this <see cref="FileDialog"/> allows the file to be saved with a different extension
  747. /// </summary>
  748. /// <value><c>true</c> if allows other file types; otherwise, <c>false</c>.</value>
  749. public bool AllowsOtherFileTypes { get; set; }
  750. /// <summary>
  751. /// The File path that is currently shown on the panel
  752. /// </summary>
  753. /// <value>The absolute file path for the file path entered.</value>
  754. public ustring FilePath {
  755. get => dirListView.MakePath (nameEntry.Text.ToString ());
  756. set {
  757. nameEntry.Text = Path.GetFileName (value.ToString ());
  758. }
  759. }
  760. /// <summary>
  761. /// Check if the dialog was or not canceled.
  762. /// </summary>
  763. public bool Canceled { get => canceled; }
  764. }
  765. /// <summary>
  766. /// The <see cref="SaveDialog"/> provides an interactive dialog box for users to pick a file to
  767. /// save.
  768. /// </summary>
  769. /// <remarks>
  770. /// <para>
  771. /// To use, create an instance of <see cref="SaveDialog"/>, and pass it to
  772. /// <see cref="Application.Run(Func{Exception, bool})"/>. This will run the dialog modally,
  773. /// and when this returns, the <see cref="FileName"/>property will contain the selected file name or
  774. /// null if the user canceled.
  775. /// </para>
  776. /// </remarks>
  777. public class SaveDialog : FileDialog {
  778. /// <summary>
  779. /// Initializes a new <see cref="SaveDialog"/>.
  780. /// </summary>
  781. public SaveDialog () : this (title: string.Empty, message: string.Empty) { }
  782. /// <summary>
  783. /// Initializes a new <see cref="SaveDialog"/>.
  784. /// </summary>
  785. /// <param name="title">The title.</param>
  786. /// <param name="message">The message.</param>
  787. /// <param name="allowedTypes">The allowed types.</param>
  788. public SaveDialog (ustring title, ustring message, List<string> allowedTypes = null)
  789. : base (title, prompt: Strings.fdSave, nameFieldLabel: $"{Strings.fdSaveAs}:", message: message, allowedTypes) { }
  790. /// <summary>
  791. /// Gets the name of the file the user selected for saving, or null
  792. /// if the user canceled the <see cref="SaveDialog"/>.
  793. /// </summary>
  794. /// <value>The name of the file.</value>
  795. public ustring FileName {
  796. get {
  797. if (canceled)
  798. return null;
  799. return Path.GetFileName (FilePath.ToString ());
  800. }
  801. }
  802. }
  803. /// <summary>
  804. /// The <see cref="OpenDialog"/>provides an interactive dialog box for users to select files or directories.
  805. /// </summary>
  806. /// <remarks>
  807. /// <para>
  808. /// The open dialog can be used to select files for opening, it can be configured to allow
  809. /// multiple items to be selected (based on the AllowsMultipleSelection) variable and
  810. /// you can control whether this should allow files or directories to be selected.
  811. /// </para>
  812. /// <para>
  813. /// To use, create an instance of <see cref="OpenDialog"/>, and pass it to
  814. /// <see cref="Application.Run(Func{Exception, bool})"/>. This will run the dialog modally,
  815. /// and when this returns, the list of files will be available on the <see cref="FilePaths"/> property.
  816. /// </para>
  817. /// <para>
  818. /// To select more than one file, users can use the spacebar, or control-t.
  819. /// </para>
  820. /// </remarks>
  821. public class OpenDialog : FileDialog {
  822. OpenMode openMode;
  823. /// <summary>
  824. /// Determine which <see cref="System.IO"/> type to open.
  825. /// </summary>
  826. public enum OpenMode {
  827. /// <summary>
  828. /// Opens only file or files.
  829. /// </summary>
  830. File,
  831. /// <summary>
  832. /// Opens only directory or directories.
  833. /// </summary>
  834. Directory,
  835. /// <summary>
  836. /// Opens files and directories.
  837. /// </summary>
  838. Mixed
  839. }
  840. /// <summary>
  841. /// Initializes a new <see cref="OpenDialog"/>.
  842. /// </summary>
  843. public OpenDialog () : this (title: string.Empty, message: string.Empty) { }
  844. /// <summary>
  845. /// Initializes a new <see cref="OpenDialog"/>.
  846. /// </summary>
  847. /// <param name="title">The title.</param>
  848. /// <param name="message">The message.</param>
  849. /// <param name="allowedTypes">The allowed types.</param>
  850. /// <param name="openMode">The open mode.</param>
  851. public OpenDialog (ustring title, ustring message, List<string> allowedTypes = null, OpenMode openMode = OpenMode.File) : base (title,
  852. prompt: openMode == OpenMode.File ? Strings.fdOpen : openMode == OpenMode.Directory ? Strings.fdSelectFolder : Strings.fdSelectMixed,
  853. nameFieldLabel: Strings.fdOpen, message: message, allowedTypes)
  854. {
  855. this.openMode = openMode;
  856. switch (openMode) {
  857. case OpenMode.File:
  858. CanChooseFiles = true;
  859. CanChooseDirectories = false;
  860. break;
  861. case OpenMode.Directory:
  862. CanChooseFiles = false;
  863. CanChooseDirectories = true;
  864. break;
  865. case OpenMode.Mixed:
  866. CanChooseFiles = true;
  867. CanChooseDirectories = true;
  868. AllowsMultipleSelection = true;
  869. break;
  870. }
  871. }
  872. /// <summary>
  873. /// Gets or sets a value indicating whether this <see cref="Terminal.Gui.OpenDialog"/> can choose files.
  874. /// </summary>
  875. /// <value><c>true</c> if can choose files; otherwise, <c>false</c>. Defaults to <c>true</c></value>
  876. public bool CanChooseFiles {
  877. get => dirListView.canChooseFiles;
  878. set {
  879. dirListView.canChooseFiles = value;
  880. dirListView.Reload ();
  881. }
  882. }
  883. /// <summary>
  884. /// Gets or sets a value indicating whether this <see cref="OpenDialog"/> can choose directories.
  885. /// </summary>
  886. /// <value><c>true</c> if can choose directories; otherwise, <c>false</c> defaults to <c>false</c>.</value>
  887. public bool CanChooseDirectories {
  888. get => dirListView.canChooseDirectories;
  889. set {
  890. dirListView.canChooseDirectories = value;
  891. dirListView.Reload ();
  892. }
  893. }
  894. /// <summary>
  895. /// Gets or sets a value indicating whether this <see cref="OpenDialog"/> allows multiple selection.
  896. /// </summary>
  897. /// <value><c>true</c> if allows multiple selection; otherwise, <c>false</c>, defaults to false.</value>
  898. public bool AllowsMultipleSelection {
  899. get => dirListView.allowsMultipleSelection;
  900. set {
  901. if (!value && openMode == OpenMode.Mixed) {
  902. return;
  903. }
  904. dirListView.allowsMultipleSelection = value;
  905. dirListView.Reload ();
  906. }
  907. }
  908. /// <summary>
  909. /// Returns the selected files, or an empty list if nothing has been selected
  910. /// </summary>
  911. /// <value>The file paths.</value>
  912. public IReadOnlyList<string> FilePaths {
  913. get => dirListView.FilePaths;
  914. }
  915. }
  916. }