From 80877770e768e032a687a0f30c0d3a2f3f48674f Mon Sep 17 00:00:00 2001 From: Taicanium Date: Sun, 24 Nov 2024 07:40:56 -0600 Subject: [PATCH] Better separation between Database and NoteController --- Common.cs | 69 +++++++++++++++++++--------------------------- Database.cs | 9 ++++-- MainWindow.xaml.cs | 14 +++++----- NetClient.cs | 25 ++++++++--------- NetServer.cs | 2 +- Network.cs | 4 +-- NoteController.cs | 26 ++++------------- Properties.xaml.cs | 2 +- Replace.xaml | 4 +-- Settings.xaml.cs | 17 ++++-------- 10 files changed, 71 insertions(+), 101 deletions(-) diff --git a/Common.cs b/Common.cs index 02ebd5a..d727230 100644 --- a/Common.cs +++ b/Common.cs @@ -53,10 +53,6 @@ public enum UUIDType public static ObservableCollection Databases { get; set; } = []; public static string DefaultDatabase { get; } = "New"; public static string DocumentsFolder { get; } = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Sylver Ink"); - public static Dictionary DocumentsSubfolders { get; } = new([ - new("Main", DocumentsFolder), - new("Databases", Path.Join(DocumentsFolder, "Databases")) - ]); public static int HighestFormat { get; } = 8; public static Import? ImportWindow { get => _import; set { _import?.Close(); _import = value; _import?.Show(); } } private static BackgroundWorker? MeasureTask { get; set; } @@ -71,6 +67,10 @@ public enum UUIDType public static ContextSettings Settings { get; } = new(); public static string SettingsFile { get; } = Path.Join(DocumentsFolder, "settings.sis"); public static Settings? SettingsWindow { get => _settings; set { _settings?.Close(); _settings = value; _settings?.Show(); } } + public static Dictionary Subfolders { get; } = new([ + new("Main", DocumentsFolder), + new("Databases", Path.Join(DocumentsFolder, "Databases")) + ]); private static double TextHeight { get; set; } = 0.0; private static BackgroundWorker? UpdateTask { get; set; } public static double WindowHeight { get; set; } = 275.0; @@ -230,34 +230,25 @@ public static void DeferUpdateRecentNotes(bool RepeatUpdate = false) public static string DialogFileSelect(bool outgoing = false, int filterIndex = 3, string? defaultName = null) { - FileDialog dialog; - - if (outgoing) + FileDialog dialog = outgoing ? new SaveFileDialog() { - dialog = new SaveFileDialog() - { - FileName = defaultName ?? DefaultDatabase, - Filter = "Sylver Ink backup files (*.sibk)|*.sibk|Sylver Ink database files (*.sidb)|*.sidb|All files (*.*)|*.*", - FilterIndex = filterIndex, - ValidateNames = true, - }; - - return dialog.ShowDialog() is true ? dialog.FileName : string.Empty; - } - - dialog = new OpenFileDialog() + FileName = defaultName ?? DefaultDatabase, + Filter = "Sylver Ink backup files (*.sibk)|*.sibk|Sylver Ink database files (*.sidb)|*.sidb|All files (*.*)|*.*", + FilterIndex = filterIndex, + ValidateNames = true, + } : new OpenFileDialog() { CheckFileExists = true, Filter = "Sylver Ink backup files (*.sibk)|*.sibk|Sylver Ink database files (*.sidb)|*.sidb|Text files (*.txt)|*.txt|All files (*.*)|*.*", FilterIndex = filterIndex, - InitialDirectory = DocumentsSubfolders["Databases"], + InitialDirectory = Subfolders["Databases"], ValidateNames = true, }; return dialog.ShowDialog() is true ? dialog.FileName : string.Empty; } - public static string GetBackupPath(Database db) => Path.Join(DocumentsSubfolders["Databases"], db.Name, db.Name); + public static string GetBackupPath(Database db) => Path.Join(Subfolders["Databases"], db.Name, db.Name); public static TabControl GetChildPanel(string basePanel) { @@ -275,29 +266,30 @@ public static string GetDatabasePath(Database db) if ((match = IndexDigits().Match(db.Name ?? string.Empty)).Success) index = int.Parse(match.Groups[1].Value); - var path = Path.Join(DocumentsSubfolders["Databases"], db.Name, $"{db.Name}.sidb"); - var uuidFile = Path.Join(DocumentsSubfolders["Databases"], db.Name, "uuid.dat"); + var path = Path.Join(Subfolders["Databases"], db.Name); + var dbFile = Path.Join(path, $"{db.Name}.sidb"); + var uuidFile = Path.Join(path, "uuid.dat"); - while (File.Exists(path)) + while (File.Exists(dbFile)) { if (File.Exists(uuidFile) && File.ReadAllText(uuidFile).Equals(db.UUID)) - return path; + return dbFile; if (!File.Exists(uuidFile)) { Database tmpDB = new(); - tmpDB.Load(path); + tmpDB.Load(dbFile); if (tmpDB.UUID?.Equals(db.UUID) is true) - return path; + return dbFile; } index++; db.Name = $"{db.Name} ({index})"; - path = Path.Join(DocumentsSubfolders["Databases"], db.Name, $"{db.Name}.sidb"); - uuidFile = Path.Join(DocumentsSubfolders["Databases"], db.Name, "uuid.dat"); + dbFile = Path.Join(path, $"{db.Name}.sidb"); + uuidFile = Path.Join(path, "uuid.dat"); } - return path; + return dbFile; } public static Label GetRibbonHeader(NoteRecord record) @@ -319,17 +311,14 @@ public static Label GetRibbonHeader(NoteRecord record) }; } - private static string GetRibbonTooltip(NoteRecord record) + private static string GetRibbonTooltip(NoteRecord record) => RibbonTabContent switch { - return RibbonTabContent switch - { - DisplayType.Change => $"{record.ShortChange} — {record.Preview}", - DisplayType.Content => record.Preview, - DisplayType.Creation => $"{record.GetCreated()} — {record.Preview}", - DisplayType.Index => $"Note #{record.Index + 1:N0} — {record.Preview}", - _ => record.Preview - }; - } + DisplayType.Change => $"{record.ShortChange} — {record.Preview}", + DisplayType.Content => record.Preview, + DisplayType.Creation => $"{record.GetCreated()} — {record.Preview}", + DisplayType.Index => $"Note #{record.Index + 1:N0} — {record.Preview}", + _ => record.Preview + }; public static int IntFromBytes(byte[] data) => (data[0] << 24) diff --git a/Database.cs b/Database.cs index 3c1ea3f..0ebacd5 100644 --- a/Database.cs +++ b/Database.cs @@ -11,13 +11,14 @@ namespace SylverInk { public partial class Database { - public NoteController Controller = new(); + private NoteController Controller = new(); public string DBFile = string.Empty; public bool Loaded = false; public bool Changed { get => Controller.Changed; set => Controller.Changed = value; } public NetClient? Client; public long? Created; + public int Format { get => Controller.Format; set => Controller.Format = value; } private StackPanel? HeaderPanel; public string? Name { get => Controller.Name; set => Controller.Name = value; } public int RecordCount => Controller.RecordCount; @@ -123,6 +124,8 @@ public void DeleteRecord(NoteRecord record, bool local = true) } } + public void DeserializeRecords(List? inMemory = null) => Controller.DeserializeRecords(inMemory); + public void Erase() { if (Client?.Connected is true || Server?.Serving is true) @@ -280,10 +283,12 @@ public void Save() Controller.SerializeRecords(); - if (DBFile.Contains(DocumentsSubfolders["Databases"])) + if (DBFile.Contains(Subfolders["Databases"])) File.WriteAllText(Path.Join(Path.GetDirectoryName(DBFile), "uuid.dat"), UUID); } + public List? SerializeRecords(bool inMemory = false) => Controller.SerializeRecords(inMemory); + public void Sort(SortType type = SortType.ByIndex) { if (type == SortType.ByIndex) diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs index 95bd011..cc5f1b1 100644 --- a/MainWindow.xaml.cs +++ b/MainWindow.xaml.cs @@ -159,13 +159,13 @@ private void DatabaseSaveAs(object sender, RoutedEventArgs e) var newPath = DialogFileSelect(true, 2, CurrentDatabase.Name); if (!newPath.Equals(string.Empty)) CurrentDatabase.DBFile = newPath; - CurrentDatabase.Controller.Format = HighestFormat; + CurrentDatabase.Format = HighestFormat; } private void DatabaseSaveLocal(object sender, RoutedEventArgs e) { - CurrentDatabase.DBFile = Path.Join(DocumentsSubfolders["Databases"], Path.GetFileNameWithoutExtension(CurrentDatabase.DBFile), Path.GetFileName(CurrentDatabase.DBFile)); - CurrentDatabase.Controller.Format = HighestFormat; + CurrentDatabase.DBFile = Path.Join(Subfolders["Databases"], Path.GetFileNameWithoutExtension(CurrentDatabase.DBFile), Path.GetFileName(CurrentDatabase.DBFile)); + CurrentDatabase.Format = HighestFormat; } private void DatabaseServe(object sender, RoutedEventArgs e) => CurrentDatabase.Server?.Serve(0); @@ -213,7 +213,7 @@ private static void LoadUserSettings() foreach (var file in files) Database.Create(file, true); if (!files.Any()) - Database.Create(Path.Join(DocumentsSubfolders["Databases"], $"{DefaultDatabase}", $"{DefaultDatabase}.sidb")); + Database.Create(Path.Join(Subfolders["Databases"], $"{DefaultDatabase}", $"{DefaultDatabase}.sidb")); break; case "ListBackground": Common.Settings.ListBackground = BrushFromBytes(keyValue[1]); @@ -278,12 +278,12 @@ private void MainWindow_Loaded(object sender, RoutedEventArgs e) { LoadUserSettings(); - foreach (var folder in DocumentsSubfolders) + foreach (var folder in Subfolders) if (!Directory.Exists(folder.Value)) Directory.CreateDirectory(folder.Value); if (FirstRun) - Database.Create(Path.Join(DocumentsSubfolders["Databases"], $"{DefaultDatabase}", $"{DefaultDatabase}.sidb")); + Database.Create(Path.Join(Subfolders["Databases"], $"{DefaultDatabase}", $"{DefaultDatabase}.sidb")); DatabasesPanel.SelectedIndex = 0; @@ -350,7 +350,7 @@ private void RenameClosed(object sender, EventArgs e) if (!Directory.Exists(oldPath)) return; - var directorySearch = Directory.GetDirectories(DocumentsSubfolders["Databases"], "*", new EnumerationOptions() { IgnoreInaccessible = true, RecurseSubdirectories = true, MaxRecursionDepth = 3 }); + var directorySearch = Directory.GetDirectories(Subfolders["Databases"], "*", new EnumerationOptions() { IgnoreInaccessible = true, RecurseSubdirectories = true, MaxRecursionDepth = 3 }); if (oldPath is not null && newPath is not null && directorySearch.Contains(oldPath)) { if (Directory.Exists(newPath)) diff --git a/NetClient.cs b/NetClient.cs index 97d5c90..cea2bee 100644 --- a/NetClient.cs +++ b/NetClient.cs @@ -135,7 +135,7 @@ private void ReadFromStream() textBuffer = new byte[textCount]; stream.Read(textBuffer, 0, textCount); - DB?.Controller.DeserializeRecords(new(textBuffer)); + DB?.DeserializeRecords(new(textBuffer)); Connecting = false; Connected = true; @@ -233,19 +233,16 @@ public async void Send(MessageType type, byte[] data) } } - public void UpdateIndicator() + public void UpdateIndicator() => Indicator?.Dispatcher.Invoke(() => { - Indicator?.Dispatcher.Invoke(() => - { - Indicator.Fill = Connecting ? Brushes.Yellow : (DBClient?.Connected is true ? Brushes.Green : Brushes.Orange); - Indicator.Height = 12; - Indicator.Margin = new(2, 4, 3, 4); - Indicator.Stroke = Common.Settings.MenuForeground; - Indicator.Width = 12; - Indicator.InvalidateVisual(); - DB?.GetHeader(); - UpdateContextMenu(); - }); - } + Indicator.Fill = Connecting ? Brushes.Yellow : (DBClient?.Connected is true ? Brushes.Green : Brushes.Orange); + Indicator.Height = 12; + Indicator.Margin = new(2, 4, 3, 4); + Indicator.Stroke = Common.Settings.MenuForeground; + Indicator.Width = 12; + Indicator.InvalidateVisual(); + DB?.GetHeader(); + UpdateContextMenu(); + }); } } diff --git a/NetServer.cs b/NetServer.cs index 95de2c4..20e5c16 100644 --- a/NetServer.cs +++ b/NetServer.cs @@ -83,7 +83,7 @@ public NetServer(Database DB) var stream = client.GetStream(); Flags = (byte)stream.ReadByte(); - var data = DB.Controller?.SerializeRecords(true); + var data = DB.SerializeRecords(true); int dataLength = data?.Count ?? 0; data?.Insert(0, (byte)MessageType.DatabaseInit); diff --git a/Network.cs b/Network.cs index 728fc66..b029dba 100644 --- a/Network.cs +++ b/Network.cs @@ -30,7 +30,7 @@ public static string CodeFromAddress(IPAddress? Address, byte? Flags) if (workingList.Length != 4) return "Vm000G"; - var convertedList = new List([ + return string.Concat([ CodeValues[(workingList[0] & 252) >> 2], CodeValues[((workingList[0] & 3) << 4) + ((workingList[1] & 240) >> 4)], CodeValues[((workingList[1] & 15) << 2) + ((workingList[2] & 192) >> 6)], @@ -38,8 +38,6 @@ public static string CodeFromAddress(IPAddress? Address, byte? Flags) CodeValues[(workingList[3] & 252) >> 2], CodeValues[((workingList[3] & 3) << 4) + ((Flags ?? 0) & 15)], ]); - - return string.Concat(convertedList); } public static IPAddress CodeToAddress(string? Code, out byte? Flags) diff --git a/NoteController.cs b/NoteController.cs index 75c87fd..dca9eb7 100644 --- a/NoteController.cs +++ b/NoteController.cs @@ -330,27 +330,13 @@ public void Revert(DateTime targetDate) return null; } - public void Sort(SortType type = SortType.ByIndex) + public void Sort(SortType type = SortType.ByIndex) => Records.Sort(new Comparison((_rev1, _rev2) => type switch { - switch (type) - { - case SortType.ByIndex: - Records.Sort(new Comparison( - (_rev1, _rev2) => _rev1.Index.CompareTo(_rev2.Index) - )); - return; - case SortType.ByChange: - Records.Sort(new Comparison( - (_rev2, _rev1) => _rev1.GetLastChangeObject().CompareTo(_rev2.GetLastChangeObject()) - )); - return; - case SortType.ByCreation: - Records.Sort(new Comparison( - (_rev2, _rev1) => _rev1.GetCreatedObject().CompareTo(_rev2.GetCreatedObject()) - )); - return; - } - } + SortType.ByChange => _rev2.GetLastChangeObject().CompareTo(_rev1.GetLastChangeObject()), + SortType.ByCreation => _rev2.GetCreatedObject().CompareTo(_rev1.GetCreatedObject()), + SortType.ByIndex => _rev1.Index.CompareTo(_rev2.Index), + _ => _rev1.Index.CompareTo(_rev2.Index), + })); public bool TestCanCompress() { diff --git a/Properties.xaml.cs b/Properties.xaml.cs index d1a29e5..ad3b399 100644 --- a/Properties.xaml.cs +++ b/Properties.xaml.cs @@ -50,7 +50,7 @@ private void InitializeProperties() { DBNameLabel.ToolTip = DBNameLabel.Text = DB?.Name; DBCreatedLabel.Content = DB?.GetCreated(); - DBFormatLabel.Content = $"SIDB v.{DB?.Controller.Format}"; + DBFormatLabel.Content = $"SIDB v.{DB?.Format}"; DBPathLabel.ToolTip = DBPathLabel.Text = $"{DB?.DBFile}"; DBNotesLabel.Content = $"{DB?.RecordCount:N0} notes"; diff --git a/Replace.xaml b/Replace.xaml index b16553c..987fcab 100644 --- a/Replace.xaml +++ b/Replace.xaml @@ -6,7 +6,7 @@ xmlns:local="clr-namespace:SylverInk" mc:Ignorable="d" d:DataContext="{d:DesignInstance Type=local:ContextSettings}" - Background="{Binding MenuBackground}" Foreground="{Binding MenuForeground}" Height="300" MinHeight="300" MinWidth="325" MouseLeftButtonDown="Drag" ResizeMode="CanResize" Title="Sylver Ink: Replace" Width="525"> + Background="{Binding MenuBackground}" Foreground="{Binding MenuForeground}" Height="275" MinHeight="275" MinWidth="325" MouseLeftButtonDown="Drag" ResizeMode="CanResize" Title="Sylver Ink: Replace" Width="525">