-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoteTree.cs
More file actions
573 lines (491 loc) · 19.7 KB
/
NoteTree.cs
File metadata and controls
573 lines (491 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
using Spectre.Console;
namespace NoteWorthy;
internal class NoteTree
{
/// <summary>
/// The width of the entire panel
/// </summary>
public static int DISPLAY_WIDTH = 32;
/// <summary>
/// The width of the text buffer that will be displayed inside the panel.
/// </summary>
public static int BUFFER_WIDTH = DISPLAY_WIDTH - 4;
/// <summary>
/// The height of the TreeItems panel.
/// </summary>
public static int DISPLAY_HEIGHT = Console.BufferHeight - 4; // -4 for the footer panel
/// <summary>
/// The height of the buffer within the TreeItems panel
/// </summary>
public static int BUFFER_HEIGHT = DISPLAY_HEIGHT - 2; // -2 for the top and bottom borders.
private readonly List<TreeItem> treeItems;
/// <summary>
/// The parent of the currently selected TreeItem.
/// Set to null if the selected TreeItem is the root directory.
/// </summary>
private TreeItem? current_parent_treeItem = null;
/// <summary>
/// The index of the selected TreeItem
/// </summary>
private int selected_item_index = 0;
/// <summary>
/// True when the display should be updated.
/// </summary>
private bool requires_update = true;
/// <summary>
/// The index of the item at the start of the display
/// </summary>
private int display_start_index = 0;
public NoteTree(string? starting_selected_dir_path = null)
{
// Load the notes from the notes directory
treeItems = LoadTreeItems(Program.NOTES_DIR_PATH, null, starting_selected_dir_path);
}
/// <summary>
/// Get the notes from the notes directory and add them to the NoteTree as TreeItems.
/// </summary>
private List<TreeItem> LoadTreeItems(string directoryPath, TreeItem? parent, string? starting_selected_dir_path)
{
IEnumerable<string> files = Directory.GetFiles(directoryPath).OrderBy(filePath => new FileInfo(filePath).CreationTime).Where((string file) => file.EndsWith(".nw"));
string[] directories = Directory.GetDirectories(directoryPath);
IEnumerable<TreeItem> _files = files.Select((string file_path) =>
{
int len = Path.GetFileName(file_path)!.Length;
if (len > BUFFER_WIDTH)
{
Console.WriteLine($"File name is too long. Must be less than {BUFFER_WIDTH} characters long. Is {len} long. Path: {file_path}");
Console.WriteLine("Press any key to continue.");
Console.ReadKey(true);
throw new FileLoadException($"File name is too long. Must be less than {BUFFER_WIDTH} characters long. Is {len} long. Path: {file_path}");
}
return new TreeItem(file_path, parent);
});
IEnumerable<TreeItem> _directories = directories.Select(directory_path =>
{
int len = new DirectoryInfo(directory_path)!.Name.Length;
if (len > BUFFER_WIDTH)
{
throw new FileLoadException($"Directory name is too long. Must be less than {BUFFER_WIDTH} characters long. Is {len} long. Path: {directory_path}");
}
var treeItem = new TreeItem(directory_path, parent);
treeItem.SetDirectory(LoadTreeItems(directory_path, treeItem, starting_selected_dir_path));
if (directory_path == starting_selected_dir_path)
{
current_parent_treeItem = treeItem;
}
return treeItem;
});
return _directories.Concat(_files).ToList();
}
/// <summary>
/// Return a <see cref="Spectre.Console.Panel"/> representing the NoteTree
/// which will be displayed on the left side of the screen
/// </summary>
public Panel GenerateDisplayPanel()
{
requires_update = false;
List<TreeItem> _treeItems = GetParentTreeItemChildren();
_treeItems = _treeItems.GetRange(display_start_index, Math.Min(BUFFER_HEIGHT, _treeItems.Count));
if (_treeItems.Count == 0)
{
return new Panel("Folder empty")
.Header("[yellow] " + (current_parent_treeItem == null ? "Root" : current_parent_treeItem.Name) + " [/]")
.Expand()
.RoundedBorder();
}
TreeItem selected_tree_item = GetSelectedTreeItem()!;
string names_string = string.Join("\n", _treeItems.Select((TreeItem x) =>
(x == selected_tree_item ? "[yellow]" : "[white]") + x.Name + (x.IsDir ? "/" : "") + "[/]"
));
return new Panel(names_string)
.Header("[yellow] " + (current_parent_treeItem == null ? "Root" : current_parent_treeItem.Name) + " [/]")
.Expand()
.RoundedBorder();
}
/// <summary>
/// Get the current tree items that are to be displayed.
///
/// If the current parent is null, then the root directory is being displayed.
/// </summary>
private List<TreeItem> GetParentTreeItemChildren()
{
if (current_parent_treeItem == null)
{
return treeItems;
}
return current_parent_treeItem.Children;
}
/// <summary>
/// Navigate to a TreeItem in the NoteTree. Must be a directory.
/// </summary>
/// <param name="treeItem">Set to <see langword="null" /> to navigate to the root directory.</param>
/// <exception cref="Exception">If the TreeItem is not a directory.</exception>
public void NavigateToTreeItemDirectory(TreeItem? treeItem)
{
if (treeItem != null && !treeItem.IsDir) throw new Exception("Cannot navigate to a file.");
current_parent_treeItem = treeItem;
selected_item_index = 0;
Set_RequiresUpdate();
}
/// <summary>
/// Navigate to the parent item if there is a parent.
/// </summary>
public void GoToParentIfPossible()
{
if (current_parent_treeItem == null) return;
NavigateToTreeItemDirectory(current_parent_treeItem.Parent);
}
/// <summary>
/// Checks if the display needs to be updated.
/// </summary>
public bool Get_RequiresUpdate()
{
return requires_update;
}
/// <summary>
/// Specify that an update is required.
/// </summary>
public void Set_RequiresUpdate()
{
requires_update = true;
}
public void MoveSelectionUp()
{
if (selected_item_index == 0)
{
MoveSelectionToBottom();
}
else
{
selected_item_index--;
display_start_index = Math.Max(0, display_start_index - 1);
Set_RequiresUpdate();
}
}
public void MoveSelectionDown()
{
if (selected_item_index == GetParentTreeItemChildren().Count - 1)
{
MoveSelectionToTop();
}
else
{
selected_item_index++;
display_start_index = Math.Min(display_start_index + 1, GetParentTreeItemChildren().Count - BUFFER_HEIGHT);
display_start_index = display_start_index < 0 ? 0 : display_start_index;
Set_RequiresUpdate();
}
}
public void MoveSelectionToTop()
{
display_start_index = 0;
selected_item_index = 0;
Set_RequiresUpdate();
}
public void MoveSelectionToBottom()
{
selected_item_index = GetParentTreeItemChildren().Count - 1;
display_start_index = Math.Max(0, GetParentTreeItemChildren().Count - BUFFER_HEIGHT);
Set_RequiresUpdate();
}
public TreeItem? GetSelectedTreeItem()
{
List<TreeItem> items = GetParentTreeItemChildren();
if (items.Count == 0) return null;
return GetParentTreeItemChildren()[selected_item_index];
}
/// <summary>
/// Prompt the user for a new folder name and create the folder inside of the current directory.
/// </summary>
/// <returns>Returns the path of the newly created file, or <see langword="null"/> if the user cancelled</returns>
public string? CreateFolder()
{
Console.Clear();
AnsiConsole.Write(new Markup("[yellow]Create a new folder[/]. Type a period '[yellow].[/]' to cancel.\n\n"));
string folder_name = AnsiConsole.Prompt(
new TextPrompt<string>("Enter the name of the folder:")
.Validate(name => !string.IsNullOrWhiteSpace(name.Trim()) && !name.Contains('/'), "Folder name cannot be empty or contain '/'")
.Validate((string s) =>
{
s = s.Trim();
return s.Length > 0 && s.Length <= NoteTree.BUFFER_WIDTH;
}, $"The dir name must be less than {NoteTree.BUFFER_WIDTH + 1} characters")
).Trim();
if (folder_name == ".") return null;
if (Settings.AutoCapitalizeNoteAndDirNames)
folder_name = TitleCase(folder_name);
string folder_path = Path.Combine(current_parent_treeItem?.FilePath ?? Program.NOTES_DIR_PATH, folder_name);
Directory.CreateDirectory(folder_path);
var treeItem = new TreeItem(folder_path, current_parent_treeItem);
treeItem.SetDirectory(new List<TreeItem>());
if (current_parent_treeItem == null)
treeItems.Add(treeItem);
else current_parent_treeItem!.AddChild(treeItem);
return folder_path;
}
/// <summary>
/// Prompt the user for a new file name and create the file inside of the current directory.
/// </summary>
/// <returns>The path of the newly-created file. <see langword="null"/> if the user cancelled.</returns>
public string? CreateFile()
{
Console.Clear();
AnsiConsole.Write(new Markup("[yellow]Create a new file[/]. Type a period '[yellow].[/]' to cancel.\n\n"));
List<TreeItem> treeItemsInDir = GetParentTreeItemChildren();
string file_name = AnsiConsole.Prompt(
new TextPrompt<string>("Enter the name of the file:")
.Validate(name => !string.IsNullOrWhiteSpace(name) && !name.Contains('/') && !name.Contains('\\'), "Folder name cannot be empty or contain '/' or '\\")
.Validate((string s) =>
{
s = s.Trim();
// -3 to account for the .nw that will be added if it's not already there
return s.Length > 0 && s.Length <= NoteTree.BUFFER_WIDTH - (s.EndsWith(".nw") ? 0 : 3);
}, $"The file name must be less than {NoteTree.BUFFER_WIDTH + 1} characters, including the '.nw' file extension")
.Validate(name =>
{
name = name.Trim();
if (Settings.AutoCapitalizeNoteAndDirNames)
name = TitleCase(name);
for (int i = 0; i < treeItemsInDir.Count; i++)
{
if (treeItemsInDir[i].Name == name || treeItemsInDir[i].Name == name + ".nw") return false;
}
return true;
}, "A file with that name already exists in this directory.")
).Trim();
if (file_name == ".") return null;
if (Settings.AutoCapitalizeNoteAndDirNames)
file_name = TitleCase(file_name);
if (!file_name.EndsWith(".nw"))
file_name += ".nw";
string file_path = Path.Combine(current_parent_treeItem?.FilePath ?? Program.NOTES_DIR_PATH, file_name);
File.Create(file_path).Close();
if (current_parent_treeItem == null)
treeItems.Add(new TreeItem(file_path, current_parent_treeItem));
else current_parent_treeItem!.AddChild(new TreeItem(file_path, current_parent_treeItem));
return file_path;
}
/// <summary>
/// Set the currently selected tree item to the TreeItem with the given path
/// </summary>
/// <param name="path">The path to the tree item in the file system</param>
public void NavigateToTreeItemInCurrentDirByPath(string path)
{
List<TreeItem> nodes = GetParentTreeItemChildren();
for (int i = 0; i < nodes.Count; i++)
{
if (nodes[i].FilePath == path)
{
selected_item_index = i;
Set_RequiresUpdate();
return;
}
}
}
public void DeleteSelectedTreeItem()
{
TreeItem? selected_tree_item = GetSelectedTreeItem();
if (selected_tree_item == null) return;
MakeSureRecycleBinExists();
if (selected_tree_item.IsDir)
{
// If the directory is empty, delete it
if (Directory.EnumerateFileSystemEntries(selected_tree_item.FilePath).Count() == 0)
{
Directory.Delete(selected_tree_item.FilePath);
}
// Otherwise, delete it but preserve it in the recycle bin
else
{
Directory.Move(selected_tree_item.FilePath, Path.Combine(Program.RECYCLE_BIN_PATH, $"{selected_tree_item.Name}-{DateTime.Now.ToString("yyyy-MM-dd")}"));
}
}
else
{
// If the file is empty, delete it
if (new FileInfo(selected_tree_item.FilePath).Length == 0)
{
File.Delete(selected_tree_item.FilePath);
}
// Otherwise, delete it but preserve it in the recycle bin
else
{
File.Move(selected_tree_item.FilePath, Path.Combine(Program.RECYCLE_BIN_PATH, $"{selected_tree_item.Name.Substring(0, selected_tree_item.Name.Length - 3)}-{DateTime.Now.ToString("yyyy-MM-dd")}.nw"));
}
}
if (current_parent_treeItem == null)
{
treeItems.Remove(selected_tree_item);
}
else
{
current_parent_treeItem.Children.Remove(selected_tree_item);
}
if (selected_item_index >= GetParentTreeItemChildren().Count)
{
selected_item_index = GetParentTreeItemChildren().Count - 1;
}
Set_RequiresUpdate();
}
private void MakeSureRecycleBinExists()
{
if (!Directory.Exists(Program.RECYCLE_BIN_PATH))
{
Directory.CreateDirectory(Program.RECYCLE_BIN_PATH);
}
}
/// <summary>
/// Get the next note file in the current directory.
/// </summary>
/// <returns>True if the next tree item was able to be selected.
/// Will be false if there was no selected tree item in the first place or if the currently selected tree item is a directory</returns>
public bool SelectNextFileTreeItem()
{
// No file is selected, so you can't go to the next file
if (GetSelectedTreeItem() == null) return false;
List<TreeItem> file_tree_items = GetParentTreeItemChildren().Where(x => !x.IsDir).ToList();
int index_in_files = file_tree_items.IndexOf(GetSelectedTreeItem()!);
requires_update = true;
// If the item is not in the list (index = -1), then the item must be a dir
// Go to the top file item, since dirs are always the top-most items
//
// If the selected file is the last file, select the top file
if (index_in_files == -1 || index_in_files == file_tree_items.Count - 1)
{
selected_item_index = GetParentTreeItemChildren().IndexOf(file_tree_items[0]);
return true;
}
else
{
selected_item_index++;
return true;
}
}
public bool SelectPreviousFileTreeItem()
{
// No file is selected, so you can't go to the previous file
if (GetSelectedTreeItem() == null) return false;
List<TreeItem> file_tree_items = GetParentTreeItemChildren().Where(x => !x.IsDir).ToList();
int index_in_files = file_tree_items.IndexOf(GetSelectedTreeItem()!);
requires_update = true;
// If the item is not in the list (index = -1), then the item must be a dir
// Go to the bottom item, since dirs are always the very top items above
//
// If the selected file is the first file, select the last file
if (index_in_files == -1 || index_in_files == 0)
{
// Set to the index of the bottom file
selected_item_index = GetParentTreeItemChildren().IndexOf(file_tree_items[file_tree_items.Count - 1]);
return true;
}
else
{
selected_item_index--;
return true;
}
}
private bool is_visible = true;
public void ToggleVisibility()
{
is_visible = !is_visible;
requires_update = true;
}
public bool IsVisible()
{
return is_visible;
}
public void SetVisible()
{
is_visible = true;
}
public void SetInvisible()
{
is_visible = false;
}
/// <summary>
/// Make a copy of the selected tree item if it is a file.
/// The copy will not be made if a file with the resulting name (name - copy.nw) already exists.
/// </summary>
/// <returns>True if a copy was made, false otherwise</returns>
public bool CopySelectedTreeItem()
{
TreeItem? t = GetSelectedTreeItem();
if (t == null) return false;
if (t.IsDir)
{
string dir_name = new DirectoryInfo(t.FilePath).Name;
string dir_path = dir_name.Length + 8 <= BUFFER_WIDTH // +8 : +7 for size of " - copy" and +1 for '/'
? t.FilePath
: t.FilePath.Substring(0, t.FilePath.Length - dir_name.Length - 7); // -7 size of " - copy "
dir_path += " - Copy";
if (Directory.Exists(dir_path))
{
Console.Beep();
return false;
}
CopyDirectory(t.FilePath, dir_path);
return true;
}
string file_name = Path.GetFileName(t.FilePath);
string file_name_no_ext = Path.GetFileNameWithoutExtension(t.FilePath);
string new_name;
if (file_name.Length <= BUFFER_WIDTH - " - Copy".Length)
{
new_name = file_name_no_ext + " - Copy.nw";
}
else
{
new_name = file_name.Substring(0, BUFFER_WIDTH - " ... - Copy.nw".Length) + " ... - Copy.nw";
}
string new_path = Path.Combine(Path.GetDirectoryName(t.FilePath)!, new_name);
if (File.Exists(new_path))
{
Console.Beep();
return false;
}
File.Copy(t.FilePath, new_path);
TreeItem new_tree_item = new TreeItem(new_path, current_parent_treeItem);
return true;
}
// ChatGPT function for copying dir
public static void CopyDirectory(string sourceDir, string destDir)
{
// Create the destination directory if it doesn't exist
Directory.CreateDirectory(destDir);
// Get all files in the source directory and copy them to the destination directory
foreach (string file in Directory.GetFiles(sourceDir))
{
string destFile = Path.Combine(destDir, Path.GetFileName(file));
File.Copy(file, destFile, true); // Overwrite if the file already exists
}
// Get all subdirectories and copy them recursively
foreach (string subdir in Directory.GetDirectories(sourceDir))
{
string destSubDir = Path.Combine(destDir, Path.GetFileName(subdir));
CopyDirectory(subdir, destSubDir);
}
}
public static void UpdateBuffers()
{
DISPLAY_HEIGHT = Console.BufferHeight - 4;
// Display width is constant 32
BUFFER_HEIGHT = DISPLAY_HEIGHT - 2;
BUFFER_WIDTH = DISPLAY_WIDTH - 4;
}
public static string TitleCase(string s)
{
string _s = "";
for (int i = 0; i < s.Length; i++)
{
if (i == 0 || s[i - 1] == ' ')
{
_s += char.ToUpper(s[i]);
}
else
{
_s += s[i];
}
}
return _s;
}
}