FileDialog.cs 28 KB

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