Skip to content

Commit

Permalink
Better separation between Database and NoteController
Browse files Browse the repository at this point in the history
  • Loading branch information
Taicanium committed Nov 24, 2024
1 parent b4f4ee0 commit 8087777
Show file tree
Hide file tree
Showing 10 changed files with 71 additions and 101 deletions.
69 changes: 29 additions & 40 deletions Common.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,6 @@ public enum UUIDType
public static ObservableCollection<Database> 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<string, string> 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; }
Expand All @@ -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<string, string> 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;
Expand Down Expand Up @@ -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)
{
Expand All @@ -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)
Expand All @@ -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)
Expand Down
9 changes: 7 additions & 2 deletions Database.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -123,6 +124,8 @@ public void DeleteRecord(NoteRecord record, bool local = true)
}
}

public void DeserializeRecords(List<byte>? inMemory = null) => Controller.DeserializeRecords(inMemory);

public void Erase()
{
if (Client?.Connected is true || Server?.Serving is true)
Expand Down Expand Up @@ -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<byte>? SerializeRecords(bool inMemory = false) => Controller.SerializeRecords(inMemory);

public void Sort(SortType type = SortType.ByIndex)
{
if (type == SortType.ByIndex)
Expand Down
14 changes: 7 additions & 7 deletions MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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]);
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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))
Expand Down
25 changes: 11 additions & 14 deletions NetClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
});
}
}
2 changes: 1 addition & 1 deletion NetServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 1 addition & 3 deletions Network.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,14 @@ public static string CodeFromAddress(IPAddress? Address, byte? Flags)
if (workingList.Length != 4)
return "Vm000G";

var convertedList = new List<char>([
return string.Concat<char>([
CodeValues[(workingList[0] & 252) >> 2],
CodeValues[((workingList[0] & 3) << 4) + ((workingList[1] & 240) >> 4)],
CodeValues[((workingList[1] & 15) << 2) + ((workingList[2] & 192) >> 6)],
CodeValues[workingList[2] & 63],
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)
Expand Down
26 changes: 6 additions & 20 deletions NoteController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<NoteRecord>((_rev1, _rev2) => type switch
{
switch (type)
{
case SortType.ByIndex:
Records.Sort(new Comparison<NoteRecord>(
(_rev1, _rev2) => _rev1.Index.CompareTo(_rev2.Index)
));
return;
case SortType.ByChange:
Records.Sort(new Comparison<NoteRecord>(
(_rev2, _rev1) => _rev1.GetLastChangeObject().CompareTo(_rev2.GetLastChangeObject())
));
return;
case SortType.ByCreation:
Records.Sort(new Comparison<NoteRecord>(
(_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()
{
Expand Down
2 changes: 1 addition & 1 deletion Properties.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down
4 changes: 2 additions & 2 deletions Replace.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -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">
<Grid>
<StackPanel HorizontalAlignment="Stretch">
<Label Content="Text to replace" FontStyle="Italic" HorizontalAlignment="Right" Margin="0,20,40,0"/>
Expand All @@ -21,7 +21,7 @@
<Button Click="Replace_Click" Content="Replace" IsEnabled="{Binding ReadyToReplace}" x:Name="DoReplace"/>
<Button Click="CloseClick" Grid.Column="1" Content="Close"/>
</Grid>
<Label Content="{Binding NumReplacements}" FontStyle="Italic" Foreground="{Binding AccentForeground}" HorizontalAlignment="Center" Margin="0,20,0,0"/>
<Label Content="{Binding NumReplacements}" FontStyle="Italic" Foreground="{Binding AccentForeground}" HorizontalAlignment="Center"/>
</StackPanel>
</Grid>
</Window>
17 changes: 6 additions & 11 deletions Settings.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,19 +101,14 @@ private void CustomColorOpened(object sender, EventArgs e)
private void FontSizeChanged(object sender, RoutedEventArgs e)
{
var button = (Button)sender;
if (button.Content.Equals("-"))
Common.Settings.MainFontSize -= 0.5;
else
Common.Settings.MainFontSize += 0.5;
Common.Settings.MainFontSize += button.Content.Equals("-") ? -0.5 : 0.5;
DeferUpdateRecentNotes();
}

private static uint HSVFromRGB(SolidColorBrush brush)
{
const double fInv = 1.0 / 255.0;
double r_ = brush.Color.R * fInv;
double g_ = brush.Color.G * fInv;
double b_ = brush.Color.B * fInv;
var (r_, g_, b_) = (brush.Color.R * fInv, brush.Color.G * fInv, brush.Color.B * fInv);
var Cmax = Math.Max(r_, Math.Max(g_, b_));
var Cmin = Math.Min(r_, Math.Min(g_, b_));
var delta = Cmax - Cmin;
Expand All @@ -124,13 +119,13 @@ private static uint HSVFromRGB(SolidColorBrush brush)
{
delta = 60.0 / delta;
if (Cmax == r_)
_h = (delta * (g_ - b_) + 360.0) % 360.0;
_h = delta * (g_ - b_) + 360.0;
if (Cmax == g_)
_h = (delta * (b_ - r_) + 120.0) % 360.0;
_h = delta * (b_ - r_) + 120.0;
if (Cmax == b_)
_h = (delta * (r_ - g_) + 240.0) % 360.0;
_h = delta * (r_ - g_) + 240.0;
}
var H = (uint)(_h * 0.7083333333);
var H = (uint)(_h % 360.0 * 0.7083333333);
var S = (uint)(_s * 255.0);
var V = (uint)(_v * 255.0);
return (H << 16) + (S << 8) + V;
Expand Down

0 comments on commit 8087777

Please sign in to comment.