Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62a3c96dc0 | ||
|
|
4fc8fdda6f | ||
|
|
b5614ff59b | ||
|
|
e2bb0298b1 |
No files matched your search
@@ -0,0 +1,171 @@
|
||||
using System.Globalization;
|
||||
using YKanBan.Export;
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.Tests.Export;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the Markdown exporter. Mutates the global Resources.Culture,
|
||||
/// therefore marked DoNotParallelize. Asserts real localized output for
|
||||
/// both supported languages.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[DoNotParallelize]
|
||||
public class MarkdownExporterTests
|
||||
{
|
||||
private static readonly DateTimeOffset ExportedAt = new(2026, 9, 30, 14, 25, 37, TimeSpan.Zero);
|
||||
|
||||
/// <summary>A local wall-clock moment, matching the exporter's conversion path.</summary>
|
||||
private static DateTimeOffset Local(int year, int month, int day, int hour, int minute) =>
|
||||
new DateTimeOffset(new DateTime(year, month, day, hour, minute, 0)).ToLocalTime();
|
||||
|
||||
/// <summary>Unix seconds for a local wall-clock time.</summary>
|
||||
private static long UnixTimeOf(int year, int month, int day, int hour, int minute) =>
|
||||
Local(year, month, day, hour, minute).ToUnixTimeSeconds();
|
||||
|
||||
/// <summary>Builds the board fixture: one working column with two cards, one empty column, two tags.</summary>
|
||||
private static (IReadOnlyList<ColumnModel> Columns, IReadOnlyList<CardModel> Cards, IReadOnlyList<(TagModel, long)> Tags) CreateBoard()
|
||||
{
|
||||
long created = UnixTimeOf(2026, 9, 1, 10, 0);
|
||||
long updated = UnixTimeOf(2026, 9, 28, 18, 30);
|
||||
|
||||
var columns = new List<ColumnModel>
|
||||
{
|
||||
new(1, "In Progress", "The work column", 100, 100),
|
||||
new(2, "Empty", string.Empty, 100, 100),
|
||||
};
|
||||
var bug = new TagModel(1, "bug", RgbColor.Parse("#ff0000"), string.Empty);
|
||||
var ui = new TagModel(2, "ui", RgbColor.Parse("#00ff00"), "Interface work");
|
||||
var cards = new List<CardModel>
|
||||
{
|
||||
new(61, 1, "Fix login", "Body text", created, updated, [bug, ui]),
|
||||
new(62, 1, string.Empty, string.Empty, created, updated, []),
|
||||
};
|
||||
var tags = new List<(TagModel, long)> { (bug, 1), (ui, 1) };
|
||||
return (columns, cards, tags);
|
||||
}
|
||||
|
||||
private static string Export(CultureInfo culture)
|
||||
{
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
Resources.Culture = culture;
|
||||
(IReadOnlyList<ColumnModel> columns, IReadOnlyList<CardModel> cards, IReadOnlyList<(TagModel, long)> tags) = CreateBoard();
|
||||
return MarkdownExporter.Export("MyRepo", columns, cards, tags, ExportedAt);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Normalize(string text) => text.Replace("\r\n", "\n");
|
||||
|
||||
[TestMethod]
|
||||
public void EnglishOutputMatchesTemplate()
|
||||
{
|
||||
string created = Local(2026, 9, 1, 10, 0).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
|
||||
string updated = Local(2026, 9, 28, 18, 30).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
|
||||
|
||||
string expected = Normalize($"""
|
||||
# MyRepo
|
||||
> Exported at: 2026-09-30 14:25:37
|
||||
|
||||
## Column: In Progress (2)
|
||||
The work column
|
||||
|
||||
### #61 Fix login
|
||||
Body text
|
||||
- Tags: `bug` `ui`
|
||||
- Created: {created} Modified: {updated}
|
||||
|
||||
### #62
|
||||
- Created: {created} Modified: {updated}
|
||||
|
||||
## Column: Empty (0)
|
||||
|
||||
## Tags
|
||||
| Name | Color | Description | Usage |
|
||||
|---|---|---|---|
|
||||
| bug | #ff0000 | | 1 |
|
||||
| ui | #00ff00 | Interface work | 1 |
|
||||
""");
|
||||
|
||||
Assert.AreEqual(expected + "\n", Normalize(Export(new CultureInfo("en"))));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ChineseOutputMatchesTemplate()
|
||||
{
|
||||
var chinese = new CultureInfo("zh-Hans");
|
||||
string created = Local(2026, 9, 1, 10, 0).ToString("yyyy年M月d日 HH:mm", chinese);
|
||||
string updated = Local(2026, 9, 28, 18, 30).ToString("yyyy年M月d日 HH:mm", chinese);
|
||||
|
||||
string expected = Normalize($"""
|
||||
# MyRepo
|
||||
> 导出时间:2026年9月30日 14:25
|
||||
|
||||
## 列:In Progress(2)
|
||||
The work column
|
||||
|
||||
### #61 Fix login
|
||||
Body text
|
||||
- 标签:`bug` `ui`
|
||||
- 创建:{created} 修改:{updated}
|
||||
|
||||
### #62
|
||||
- 创建:{created} 修改:{updated}
|
||||
|
||||
## 列:Empty(0)
|
||||
|
||||
## 标签总表
|
||||
| 名称 | 颜色 | 描述 | 使用数 |
|
||||
|---|---|---|---|
|
||||
| bug | #ff0000 | | 1 |
|
||||
| ui | #00ff00 | Interface work | 1 |
|
||||
""");
|
||||
|
||||
Assert.AreEqual(expected + "\n", Normalize(Export(new CultureInfo("zh-Hans"))));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FileNameFollowsLanguage()
|
||||
{
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
Assert.AreEqual("MyRepo-export-20260930-142537.md", MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
|
||||
|
||||
Resources.Culture = new CultureInfo("zh-Hans");
|
||||
Assert.AreEqual("MyRepo-导出-20260930-142537.md", MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagTableCellsEscapePipesAndLineBreaks()
|
||||
{
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
var tag = new TagModel(1, "a|b", RgbColor.Parse("#112233"), "first\nsecond");
|
||||
string markdown = MarkdownExporter.Export("W",
|
||||
[new ColumnModel(1, "C", string.Empty, 1, 1)],
|
||||
[],
|
||||
[(tag, 0L)],
|
||||
ExportedAt);
|
||||
|
||||
StringAssert.Contains(markdown, "| a\\|b | #112233 | first second | 0 |");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using YKanBan.Ipc;
|
||||
|
||||
namespace YKanBan.Tests.Ipc;
|
||||
|
||||
/// <summary>Tests for the IPC wire protocol codec.</summary>
|
||||
[TestClass]
|
||||
public class IpcProtocolTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void ShowMainEncodesAsSingleLine()
|
||||
{
|
||||
Assert.AreEqual("show\n", IpcProtocol.Encode(new LaunchCommand.ShowMain()));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OpenWorkspaceEncodesCommandAndPathLines()
|
||||
{
|
||||
Assert.AreEqual(
|
||||
"open\nD:\\my repo\n",
|
||||
IpcProtocol.Encode(new LaunchCommand.OpenWorkspace(@"D:\my repo")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void RoundTripPreservesCommands()
|
||||
{
|
||||
LaunchCommand[] commands =
|
||||
[
|
||||
new LaunchCommand.ShowMain(),
|
||||
new LaunchCommand.OpenWorkspace(@"D:\my repo"),
|
||||
new LaunchCommand.OpenWorkspace("/home/user/仓库"),
|
||||
];
|
||||
|
||||
foreach (LaunchCommand command in commands)
|
||||
{
|
||||
Assert.AreEqual(command, IpcProtocol.Decode(IpcProtocol.Encode(command)));
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DecodeToleratesMissingTrailingNewline()
|
||||
{
|
||||
Assert.AreEqual(new LaunchCommand.ShowMain(), IpcProtocol.Decode("show"));
|
||||
Assert.AreEqual(
|
||||
new LaunchCommand.OpenWorkspace(@"C:\x"),
|
||||
IpcProtocol.Decode("open\nC:\\x"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DecodePreservesPathsWithSpacesAndUnicode()
|
||||
{
|
||||
LaunchCommand command = IpcProtocol.Decode("open\nD:\\我的 仓库\n");
|
||||
Assert.AreEqual(new LaunchCommand.OpenWorkspace(@"D:\我的 仓库"), command);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DecodeRejectsEmptyPayload()
|
||||
{
|
||||
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode(string.Empty));
|
||||
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode("\n"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DecodeRejectsUnknownCommand()
|
||||
{
|
||||
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode("frobnicate\n"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DecodeRejectsOpenWithoutPath()
|
||||
{
|
||||
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode("open\n"));
|
||||
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode("open"));
|
||||
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode("open\n\n"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DecodeRejectsContentAfterShow()
|
||||
{
|
||||
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode("show\nextra\n"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EncodeRejectsNullCommand()
|
||||
{
|
||||
Assert.ThrowsExactly<InvalidOperationException>(() => IpcProtocol.Encode(null!));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using YKanBan.Ipc;
|
||||
|
||||
namespace YKanBan.Tests.Ipc;
|
||||
|
||||
/// <summary>Tests for command-line argument parsing.</summary>
|
||||
[TestClass]
|
||||
public class LaunchArgumentsTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void NoArgumentsYieldShowMain()
|
||||
{
|
||||
Assert.AreEqual(new LaunchCommand.ShowMain(), LaunchArguments.Parse([]));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void BlankArgumentsOnlyYieldShowMain()
|
||||
{
|
||||
Assert.AreEqual(new LaunchCommand.ShowMain(), LaunchArguments.Parse(["", " "]));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SingleArgumentBecomesWorkspacePath()
|
||||
{
|
||||
Assert.AreEqual(
|
||||
new LaunchCommand.OpenWorkspace(@"D:\repo"),
|
||||
LaunchArguments.Parse([@"D:\repo"]));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PathWithSpacesIsPreserved()
|
||||
{
|
||||
Assert.AreEqual(
|
||||
new LaunchCommand.OpenWorkspace(@"D:\my repo\ws"),
|
||||
LaunchArguments.Parse([@"D:\my repo\ws"]));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FirstMeaningfulArgumentWins()
|
||||
{
|
||||
Assert.AreEqual(
|
||||
new LaunchCommand.OpenWorkspace(@"D:\a"),
|
||||
LaunchArguments.Parse([@"D:\a", @"D:\b"]));
|
||||
Assert.AreEqual(
|
||||
new LaunchCommand.OpenWorkspace(@"D:\b"),
|
||||
LaunchArguments.Parse(["", @"D:\b", @"D:\c"]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.Tests.Models;
|
||||
|
||||
/// <summary>Tests for the RGB color value type and its #RRGGBB text conversions.</summary>
|
||||
[TestClass]
|
||||
public class RgbColorTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void ParseExtractsComponents()
|
||||
{
|
||||
RgbColor color = RgbColor.Parse("#ff0a00");
|
||||
Assert.AreEqual(new RgbColor(0xFF, 0x0A, 0x00), color);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParseAcceptsUppercaseAndMixedCaseHex()
|
||||
{
|
||||
Assert.AreEqual(new RgbColor(0xAB, 0xCD, 0xEF), RgbColor.Parse("#ABCDEF"));
|
||||
Assert.AreEqual(new RgbColor(0xAB, 0xCD, 0xEF), RgbColor.Parse("#aBcDeF"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("ff0000")]
|
||||
[DataRow("#ff000")]
|
||||
[DataRow("#ff00000")]
|
||||
[DataRow("#gg0000")]
|
||||
[DataRow("#ff 000")]
|
||||
[DataRow(" #ff0000")]
|
||||
[DataRow("#ff0000 ")]
|
||||
[DataRow("#")]
|
||||
[DataRow("")]
|
||||
public void TryParseRejectsMalformedText(string text)
|
||||
{
|
||||
Assert.IsFalse(RgbColor.TryParse(text, out _));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TryParseRejectsNull()
|
||||
{
|
||||
Assert.IsFalse(RgbColor.TryParse(null, out _));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParseThrowsFormatExceptionForMalformedText()
|
||||
{
|
||||
Assert.ThrowsExactly<FormatException>(() => RgbColor.Parse("red"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ToStringProducesCanonicalLowercaseForm()
|
||||
{
|
||||
Assert.AreEqual("#ee0a0a", new RgbColor(0xEE, 0x0A, 0x0A).ToString());
|
||||
|
||||
// Uppercase input normalizes to the canonical lowercase output.
|
||||
Assert.AreEqual("#ee0a0a", RgbColor.Parse("#EE0A0A").ToString());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EqualityComparesComponents()
|
||||
{
|
||||
Assert.AreEqual(RgbColor.Parse("#ff0000"), RgbColor.Parse("#FF0000"));
|
||||
Assert.AreNotEqual(RgbColor.Parse("#ff0000"), RgbColor.Parse("#ff0001"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TextRoundTripPreservesColor()
|
||||
{
|
||||
RgbColor original = new(0x12, 0x34, 0x56);
|
||||
Assert.AreEqual(original, RgbColor.Parse(original.ToString()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using YKanBan.Search;
|
||||
|
||||
namespace YKanBan.Tests.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Structural comparer for search AST nodes, used by assertions only. The
|
||||
/// AST records compare by reference for their Terms collections by design
|
||||
/// (see the YYC MARK note in SearchNodes.cs), so tests provide equality
|
||||
/// explicitly.
|
||||
/// </summary>
|
||||
public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
|
||||
{
|
||||
/// <summary>Shared comparer instance.</summary>
|
||||
public static SearchNodeComparer Instance { get; } = new();
|
||||
|
||||
/// <summary>Determines structural equality of two nodes.</summary>
|
||||
public bool Equals(SearchNode? x, SearchNode? y)
|
||||
{
|
||||
if (ReferenceEquals(x, y))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (x is null || y is null || x.GetType() != y.GetType())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return (x, y) switch
|
||||
{
|
||||
(SearchNode.Or a, SearchNode.Or b) => SequencesEqual(a.Terms, b.Terms),
|
||||
(SearchNode.And a, SearchNode.And b) => SequencesEqual(a.Terms, b.Terms),
|
||||
(SearchNode.FreeText a, SearchNode.FreeText b) => a.Text == b.Text,
|
||||
(SearchNode.FieldText a, SearchNode.FieldText b) => a.Field == b.Field && a.Text == b.Text,
|
||||
(SearchNode.TagName a, SearchNode.TagName b) => a.Name == b.Name,
|
||||
(SearchNode.ColumnTitle a, SearchNode.ColumnTitle b) => a.Title == b.Title,
|
||||
(SearchNode.CardId a, SearchNode.CardId b) => a.Id == b.Id,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Not supported: the comparer exists for assertions, not hashing.</summary>
|
||||
public int GetHashCode(SearchNode obj) =>
|
||||
throw new NotSupportedException("Structural comparison for assertions only; hashing is not supported.");
|
||||
|
||||
/// <summary>Order-sensitive element-wise comparison.</summary>
|
||||
private static bool SequencesEqual(IReadOnlyList<SearchNode> x, IReadOnlyList<SearchNode> y)
|
||||
{
|
||||
if (x.Count != y.Count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return Enumerable.Zip(x, y, (a, b) => (a, b)).All(pair => Instance.Equals(pair.a, pair.b));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
using YKanBan.Search;
|
||||
|
||||
namespace YKanBan.Tests.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the search parser: the full grammar branches plus the strict
|
||||
/// failure behavior (malformed input always throws SearchSyntaxException).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class SearchQueryParserTests
|
||||
{
|
||||
/// <summary>Parses and asserts structural equality against the expected AST.</summary>
|
||||
private static void AssertParsesTo(SearchNode expected, string text)
|
||||
{
|
||||
SearchNode? parsed = SearchQueryParser.Parse(text);
|
||||
Assert.IsNotNull(parsed, $"Blank-looking input: '{text}'.");
|
||||
Assert.AreEqual(expected, parsed, SearchNodeComparer.Instance);
|
||||
}
|
||||
|
||||
/// <summary>Asserts that the input violates the grammar.</summary>
|
||||
private static void AssertSyntaxError(string text)
|
||||
{
|
||||
Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse(text));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void BlankInputReturnsNull()
|
||||
{
|
||||
Assert.IsNull(SearchQueryParser.Parse(string.Empty));
|
||||
Assert.IsNull(SearchQueryParser.Parse(" "));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SingleWordIsFreeText()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.FreeText("login"), "login");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AdjacentWordsAreImplicitAnd()
|
||||
{
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([new SearchNode.FreeText("fix"), new SearchNode.FreeText("login")]),
|
||||
"fix login");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ExplicitAndKeyword()
|
||||
{
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||
"a AND b");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OrKeyword()
|
||||
{
|
||||
AssertParsesTo(
|
||||
new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||
"a OR b");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ImplicitAndBindsTighterThanOr()
|
||||
{
|
||||
AssertParsesTo(
|
||||
new SearchNode.Or([
|
||||
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||
new SearchNode.FreeText("c")]),
|
||||
"a b OR c");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParenthesesForceGrouping()
|
||||
{
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([
|
||||
new SearchNode.FreeText("a"),
|
||||
new SearchNode.Or([new SearchNode.FreeText("b"), new SearchNode.FreeText("c")])]),
|
||||
"a (b OR c)");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NestedParenthesesCollapse()
|
||||
{
|
||||
AssertParsesTo(
|
||||
new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||
"((a OR b))");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LowercaseKeywordsArePlainWords()
|
||||
{
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([
|
||||
new SearchNode.FreeText("a"),
|
||||
new SearchNode.FreeText("and"),
|
||||
new SearchNode.FreeText("or"),
|
||||
new SearchNode.FreeText("b")]),
|
||||
"a and or b");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PhraseIsFreeText()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.FreeText("hello world"), "\"hello world\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PhraseSupportsEscapes()
|
||||
{
|
||||
// Escaped quote, escaped backslash, and a lone backslash kept literally.
|
||||
AssertParsesTo(new SearchNode.FreeText("a\"b"), "\"a\\\"b\"");
|
||||
AssertParsesTo(new SearchNode.FreeText("a\\b"), "\"a\\\\b\"");
|
||||
AssertParsesTo(new SearchNode.FreeText("C:\\x"), "\"C:\\x\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagQualifier()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.TagName("bug"), "tag:bug");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagQualifierAcceptsPhraseValue()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.TagName("a b"), "tag:\"a b\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TitleAndContentQualifiers()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.FieldText(SearchField.Title, "foo"), "title:foo");
|
||||
AssertParsesTo(new SearchNode.FieldText(SearchField.Content, "foo"), "content:foo");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnQualifierAcceptsPhraseValue()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.ColumnTitle("To Do"), "column:\"To Do\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void IdQualifierParsesNumber()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.CardId(42), "id:42");
|
||||
AssertParsesTo(new SearchNode.CardId(12), "id:\"12\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void QualifierKeysAreCaseSensitive()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.FreeText("Tag:x"), "Tag:x");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnterminatedPhraseIsAnError()
|
||||
{
|
||||
AssertSyntaxError("\"abc def");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnbalancedOpenParenIsAnError()
|
||||
{
|
||||
AssertSyntaxError("(a");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void StrayCloseParenIsAnError()
|
||||
{
|
||||
AssertSyntaxError("a)");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EmptyParensAreAnError()
|
||||
{
|
||||
AssertSyntaxError("()");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DanglingOrIsAnError()
|
||||
{
|
||||
AssertSyntaxError("a OR");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DanglingAndIsAnError()
|
||||
{
|
||||
AssertSyntaxError("a AND");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LeadingAndIsAnError()
|
||||
{
|
||||
AssertSyntaxError("AND a");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OperatorAtOperandPositionIsAnError()
|
||||
{
|
||||
AssertSyntaxError("a AND OR b");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void QualifierWithoutValueIsAnError()
|
||||
{
|
||||
AssertSyntaxError("tag:");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NonNumericIdIsAnError()
|
||||
{
|
||||
AssertSyntaxError("id:12x");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SyntaxErrorCarriesDescriptiveMessage()
|
||||
{
|
||||
SearchSyntaxException ex = Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse("a AND"));
|
||||
Assert.IsFalse(string.IsNullOrEmpty(ex.Message));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using YKanBan.Search;
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
|
||||
namespace YKanBan.Tests.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the query-to-SQL compiler, executed end-to-end against a
|
||||
/// fixture workspace database.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class SearchSqlCompilerTests
|
||||
{
|
||||
/// <summary>Owns a workspace with a fixed card/tag fixture.</summary>
|
||||
private sealed class SearchFixture : IDisposable
|
||||
{
|
||||
public TempDirectory Directory { get; } = new();
|
||||
|
||||
public SqliteConnection Connection { get; }
|
||||
|
||||
public SearchFixture()
|
||||
{
|
||||
WorkspaceInitializer.Initialize(Directory.FullPath);
|
||||
using (SqliteConnection setup = SqliteTestHelper.OpenWorkspace(Directory.FullPath))
|
||||
{
|
||||
// Columns: 1 "To Do", 2 "In Progress".
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('To Do', '', 1, 1);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('In Progress', '', 1, 1);");
|
||||
|
||||
// Cards: 1 titled, 2 title-or-content matches, 3 untitled, 4 wildcard chars.
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, 'Fix login', 'Cannot sign in', 1, 1);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (2, 'Green apple', 'the apple pie', 1, 1);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (2, '', 'banana split', 1, 1);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, '100% done', 'a_b test', 1, 1);");
|
||||
|
||||
// Tags: mixed case names plus one containing spaces.
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO tags (name, color, description) VALUES ('Bug', '#ff0000', '');");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO tags (name, color, description) VALUES ('UI', '#00ff00', '');");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO tags (name, color, description) VALUES ('release notes', '#0000ff', '');");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 1);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO card_tags (card_id, tag_id) VALUES (2, 2);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO card_tags (card_id, tag_id) VALUES (3, 2);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO card_tags (card_id, tag_id) VALUES (4, 3);");
|
||||
}
|
||||
|
||||
Connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath);
|
||||
}
|
||||
|
||||
/// <summary>Runs a query and returns the ids of the matching cards.</summary>
|
||||
public List<long> Search(string queryText)
|
||||
{
|
||||
SearchNode? query = SearchQueryParser.Parse(queryText);
|
||||
Assert.IsNotNull(query, "Blank fixture queries are not expected here.");
|
||||
CompiledSearch compiled = SearchSqlCompiler.Compile(query);
|
||||
|
||||
using var command = Connection.CreateCommand();
|
||||
command.CommandText = $"SELECT c.id FROM cards c WHERE {compiled.Predicate} ORDER BY c.id ASC;";
|
||||
foreach ((string name, object value) in compiled.Parameters)
|
||||
{
|
||||
command.Parameters.AddWithValue(name, value);
|
||||
}
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var ids = new List<long>();
|
||||
while (reader.Read())
|
||||
{
|
||||
ids.Add(reader.GetInt64(0));
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Connection.Dispose();
|
||||
Directory.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FreeTextMatchesTitleOrContentCaseInsensitively()
|
||||
{
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple"));
|
||||
CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("login"));
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("APPLE"));
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("pie"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FieldQualifiersScopeToTheirField()
|
||||
{
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("title:apple"));
|
||||
CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("content:banana"));
|
||||
Assert.AreEqual(0, fixture.Search("title:pie").Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagQualifierMatchesExactlyAndCaseInsensitively()
|
||||
{
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("tag:bug"));
|
||||
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("tag:ui"));
|
||||
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("tag:\"release notes\""));
|
||||
|
||||
// Exact match: prefixes and substrings do not hit.
|
||||
Assert.AreEqual(0, fixture.Search("tag:bu").Count);
|
||||
Assert.AreEqual(0, fixture.Search("tag:release").Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnQualifierMatchesColumnTitleExactly()
|
||||
{
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 1L, 4L }, fixture.Search("column:\"to do\""));
|
||||
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("column:\"in progress\""));
|
||||
|
||||
// Not a prefix or substring match.
|
||||
Assert.AreEqual(0, fixture.Search("column:To").Count);
|
||||
Assert.AreEqual(0, fixture.Search("column:progress").Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void IdQualifierMatchesExactly()
|
||||
{
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("id:3"));
|
||||
Assert.AreEqual(0, fixture.Search("id:99").Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AndOrCombination()
|
||||
{
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("apple OR banana"));
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple AND id:2"));
|
||||
Assert.AreEqual(0, fixture.Search("apple AND id:1").Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParenthesizedGrouping()
|
||||
{
|
||||
using var fixture = new SearchFixture();
|
||||
|
||||
// (apple OR banana) hits cards 2,3; intersected with column "In Progress" (2,3).
|
||||
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("(apple OR banana) AND column:\"In Progress\""));
|
||||
|
||||
// ...while column "To Do" holds cards 1,4 — the intersection is empty.
|
||||
Assert.AreEqual(0, fixture.Search("(apple OR banana) AND column:\"To Do\"").Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LikeWildcardsInUserTextMatchLiterally()
|
||||
{
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("100%"));
|
||||
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("a_b"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CompiledPredicateUsesNamedParameters()
|
||||
{
|
||||
CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("x"));
|
||||
|
||||
StringAssert.Contains(compiled.Predicate, "$p0");
|
||||
StringAssert.Contains(compiled.Predicate, "$p1");
|
||||
Assert.AreEqual(2, compiled.Parameters.Count);
|
||||
Assert.AreEqual("%x%", compiled.Parameters[0].Value);
|
||||
Assert.AreEqual("%x%", compiled.Parameters[1].Value);
|
||||
}
|
||||
}
|
||||
@@ -235,7 +235,7 @@ public class WorkspaceRepositoryTests
|
||||
using var fixture = new RepositoryFixture();
|
||||
fixture.Clock = 2000;
|
||||
|
||||
TagModel result = fixture.Repository.UpdateTag(fixture.BugTagId, "bug", "#ff0000", "");
|
||||
TagModel result = fixture.Repository.UpdateTag(fixture.BugTagId, "bug", RgbColor.Parse("#ff0000"), "");
|
||||
|
||||
Assert.AreEqual("bug", result.Name);
|
||||
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
|
||||
@@ -247,10 +247,10 @@ public class WorkspaceRepositoryTests
|
||||
using var fixture = new RepositoryFixture();
|
||||
fixture.Clock = 3000;
|
||||
|
||||
TagModel updated = fixture.Repository.UpdateTag(fixture.BugTagId, "defect", "#ee0a0a", "desc");
|
||||
TagModel updated = fixture.Repository.UpdateTag(fixture.BugTagId, "defect", RgbColor.Parse("#ee0a0a"), "desc");
|
||||
|
||||
Assert.AreEqual("defect", updated.Name);
|
||||
Assert.AreEqual("#ee0a0a", updated.Color);
|
||||
Assert.AreEqual(new RgbColor(0xEE, 0x0A, 0x0A), updated.Color);
|
||||
Assert.AreEqual("desc", updated.Description);
|
||||
Assert.AreEqual(3000L, fixture.LastEditedAt);
|
||||
}
|
||||
|
||||
+19
-1
@@ -1,9 +1,27 @@
|
||||
<Application xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="YKanBan.App"
|
||||
xmlns:semi="https://irihi.tech/semi"
|
||||
RequestedThemeVariant="Default">
|
||||
|
||||
<Application.Styles>
|
||||
<FluentTheme />
|
||||
<semi:SemiTheme />
|
||||
</Application.Styles>
|
||||
|
||||
<!--Custom colors MUST be declared as Light/Dark pairs inside ThemeDictionaries
|
||||
and consumed via DynamicResource so theme switches restyle everything.-->
|
||||
<Application.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.ThemeDictionaries>
|
||||
<ResourceDictionary x:Key="Light">
|
||||
<SolidColorBrush x:Key="SidebarBackgroundBrush" Color="#F6F7F9"/>
|
||||
<SolidColorBrush x:Key="SidebarBorderBrush" Color="#E2E4EA"/>
|
||||
</ResourceDictionary>
|
||||
<ResourceDictionary x:Key="Dark">
|
||||
<SolidColorBrush x:Key="SidebarBackgroundBrush" Color="#1C1E24"/>
|
||||
<SolidColorBrush x:Key="SidebarBorderBrush" Color="#2C2F37"/>
|
||||
</ResourceDictionary>
|
||||
</ResourceDictionary.ThemeDictionaries>
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
+84
-3
@@ -1,16 +1,29 @@
|
||||
using System.Linq;
|
||||
using System.Globalization;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Data.Core;
|
||||
using Avalonia.Data.Core.Plugins;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Styling;
|
||||
using Avalonia.Threading;
|
||||
using YKanBan.Ipc;
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.ViewModels;
|
||||
using YKanBan.Views;
|
||||
using Resx = YKanBan.Resources;
|
||||
|
||||
namespace YKanBan;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
/// <summary>Composition root, created before the main window.</summary>
|
||||
public static AppServices Services { get; } = new();
|
||||
|
||||
/// <summary>The language applied at startup; a live selection differing from it needs a restart.</summary>
|
||||
public static string StartupLanguage { get; private set; } = AppConfig.DefaultLanguage;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
@@ -21,16 +34,84 @@ public partial class App : Application
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
DisableAvaloniaDataAnnotationValidation();
|
||||
|
||||
// Startup order: apply the configured culture (and its RTL flow direction)
|
||||
// and the theme BEFORE creating the main window.
|
||||
CultureInfo culture = ResolveCulture(Services.Config.Language);
|
||||
StartupLanguage = Services.Config.Language;
|
||||
Resx.Culture = culture;
|
||||
ApplyTheme(Services.Config.Theme);
|
||||
|
||||
var mainViewModel = new MainWindowViewModel(Services);
|
||||
desktop.MainWindow = new MainWindow
|
||||
{
|
||||
DataContext = new MainWindowViewModel(),
|
||||
DataContext = mainViewModel,
|
||||
|
||||
// RTL detection drives the whole window flow direction; the two
|
||||
// supported languages are LTR, but the infrastructure stays in
|
||||
// place for future languages.
|
||||
FlowDirection = culture.TextInfo.IsRightToLeft
|
||||
? FlowDirection.RightToLeft
|
||||
: FlowDirection.LeftToRight,
|
||||
};
|
||||
|
||||
// Primary instance: serve launch commands forwarded by secondary instances.
|
||||
Program.SingleInstance?.StartServer(command => HandleLaunchCommand(desktop, mainViewModel, command));
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
|
||||
private void DisableAvaloniaDataAnnotationValidation()
|
||||
/// <summary>Resolves the configured language to a culture, falling back to English.</summary>
|
||||
public static CultureInfo ResolveCulture(string language)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new CultureInfo(language);
|
||||
}
|
||||
catch (CultureNotFoundException)
|
||||
{
|
||||
return new CultureInfo(AppConfig.DefaultLanguage);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Applies a theme selection immediately; Default follows the operating system.</summary>
|
||||
public static void ApplyTheme(ThemeOption option)
|
||||
{
|
||||
if (Current is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Current.RequestedThemeVariant = option switch
|
||||
{
|
||||
ThemeOption.Light => ThemeVariant.Light,
|
||||
ThemeOption.Dark => ThemeVariant.Dark,
|
||||
_ => ThemeVariant.Default,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Activates the window for a forwarded command; OpenWorkspace also switches to it.</summary>
|
||||
private static void HandleLaunchCommand(
|
||||
IClassicDesktopStyleApplicationLifetime desktop,
|
||||
MainWindowViewModel mainViewModel,
|
||||
LaunchCommand command)
|
||||
{
|
||||
// IPC delivery happens on a background thread; hop to the UI thread.
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
if (desktop.MainWindow is { } window)
|
||||
{
|
||||
window.Show();
|
||||
window.Activate();
|
||||
}
|
||||
if (command is LaunchCommand.OpenWorkspace open)
|
||||
{
|
||||
mainViewModel.OpenWorkspaceFromLaunch(open.Path);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void DisableAvaloniaDataAnnotationValidation()
|
||||
{
|
||||
var dataValidationPluginsToRemove =
|
||||
BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray();
|
||||
|
||||
@@ -21,4 +21,169 @@
|
||||
<data name="PresetColumn_Done" xml:space="preserve">
|
||||
<value>Done</value>
|
||||
</data>
|
||||
<data name="Export_FileNamePattern" xml:space="preserve">
|
||||
<value>{0}-export-{1:yyyyMMdd-HHmmss}.md</value>
|
||||
</data>
|
||||
<data name="Export_TimePattern" xml:space="preserve">
|
||||
<value>yyyy-MM-dd HH:mm:ss</value>
|
||||
</data>
|
||||
<data name="Export_CardTimePattern" xml:space="preserve">
|
||||
<value>yyyy-MM-dd HH:mm</value>
|
||||
</data>
|
||||
<data name="Export_WorkspaceHeading" xml:space="preserve">
|
||||
<value># {0}</value>
|
||||
</data>
|
||||
<data name="Export_ExportedAtLine" xml:space="preserve">
|
||||
<value>> Exported at: {0}</value>
|
||||
</data>
|
||||
<data name="Export_ColumnHeading" xml:space="preserve">
|
||||
<value>## Column: {0} ({1})</value>
|
||||
</data>
|
||||
<data name="Export_TagsLine" xml:space="preserve">
|
||||
<value>- Tags: {0}</value>
|
||||
</data>
|
||||
<data name="Export_CreatedModifiedLine" xml:space="preserve">
|
||||
<value>- Created: {0} Modified: {1}</value>
|
||||
</data>
|
||||
<data name="Export_TagsSummaryHeading" xml:space="preserve">
|
||||
<value>## Tags</value>
|
||||
</data>
|
||||
<data name="Export_TagsTableHeader" xml:space="preserve">
|
||||
<value>| Name | Color | Description | Usage |</value>
|
||||
</data>
|
||||
<data name="App_Name" xml:space="preserve">
|
||||
<value>YKanBan</value>
|
||||
</data>
|
||||
<data name="Common_Yes" xml:space="preserve">
|
||||
<value>Yes</value>
|
||||
</data>
|
||||
<data name="Common_No" xml:space="preserve">
|
||||
<value>No</value>
|
||||
</data>
|
||||
<data name="Common_Close" xml:space="preserve">
|
||||
<value>Close</value>
|
||||
</data>
|
||||
<data name="Sidebar_Welcome" xml:space="preserve">
|
||||
<value>Welcome</value>
|
||||
</data>
|
||||
<data name="Sidebar_OpenProject" xml:space="preserve">
|
||||
<value>Open project…</value>
|
||||
</data>
|
||||
<data name="Sidebar_SortLabel" xml:space="preserve">
|
||||
<value>Sort</value>
|
||||
</data>
|
||||
<data name="Sidebar_Sort_NameAsc" xml:space="preserve">
|
||||
<value>Name A to Z</value>
|
||||
</data>
|
||||
<data name="Sidebar_Sort_NameDesc" xml:space="preserve">
|
||||
<value>Name Z to A</value>
|
||||
</data>
|
||||
<data name="Sidebar_Sort_RecentlyUpdated" xml:space="preserve">
|
||||
<value>Recently updated</value>
|
||||
</data>
|
||||
<data name="Sidebar_Settings" xml:space="preserve">
|
||||
<value>Settings</value>
|
||||
</data>
|
||||
<data name="Sidebar_About" xml:space="preserve">
|
||||
<value>About</value>
|
||||
</data>
|
||||
<data name="Sidebar_RemoveFromList" xml:space="preserve">
|
||||
<value>Remove from list</value>
|
||||
</data>
|
||||
<data name="Welcome_Hint" xml:space="preserve">
|
||||
<value>Open or create a workspace from the left.</value>
|
||||
</data>
|
||||
<data name="Dialog_InitializeTitle" xml:space="preserve">
|
||||
<value>Initialize workspace?</value>
|
||||
</data>
|
||||
<data name="Dialog_InitializeMessage" xml:space="preserve">
|
||||
<value>There is no .ykanban structure in "{0}". Initialize it here?</value>
|
||||
</data>
|
||||
<data name="Settings_Title" xml:space="preserve">
|
||||
<value>Settings</value>
|
||||
</data>
|
||||
<data name="Settings_Language" xml:space="preserve">
|
||||
<value>Language</value>
|
||||
</data>
|
||||
<data name="Settings_Language_RestartNotice" xml:space="preserve">
|
||||
<value>Takes effect after restart</value>
|
||||
</data>
|
||||
<data name="Settings_LanguageEnglish" xml:space="preserve">
|
||||
<value>English</value>
|
||||
</data>
|
||||
<data name="Settings_LanguageChinese" xml:space="preserve">
|
||||
<value>简体中文</value>
|
||||
</data>
|
||||
<data name="Settings_Theme" xml:space="preserve">
|
||||
<value>Theme</value>
|
||||
</data>
|
||||
<data name="Settings_ThemeLight" xml:space="preserve">
|
||||
<value>Light</value>
|
||||
</data>
|
||||
<data name="Settings_ThemeDark" xml:space="preserve">
|
||||
<value>Dark</value>
|
||||
</data>
|
||||
<data name="Settings_ThemeFollowSystem" xml:space="preserve">
|
||||
<value>Follow system</value>
|
||||
</data>
|
||||
<data name="Settings_Confirmations" xml:space="preserve">
|
||||
<value>Confirmations</value>
|
||||
</data>
|
||||
<data name="Settings_ConfirmDeleteCard" xml:space="preserve">
|
||||
<value>Ask before deleting a card</value>
|
||||
</data>
|
||||
<data name="Settings_ConfirmDeleteColumn" xml:space="preserve">
|
||||
<value>Ask before deleting a column</value>
|
||||
</data>
|
||||
<data name="Settings_ConfirmDeleteTag" xml:space="preserve">
|
||||
<value>Ask before deleting a tag</value>
|
||||
</data>
|
||||
<data name="Settings_ConfirmDiscardEdit" xml:space="preserve">
|
||||
<value>Ask before discarding card edits</value>
|
||||
</data>
|
||||
<data name="About_Title" xml:space="preserve">
|
||||
<value>About</value>
|
||||
</data>
|
||||
<data name="About_Version" xml:space="preserve">
|
||||
<value>Version {0}</value>
|
||||
</data>
|
||||
<data name="About_Repository" xml:space="preserve">
|
||||
<value>Repository</value>
|
||||
</data>
|
||||
<data name="About_RepositoryUrl" xml:space="preserve">
|
||||
<value>(to be filled)</value>
|
||||
</data>
|
||||
<data name="About_License" xml:space="preserve">
|
||||
<value>License</value>
|
||||
</data>
|
||||
<data name="About_LicenseValue" xml:space="preserve">
|
||||
<value>(to be filled)</value>
|
||||
</data>
|
||||
<data name="State_LockConflict_Title" xml:space="preserve">
|
||||
<value>Workspace locked</value>
|
||||
</data>
|
||||
<data name="State_LockConflict_Detail" xml:space="preserve">
|
||||
<value>The workspace is locked by another instance.</value>
|
||||
</data>
|
||||
<data name="State_NotInitialized_Title" xml:space="preserve">
|
||||
<value>No workspace here</value>
|
||||
</data>
|
||||
<data name="State_NotInitialized_Detail" xml:space="preserve">
|
||||
<value>The folder has no .ykanban structure.</value>
|
||||
</data>
|
||||
<data name="State_DirectoryMissing_Title" xml:space="preserve">
|
||||
<value>Folder missing</value>
|
||||
</data>
|
||||
<data name="State_DirectoryMissing_Detail" xml:space="preserve">
|
||||
<value>The folder does not exist on disk.</value>
|
||||
</data>
|
||||
<data name="State_SchemaVersion_Title" xml:space="preserve">
|
||||
<value>Incompatible database</value>
|
||||
</data>
|
||||
<data name="State_SchemaVersion_Detail" xml:space="preserve">
|
||||
<value>The workspace was written by a newer version.</value>
|
||||
</data>
|
||||
<data name="State_Unknown_Title" xml:space="preserve">
|
||||
<value>Open failed</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -21,4 +21,169 @@
|
||||
<data name="PresetColumn_Done" xml:space="preserve">
|
||||
<value>已完成</value>
|
||||
</data>
|
||||
<data name="Export_FileNamePattern" xml:space="preserve">
|
||||
<value>{0}-导出-{1:yyyyMMdd-HHmmss}.md</value>
|
||||
</data>
|
||||
<data name="Export_TimePattern" xml:space="preserve">
|
||||
<value>yyyy年M月d日 HH:mm</value>
|
||||
</data>
|
||||
<data name="Export_CardTimePattern" xml:space="preserve">
|
||||
<value>yyyy年M月d日 HH:mm</value>
|
||||
</data>
|
||||
<data name="Export_WorkspaceHeading" xml:space="preserve">
|
||||
<value># {0}</value>
|
||||
</data>
|
||||
<data name="Export_ExportedAtLine" xml:space="preserve">
|
||||
<value>> 导出时间:{0}</value>
|
||||
</data>
|
||||
<data name="Export_ColumnHeading" xml:space="preserve">
|
||||
<value>## 列:{0}({1})</value>
|
||||
</data>
|
||||
<data name="Export_TagsLine" xml:space="preserve">
|
||||
<value>- 标签:{0}</value>
|
||||
</data>
|
||||
<data name="Export_CreatedModifiedLine" xml:space="preserve">
|
||||
<value>- 创建:{0} 修改:{1}</value>
|
||||
</data>
|
||||
<data name="Export_TagsSummaryHeading" xml:space="preserve">
|
||||
<value>## 标签总表</value>
|
||||
</data>
|
||||
<data name="Export_TagsTableHeader" xml:space="preserve">
|
||||
<value>| 名称 | 颜色 | 描述 | 使用数 |</value>
|
||||
</data>
|
||||
<data name="App_Name" xml:space="preserve">
|
||||
<value>YKanBan</value>
|
||||
</data>
|
||||
<data name="Common_Yes" xml:space="preserve">
|
||||
<value>是</value>
|
||||
</data>
|
||||
<data name="Common_No" xml:space="preserve">
|
||||
<value>否</value>
|
||||
</data>
|
||||
<data name="Common_Close" xml:space="preserve">
|
||||
<value>关闭</value>
|
||||
</data>
|
||||
<data name="Sidebar_Welcome" xml:space="preserve">
|
||||
<value>欢迎页</value>
|
||||
</data>
|
||||
<data name="Sidebar_OpenProject" xml:space="preserve">
|
||||
<value>打开项目…</value>
|
||||
</data>
|
||||
<data name="Sidebar_SortLabel" xml:space="preserve">
|
||||
<value>排序</value>
|
||||
</data>
|
||||
<data name="Sidebar_Sort_NameAsc" xml:space="preserve">
|
||||
<value>名称 A 到 Z</value>
|
||||
</data>
|
||||
<data name="Sidebar_Sort_NameDesc" xml:space="preserve">
|
||||
<value>名称 Z 到 A</value>
|
||||
</data>
|
||||
<data name="Sidebar_Sort_RecentlyUpdated" xml:space="preserve">
|
||||
<value>最近更新</value>
|
||||
</data>
|
||||
<data name="Sidebar_Settings" xml:space="preserve">
|
||||
<value>设置</value>
|
||||
</data>
|
||||
<data name="Sidebar_About" xml:space="preserve">
|
||||
<value>关于</value>
|
||||
</data>
|
||||
<data name="Sidebar_RemoveFromList" xml:space="preserve">
|
||||
<value>从列表移除</value>
|
||||
</data>
|
||||
<data name="Welcome_Hint" xml:space="preserve">
|
||||
<value>从左侧打开或新建工作区。</value>
|
||||
</data>
|
||||
<data name="Dialog_InitializeTitle" xml:space="preserve">
|
||||
<value>初始化工作区?</value>
|
||||
</data>
|
||||
<data name="Dialog_InitializeMessage" xml:space="preserve">
|
||||
<value>“{0}”中不存在 .ykanban 数据。在此初始化?</value>
|
||||
</data>
|
||||
<data name="Settings_Title" xml:space="preserve">
|
||||
<value>设置</value>
|
||||
</data>
|
||||
<data name="Settings_Language" xml:space="preserve">
|
||||
<value>语言</value>
|
||||
</data>
|
||||
<data name="Settings_Language_RestartNotice" xml:space="preserve">
|
||||
<value>重启后生效</value>
|
||||
</data>
|
||||
<data name="Settings_LanguageEnglish" xml:space="preserve">
|
||||
<value>English</value>
|
||||
</data>
|
||||
<data name="Settings_LanguageChinese" xml:space="preserve">
|
||||
<value>简体中文</value>
|
||||
</data>
|
||||
<data name="Settings_Theme" xml:space="preserve">
|
||||
<value>主题</value>
|
||||
</data>
|
||||
<data name="Settings_ThemeLight" xml:space="preserve">
|
||||
<value>浅色</value>
|
||||
</data>
|
||||
<data name="Settings_ThemeDark" xml:space="preserve">
|
||||
<value>深色</value>
|
||||
</data>
|
||||
<data name="Settings_ThemeFollowSystem" xml:space="preserve">
|
||||
<value>跟随系统</value>
|
||||
</data>
|
||||
<data name="Settings_Confirmations" xml:space="preserve">
|
||||
<value>操作确认</value>
|
||||
</data>
|
||||
<data name="Settings_ConfirmDeleteCard" xml:space="preserve">
|
||||
<value>删除卡片前确认</value>
|
||||
</data>
|
||||
<data name="Settings_ConfirmDeleteColumn" xml:space="preserve">
|
||||
<value>删除列前确认</value>
|
||||
</data>
|
||||
<data name="Settings_ConfirmDeleteTag" xml:space="preserve">
|
||||
<value>删除标签前确认</value>
|
||||
</data>
|
||||
<data name="Settings_ConfirmDiscardEdit" xml:space="preserve">
|
||||
<value>放弃卡片编辑前确认</value>
|
||||
</data>
|
||||
<data name="About_Title" xml:space="preserve">
|
||||
<value>关于</value>
|
||||
</data>
|
||||
<data name="About_Version" xml:space="preserve">
|
||||
<value>版本 {0}</value>
|
||||
</data>
|
||||
<data name="About_Repository" xml:space="preserve">
|
||||
<value>仓库</value>
|
||||
</data>
|
||||
<data name="About_RepositoryUrl" xml:space="preserve">
|
||||
<value>(待填写)</value>
|
||||
</data>
|
||||
<data name="About_License" xml:space="preserve">
|
||||
<value>许可证</value>
|
||||
</data>
|
||||
<data name="About_LicenseValue" xml:space="preserve">
|
||||
<value>(待填写)</value>
|
||||
</data>
|
||||
<data name="State_LockConflict_Title" xml:space="preserve">
|
||||
<value>工作区已被占用</value>
|
||||
</data>
|
||||
<data name="State_LockConflict_Detail" xml:space="preserve">
|
||||
<value>该工作区正被另一实例锁定。</value>
|
||||
</data>
|
||||
<data name="State_NotInitialized_Title" xml:space="preserve">
|
||||
<value>此处没有工作区</value>
|
||||
</data>
|
||||
<data name="State_NotInitialized_Detail" xml:space="preserve">
|
||||
<value>该文件夹没有 .ykanban 数据。</value>
|
||||
</data>
|
||||
<data name="State_DirectoryMissing_Title" xml:space="preserve">
|
||||
<value>文件夹不存在</value>
|
||||
</data>
|
||||
<data name="State_DirectoryMissing_Detail" xml:space="preserve">
|
||||
<value>该文件夹在磁盘上不存在。</value>
|
||||
</data>
|
||||
<data name="State_SchemaVersion_Title" xml:space="preserve">
|
||||
<value>数据库版本不兼容</value>
|
||||
</data>
|
||||
<data name="State_SchemaVersion_Detail" xml:space="preserve">
|
||||
<value>该工作区由更新版本的程序创建。</value>
|
||||
</data>
|
||||
<data name="State_Unknown_Title" xml:space="preserve">
|
||||
<value>打开失败</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.Export;
|
||||
|
||||
/// <summary>
|
||||
/// Generates the human-readable Markdown snapshot of a whole board. All
|
||||
/// template text and time formats come from the ResX resources in the
|
||||
/// current UI language; the export timestamp uses the per-language pattern,
|
||||
/// card timestamps use the shared minute-precision pattern. The output is
|
||||
/// meant for reading only — there is no re-import.
|
||||
/// </summary>
|
||||
public static class MarkdownExporter
|
||||
{
|
||||
/// <summary>Renders the whole board to Markdown.</summary>
|
||||
/// <param name="workspaceName">Workspace display name (the folder name).</param>
|
||||
/// <param name="columns">All columns, in id order; empty columns are kept.</param>
|
||||
/// <param name="cards">All cards; grouped by column, id order within a column.</param>
|
||||
/// <param name="tags">All tags with usage counts, in id order.</param>
|
||||
/// <param name="exportedAt">Export moment in local time.</param>
|
||||
public static string Export(
|
||||
string workspaceName,
|
||||
IReadOnlyList<ColumnModel> columns,
|
||||
IReadOnlyList<CardModel> cards,
|
||||
IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
|
||||
DateTimeOffset exportedAt)
|
||||
{
|
||||
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
|
||||
|
||||
var builder = new StringBuilder();
|
||||
|
||||
// Header: workspace name and the export timestamp in the UI language's format.
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_WorkspaceHeading, workspaceName));
|
||||
builder.AppendLine(string.Format(
|
||||
culture, Resources.Export_ExportedAtLine, exportedAt.ToString(Resources.Export_TimePattern, culture)));
|
||||
builder.AppendLine();
|
||||
|
||||
// Board body: every column in id order, empty ones included.
|
||||
foreach (ColumnModel column in columns)
|
||||
{
|
||||
IReadOnlyList<CardModel> cardsInColumn = cards.Where(card => card.ColumnId == column.Id).ToArray();
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, column.Title, cardsInColumn.Count));
|
||||
if (column.Description.Length > 0)
|
||||
{
|
||||
builder.AppendLine(SingleLine(column.Description));
|
||||
}
|
||||
builder.AppendLine();
|
||||
|
||||
foreach (CardModel card in cardsInColumn)
|
||||
{
|
||||
AppendCard(builder, card, culture);
|
||||
}
|
||||
}
|
||||
|
||||
AppendTagTable(builder, tags, culture);
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Builds the default export file name in the UI language, e.g. "MyRepo-export-20260930-142537.md".</summary>
|
||||
public static string BuildFileName(string workspaceName, DateTimeOffset exportedAt)
|
||||
{
|
||||
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
|
||||
return string.Format(culture, Resources.Export_FileNamePattern, workspaceName, exportedAt);
|
||||
}
|
||||
|
||||
/// <summary>Appends one card block: heading, body, tags line, timestamps line.</summary>
|
||||
private static void AppendCard(StringBuilder builder, CardModel card, CultureInfo culture)
|
||||
{
|
||||
// Heading: "#id title"; an untitled card shows only the id.
|
||||
builder.AppendLine(card.Title.Length == 0
|
||||
? $"### #{card.Id}"
|
||||
: $"### #{card.Id} {SingleLine(card.Title)}");
|
||||
|
||||
if (card.Content.Length > 0)
|
||||
{
|
||||
builder.AppendLine(card.Content);
|
||||
}
|
||||
|
||||
if (card.Tags.Count > 0)
|
||||
{
|
||||
string names = string.Join(" ", card.Tags.Select(tag => $"`{tag.Name}`"));
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_TagsLine, names));
|
||||
}
|
||||
|
||||
string created = ToLocalTime(card.CreatedAt).ToString(Resources.Export_CardTimePattern, culture);
|
||||
string updated = ToLocalTime(card.UpdatedAt).ToString(Resources.Export_CardTimePattern, culture);
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_CreatedModifiedLine, created, updated));
|
||||
builder.AppendLine();
|
||||
}
|
||||
|
||||
/// <summary>Appends the tag summary table with usage counts; tags with zero usage are included.</summary>
|
||||
private static void AppendTagTable(
|
||||
StringBuilder builder,
|
||||
IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
|
||||
CultureInfo culture)
|
||||
{
|
||||
builder.AppendLine(Resources.Export_TagsSummaryHeading);
|
||||
builder.AppendLine(Resources.Export_TagsTableHeader);
|
||||
builder.AppendLine("|---|---|---|---|");
|
||||
foreach ((TagModel tag, long usage) in tags)
|
||||
{
|
||||
// '|' and line breaks would break the table row; neutralize them.
|
||||
builder.AppendLine($"| {Cell(tag.Name)} | {tag.Color} | {Cell(tag.Description)} | {usage} |");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Formats a table cell: single line with escaped pipe characters.</summary>
|
||||
private static string Cell(string text) => SingleLine(text).Replace("|", "\\|");
|
||||
|
||||
/// <summary>Collapses line breaks so the text stays on one Markdown line.</summary>
|
||||
private static string SingleLine(string text) => text.Replace("\r", string.Empty).Replace("\n", " ");
|
||||
|
||||
/// <summary>Converts stored Unix seconds to a local-time DateTimeOffset.</summary>
|
||||
private static DateTimeOffset ToLocalTime(long unixSeconds) =>
|
||||
DateTimeOffset.FromUnixTimeSeconds(unixSeconds).ToLocalTime();
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
namespace YKanBan.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// Single-instance detection and inter-instance messaging, built on a named
|
||||
/// mutex (detection) and a named pipe (command forwarding). The primary
|
||||
/// instance holds the mutex for its lifetime and serves the pipe; secondary
|
||||
/// instances forward their launch command to the primary and exit.
|
||||
/// </summary>
|
||||
public interface ISingleInstanceService : IDisposable
|
||||
{
|
||||
/// <summary>Attempts to register this process as the single YKanBan instance.</summary>
|
||||
/// <returns>True when this process is the primary instance; false when another one exists.</returns>
|
||||
bool TryAcquireSingleInstance();
|
||||
|
||||
/// <summary>Starts serving launch commands on a background task (primary instance only).</summary>
|
||||
/// <param name="handler">Invoked for each decoded command; runs on a background thread.</param>
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// Not called on a primary instance, or called a second time.
|
||||
/// </exception>
|
||||
void StartServer(Action<LaunchCommand> handler);
|
||||
|
||||
/// <summary>Delivers a command to the primary instance and waits for its acknowledgement.</summary>
|
||||
/// <returns>True when the primary instance acknowledged the command.</returns>
|
||||
bool TrySend(LaunchCommand command);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
namespace YKanBan.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// Text encoding of launch commands on the IPC pipe. A message is one or
|
||||
/// two newline-terminated lines: "show", or "open" followed by the
|
||||
/// workspace path taken verbatim (paths may contain spaces; paths
|
||||
/// containing newlines are not supported). Decoding is strict and throws
|
||||
/// FormatException on malformed payloads.
|
||||
/// </summary>
|
||||
public static class IpcProtocol
|
||||
{
|
||||
/// <summary>Encodes a command into its wire text.</summary>
|
||||
/// <exception cref="InvalidOperationException">The command type is unknown.</exception>
|
||||
public static string Encode(LaunchCommand command) => command switch
|
||||
{
|
||||
LaunchCommand.ShowMain => "show\n",
|
||||
LaunchCommand.OpenWorkspace open => $"open\n{open.Path}\n",
|
||||
_ => throw new InvalidOperationException($"Unsupported launch command: {command?.GetType().Name ?? "null"}"),
|
||||
};
|
||||
|
||||
/// <summary>Decodes wire text into a command; trailing newlines are tolerated.</summary>
|
||||
/// <exception cref="FormatException">The payload is not a valid message.</exception>
|
||||
public static LaunchCommand Decode(string payload)
|
||||
{
|
||||
List<string> lines = payload.Split('\n').ToList();
|
||||
|
||||
// Trailing newlines are a framing detail; drop the empty lines they produce.
|
||||
while (lines.Count > 0 && lines[^1].Length == 0)
|
||||
{
|
||||
lines.RemoveAt(lines.Count - 1);
|
||||
}
|
||||
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
throw new FormatException("Empty IPC payload.");
|
||||
}
|
||||
|
||||
switch (lines[0])
|
||||
{
|
||||
case "show":
|
||||
if (lines.Count != 1)
|
||||
{
|
||||
throw new FormatException($"Unexpected content after 'show': '{lines[1]}'");
|
||||
}
|
||||
return new LaunchCommand.ShowMain();
|
||||
|
||||
case "open":
|
||||
if (lines.Count != 2)
|
||||
{
|
||||
throw new FormatException("'open' requires exactly one path line.");
|
||||
}
|
||||
if (lines[1].Length == 0)
|
||||
{
|
||||
throw new FormatException("'open' requires a non-empty path.");
|
||||
}
|
||||
return new LaunchCommand.OpenWorkspace(lines[1]);
|
||||
|
||||
default:
|
||||
throw new FormatException($"Unknown IPC command: '{lines[0]}'");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace YKanBan.Ipc;
|
||||
|
||||
/// <summary>Parses command-line arguments into a launch command.</summary>
|
||||
public static class LaunchArguments
|
||||
{
|
||||
/// <summary>
|
||||
/// Parses raw command-line arguments: with no meaningful argument the
|
||||
/// command is ShowMain; otherwise the first non-blank argument is taken
|
||||
/// as the workspace path and any further arguments are ignored.
|
||||
/// </summary>
|
||||
public static LaunchCommand Parse(IReadOnlyList<string> arguments)
|
||||
{
|
||||
string? path = arguments.FirstOrDefault(argument => !string.IsNullOrWhiteSpace(argument));
|
||||
return path is null
|
||||
? new LaunchCommand.ShowMain()
|
||||
: new LaunchCommand.OpenWorkspace(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace YKanBan.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// A launch command: what a YKanBan invocation asks the application to do.
|
||||
/// Doubles as the IPC message forwarded from a secondary instance to the
|
||||
/// primary one.
|
||||
/// </summary>
|
||||
public abstract record LaunchCommand
|
||||
{
|
||||
/// <summary>No arguments: show the main window and bring it to front.</summary>
|
||||
public sealed record ShowMain : LaunchCommand;
|
||||
|
||||
/// <summary>A workspace path: activate the window and switch to (or open) the workspace.</summary>
|
||||
public sealed record OpenWorkspace(string Path) : LaunchCommand;
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
using System.IO.Pipes;
|
||||
using System.Text;
|
||||
|
||||
namespace YKanBan.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// Mutex + named pipe implementation of <see cref="ISingleInstanceService"/>.
|
||||
/// The mutex name is per-user-session (Local\ prefix), so separate users on
|
||||
/// one machine run independently. A crash releases the mutex with the
|
||||
/// process — no stale state survives.
|
||||
/// </summary>
|
||||
public sealed class SingleInstanceService : ISingleInstanceService
|
||||
{
|
||||
private const string MutexName = @"Local\YKanBan.SingleInstance";
|
||||
private const string PipeName = "YKanBan.Ipc";
|
||||
private const int ConnectTimeoutMilliseconds = 2000;
|
||||
private const int ConnectAttempts = 3;
|
||||
private const int RetryDelayMilliseconds = 300;
|
||||
|
||||
private readonly object _gate = new();
|
||||
private Mutex? _mutex;
|
||||
private CancellationTokenSource? _serverCancellation;
|
||||
private bool _isPrimary;
|
||||
|
||||
/// <summary>Attempts to register this process as the single YKanBan instance.</summary>
|
||||
/// <exception cref="InvalidOperationException">Acquired a second time.</exception>
|
||||
public bool TryAcquireSingleInstance()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_mutex is not null)
|
||||
{
|
||||
throw new InvalidOperationException("Single instance already acquired.");
|
||||
}
|
||||
|
||||
// Ownership is requested up front; createdNew tells primary from secondary.
|
||||
_mutex = new Mutex(initiallyOwned: true, MutexName, out bool createdNew);
|
||||
_isPrimary = createdNew;
|
||||
return createdNew;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Starts serving launch commands on a background task (primary instance only).</summary>
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// Not called on a primary instance, or called a second time.
|
||||
/// </exception>
|
||||
public void StartServer(Action<LaunchCommand> handler)
|
||||
{
|
||||
CancellationTokenSource cancellation;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_isPrimary || _mutex is null)
|
||||
{
|
||||
throw new InvalidOperationException("Only the primary instance can serve IPC.");
|
||||
}
|
||||
if (_serverCancellation is not null)
|
||||
{
|
||||
throw new InvalidOperationException("IPC server already started.");
|
||||
}
|
||||
_serverCancellation = new CancellationTokenSource();
|
||||
cancellation = _serverCancellation;
|
||||
}
|
||||
|
||||
_ = Task.Run(() => ServerLoopAsync(handler, cancellation.Token));
|
||||
}
|
||||
|
||||
/// <summary>Delivers a command to the primary instance and waits for its acknowledgement.</summary>
|
||||
public bool TrySend(LaunchCommand command)
|
||||
{
|
||||
string payload = IpcProtocol.Encode(command);
|
||||
|
||||
// The primary may still be starting its server; retry briefly before giving up.
|
||||
for (int attempt = 0; attempt < ConnectAttempts; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var client = new NamedPipeClientStream(".", PipeName, PipeDirection.InOut);
|
||||
client.Connect(ConnectTimeoutMilliseconds);
|
||||
|
||||
using (var writer = new StreamWriter(client, Encoding.UTF8, bufferSize: 64, leaveOpen: true)
|
||||
{
|
||||
AutoFlush = true,
|
||||
})
|
||||
{
|
||||
writer.Write(payload);
|
||||
}
|
||||
|
||||
using var reader = new StreamReader(client, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 64, leaveOpen: true);
|
||||
string acknowledgement = reader.ReadLine() ?? string.Empty;
|
||||
return acknowledgement == "ok";
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
Thread.Sleep(RetryDelayMilliseconds);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
Thread.Sleep(RetryDelayMilliseconds);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Releases the mutex and stops the IPC server.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_serverCancellation?.Cancel();
|
||||
_serverCancellation?.Dispose();
|
||||
_serverCancellation = null;
|
||||
_mutex?.Dispose();
|
||||
_mutex = null;
|
||||
_isPrimary = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Accepts one client at a time: read, decode, dispatch, acknowledge, disconnect.</summary>
|
||||
private static async Task ServerLoopAsync(Action<LaunchCommand> handler, CancellationToken cancellation)
|
||||
{
|
||||
while (!cancellation.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var server = new NamedPipeServerStream(PipeName, PipeDirection.InOut, maxNumberOfServerInstances: 1);
|
||||
await server.WaitForConnectionAsync(cancellation);
|
||||
|
||||
string payload = await ReadMessageAsync(server, cancellation);
|
||||
LaunchCommand command = IpcProtocol.Decode(payload);
|
||||
|
||||
// Dispatch to the app; handler failures must not kill the server.
|
||||
try
|
||||
{
|
||||
handler(command);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// Swallow handler exceptions: one bad dispatch must not stop serving.
|
||||
}
|
||||
|
||||
WriteAcknowledgement(server);
|
||||
server.Disconnect();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Client vanished mid-conversation: drop the connection and keep serving.
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
// Malformed payload: no acknowledgement is written; keep serving.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the command line plus, for open, the path line.</summary>
|
||||
private static async Task<string> ReadMessageAsync(PipeStream pipe, CancellationToken cancellation)
|
||||
{
|
||||
using var reader = new StreamReader(pipe, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true);
|
||||
|
||||
string firstLine = await reader.ReadLineAsync(cancellation)
|
||||
?? throw new IOException("Connection closed before the command line arrived.");
|
||||
if (firstLine != "open")
|
||||
{
|
||||
return firstLine;
|
||||
}
|
||||
|
||||
string? pathLine = await reader.ReadLineAsync(cancellation);
|
||||
if (pathLine is null)
|
||||
{
|
||||
throw new IOException("Connection closed before the path line arrived.");
|
||||
}
|
||||
return $"open\n{pathLine}";
|
||||
}
|
||||
|
||||
/// <summary>Writes the acknowledgement the sender waits for.</summary>
|
||||
private static void WriteAcknowledgement(PipeStream pipe)
|
||||
{
|
||||
using var writer = new StreamWriter(pipe, Encoding.UTF8, bufferSize: 64, leaveOpen: true)
|
||||
{
|
||||
AutoFlush = true,
|
||||
};
|
||||
writer.Write("ok\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
namespace YKanBan.Models;
|
||||
|
||||
/// <summary>
|
||||
/// An RGB color without an alpha channel, stored as one byte per component
|
||||
/// — mirroring the color structures of WinForms, WPF and Avalonia minus
|
||||
/// the alpha byte. The type is total: every combination of components is
|
||||
/// valid, and all validation happens at the text boundary. Converts to and
|
||||
/// from the persisted "#RRGGBB" text form; ToString always produces the
|
||||
/// canonical lowercase form (e.g. "#ff0a00").
|
||||
/// </summary>
|
||||
public readonly record struct RgbColor(byte R, byte G, byte B)
|
||||
{
|
||||
/// <summary>Parses a "#RRGGBB" text with case-insensitive hex digits.</summary>
|
||||
/// <exception cref="FormatException">The text is not in #RRGGBB form.</exception>
|
||||
public static RgbColor Parse(string text) =>
|
||||
TryParse(text, out RgbColor color)
|
||||
? color
|
||||
: throw new FormatException($"Not a valid #RRGGBB color: '{text}'.");
|
||||
|
||||
/// <summary>Attempts to parse a "#RRGGBB" text; no whitespace tolerance.</summary>
|
||||
public static bool TryParse(string? text, out RgbColor color)
|
||||
{
|
||||
color = default;
|
||||
if (text is not { Length: 7 } || text[0] != '#')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Two hex digits per component: R, G, B.
|
||||
if (TryHexPair(text, 1, out byte r) && TryHexPair(text, 3, out byte g) && TryHexPair(text, 5, out byte b))
|
||||
{
|
||||
color = new RgbColor(r, g, b);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Returns the canonical lowercase "#RRGGBB" form used by the database and exports.</summary>
|
||||
public override string ToString() => $"#{R:x2}{G:x2}{B:x2}";
|
||||
|
||||
/// <summary>Parses exactly two hex digits into a byte value.</summary>
|
||||
private static bool TryHexPair(string text, int start, out byte value)
|
||||
{
|
||||
value = 0;
|
||||
int high = HexDigit(text[start]);
|
||||
int low = HexDigit(text[start + 1]);
|
||||
if (high < 0 || low < 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
value = (byte)((high << 4) | low);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Converts one hex digit to its value; -1 for any other character.</summary>
|
||||
private static int HexDigit(char character) => character switch
|
||||
{
|
||||
>= '0' and <= '9' => character - '0',
|
||||
>= 'a' and <= 'f' => character - 'a' + 10,
|
||||
>= 'A' and <= 'F' => character - 'A' + 10,
|
||||
_ => -1,
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,6 @@ namespace YKanBan.Models;
|
||||
/// <summary>A tag assignable to cards. Tags are never garbage-collected: unreferenced tags stay until deleted explicitly.</summary>
|
||||
/// <param name="Id">Row id.</param>
|
||||
/// <param name="Name">Arbitrary non-empty text; no charset or length rules.</param>
|
||||
/// <param name="Color">Fixed #RRGGBB form.</param>
|
||||
/// <param name="Color">The tag color; persisted as #RRGGBB text.</param>
|
||||
/// <param name="Description">Free-form description, possibly empty.</param>
|
||||
public sealed record TagModel(long Id, string Name, string Color, string Description);
|
||||
public sealed record TagModel(long Id, string Name, RgbColor Color, string Description);
|
||||
+23
-2
@@ -1,13 +1,34 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using YKanBan.Ipc;
|
||||
|
||||
namespace YKanBan;
|
||||
|
||||
sealed class Program
|
||||
{
|
||||
/// <summary>The single-instance service held by this process while the app runs.</summary>
|
||||
internal static ISingleInstanceService? SingleInstance { get; private set; }
|
||||
|
||||
[STAThread]
|
||||
public static void Main(string[] args) => BuildAvaloniaApp()
|
||||
.StartWithClassicDesktopLifetime(args);
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
LaunchCommand command = LaunchArguments.Parse(args);
|
||||
using ISingleInstanceService singleInstance = new SingleInstanceService();
|
||||
|
||||
// Secondary instance: forward the command to the primary, then exit immediately.
|
||||
if (!singleInstance.TryAcquireSingleInstance())
|
||||
{
|
||||
singleInstance.TrySend(command);
|
||||
return;
|
||||
}
|
||||
|
||||
SingleInstance = singleInstance;
|
||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
|
||||
// Lifetime ended: persist the configuration once, then release the services.
|
||||
App.Services.SaveConfiguration();
|
||||
App.Services.Dispose();
|
||||
}
|
||||
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
=> AppBuilder.Configure<App>()
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
using Pidgin;
|
||||
|
||||
namespace YKanBan.Search;
|
||||
|
||||
/// <summary>Lexical tokens of the search syntax.</summary>
|
||||
public abstract record SearchToken
|
||||
{
|
||||
/// <summary>A bare word; qualifier detection happens later from the text.</summary>
|
||||
public sealed record Word(string Text) : SearchToken;
|
||||
|
||||
/// <summary>A quoted phrase with escapes already resolved.</summary>
|
||||
public sealed record Phrase(string Text) : SearchToken;
|
||||
|
||||
/// <summary>An opening parenthesis.</summary>
|
||||
public sealed record OpenParen : SearchToken;
|
||||
|
||||
/// <summary>A closing parenthesis.</summary>
|
||||
public sealed record CloseParen : SearchToken;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pidgin-based lexer for the search syntax. Splits the input into words,
|
||||
/// quoted phrases (with \" and \\ escapes) and parentheses; whitespace only
|
||||
/// separates tokens. The lexer is total: it never rejects input — anything
|
||||
/// the dedicated rules do not cover falls through to the word rule, and an
|
||||
/// unterminated phrase simply extends to the end of the input.
|
||||
/// </summary>
|
||||
public static class SearchLexer
|
||||
{
|
||||
private static readonly Parser<char, char> PhraseCharacter =
|
||||
Parser.Try(Parser.String("\\\"").Select(_ => '"'))
|
||||
.Or(Parser.Try(Parser.String("\\\\").Select(_ => '\\')))
|
||||
.Or(Parser.AnyCharExcept('"'));
|
||||
|
||||
private static readonly Parser<char, SearchToken> PhraseParser =
|
||||
from openingQuote in Parser.Char('"')
|
||||
from content in PhraseCharacter.Many()
|
||||
from closingQuote in Parser.Char('"')
|
||||
select (SearchToken)new SearchToken.Phrase(new string(content.ToArray()));
|
||||
|
||||
private static readonly Parser<char, SearchToken> OpenParenParser =
|
||||
Parser.Char('(').Select(_ => (SearchToken)new SearchToken.OpenParen());
|
||||
|
||||
private static readonly Parser<char, SearchToken> CloseParenParser =
|
||||
Parser.Char(')').Select(_ => (SearchToken)new SearchToken.CloseParen());
|
||||
|
||||
private static readonly Parser<char, SearchToken> WordParser =
|
||||
Parser<char>.Token(c => !char.IsWhiteSpace(c) && c != '(' && c != ')' && c != '"')
|
||||
.AtLeastOnce()
|
||||
.Select(chars => (SearchToken)new SearchToken.Word(new string(chars.ToArray())));
|
||||
|
||||
private static readonly Parser<char, SearchToken> AnyCharacterAsWord =
|
||||
Parser<char>.Any.Select(c => (SearchToken)new SearchToken.Word(c.ToString()));
|
||||
|
||||
private static readonly Parser<char, SearchToken> TokenParser =
|
||||
Parser.SkipWhitespaces.Then(
|
||||
PhraseParser
|
||||
.Or(OpenParenParser)
|
||||
.Or(CloseParenParser)
|
||||
.Or(WordParser)
|
||||
.Or(AnyCharacterAsWord));
|
||||
|
||||
private static readonly Parser<char, IReadOnlyList<SearchToken>> Lexer =
|
||||
// Try(...) keeps a trailing-whitespace failure non-consuming so Many stops
|
||||
// gracefully; the trailing Before(...) then swallows the leftover whitespace.
|
||||
Parser.Try(TokenParser).Many()
|
||||
.Before(Parser.SkipWhitespaces)
|
||||
.Select(tokens => (IReadOnlyList<SearchToken>)tokens.ToList());
|
||||
|
||||
/// <summary>Tokenizes the search text; total over any input.</summary>
|
||||
public static IReadOnlyList<SearchToken> Tokenize(string input) =>
|
||||
Lexer.ParseOrThrow(input);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// YYC MARK: C# records synthesize equality by running EqualityComparer<T>.Default
|
||||
// on each positional property. For collection properties (IReadOnlyList<>,
|
||||
// ImmutableArray<>, arrays, ...) that comparer falls back to REFERENCE equality,
|
||||
// so the And/Or nodes below deliberately do NOT compare structurally. The only
|
||||
// structural comparison lives in the test helper (SearchNodeComparer); production
|
||||
// code never compares AST nodes.
|
||||
namespace YKanBan.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Root of the search query AST. Search keywords are fixed English grammar
|
||||
/// and are never localized.
|
||||
/// </summary>
|
||||
public abstract record SearchNode
|
||||
{
|
||||
/// <summary>Disjunction: matches when any term matches (OR).</summary>
|
||||
public sealed record Or(IReadOnlyList<SearchNode> Terms) : SearchNode;
|
||||
|
||||
/// <summary>Conjunction: matches when all terms match (explicit AND or adjacency).</summary>
|
||||
public sealed record And(IReadOnlyList<SearchNode> Terms) : SearchNode;
|
||||
|
||||
/// <summary>A bare word or phrase matched as a substring of the title OR content.</summary>
|
||||
public sealed record FreeText(string Text) : SearchNode;
|
||||
|
||||
/// <summary>A substring match scoped to one card field.</summary>
|
||||
public sealed record FieldText(SearchField Field, string Text) : SearchNode;
|
||||
|
||||
/// <summary>An exact, case-insensitive tag name match.</summary>
|
||||
public sealed record TagName(string Name) : SearchNode;
|
||||
|
||||
/// <summary>An exact, case-insensitive column title match.</summary>
|
||||
public sealed record ColumnTitle(string Title) : SearchNode;
|
||||
|
||||
/// <summary>An exact card id match.</summary>
|
||||
public sealed record CardId(long Id) : SearchNode;
|
||||
}
|
||||
|
||||
/// <summary>The card fields a <see cref="SearchNode.FieldText"/> atom can scope to.</summary>
|
||||
public enum SearchField
|
||||
{
|
||||
/// <summary>The card title.</summary>
|
||||
Title,
|
||||
|
||||
/// <summary>The card content body.</summary>
|
||||
Content,
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
using System.Globalization;
|
||||
using Pidgin;
|
||||
|
||||
namespace YKanBan.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Thrown when the search text violates the search grammar. Carries the
|
||||
/// underlying parser's descriptive message (including the error position);
|
||||
/// the UI surfaces it as a search error instead of coupling to Pidgin types.
|
||||
/// </summary>
|
||||
public sealed class SearchSyntaxException : Exception
|
||||
{
|
||||
/// <summary>Creates an exception wrapping the original parse failure.</summary>
|
||||
public SearchSyntaxException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the search grammar with Pidgin, strictly: any malformed input
|
||||
/// (unbalanced parentheses, dangling operators, unterminated phrases,
|
||||
/// qualifier keys without a value, non-numeric id values) raises
|
||||
/// <see cref="SearchSyntaxException"/>. Only uppercase AND/OR are operators
|
||||
/// (lowercase ones are plain words); AND — explicit or by adjacency — binds
|
||||
/// tighter than OR; parentheses group. Blank input returns null and means
|
||||
/// "show everything".
|
||||
/// </summary>
|
||||
public static class SearchQueryParser
|
||||
{
|
||||
/// <summary>Recognized qualifier kinds; extend <see cref="Qualifiers"/> to add new keys.</summary>
|
||||
private enum QualifierKind
|
||||
{
|
||||
Tag,
|
||||
Title,
|
||||
Content,
|
||||
Id,
|
||||
Column,
|
||||
}
|
||||
|
||||
/// <summary>The qualifier key table ("key:" prefixes); reserved for future keys like created:.</summary>
|
||||
private static readonly (string Key, QualifierKind Kind)[] Qualifiers =
|
||||
[
|
||||
("tag", QualifierKind.Tag),
|
||||
("title", QualifierKind.Title),
|
||||
("content", QualifierKind.Content),
|
||||
("id", QualifierKind.Id),
|
||||
("column", QualifierKind.Column),
|
||||
];
|
||||
|
||||
#region Token primitives
|
||||
|
||||
private static readonly Parser<SearchToken, SearchToken> AndKeyword =
|
||||
Parser<SearchToken>.Token(new SearchToken.Word("AND"));
|
||||
|
||||
private static readonly Parser<SearchToken, SearchToken> OrKeyword =
|
||||
Parser<SearchToken>.Token(new SearchToken.Word("OR"));
|
||||
|
||||
private static readonly Parser<SearchToken, SearchToken> OpenParen =
|
||||
Parser<SearchToken>.Token((SearchToken)new SearchToken.OpenParen());
|
||||
|
||||
private static readonly Parser<SearchToken, SearchToken> CloseParen =
|
||||
Parser<SearchToken>.Token((SearchToken)new SearchToken.CloseParen());
|
||||
|
||||
/// <summary>The text of a phrase token.</summary>
|
||||
private static readonly Parser<SearchToken, string> PhraseText =
|
||||
Parser<SearchToken>.Token(t => t is SearchToken.Phrase)
|
||||
.Select(t => ((SearchToken.Phrase)t).Text);
|
||||
|
||||
/// <summary>The text of a word token, operator keywords excluded (they never start an operand).</summary>
|
||||
private static readonly Parser<SearchToken, string> NonKeywordWord =
|
||||
Parser<SearchToken>.Token(t => t is SearchToken.Word w && w.Text != "AND" && w.Text != "OR")
|
||||
.Select(t => ((SearchToken.Word)t).Text);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Grammar
|
||||
|
||||
// A bare phrase matched against title or content.
|
||||
private static readonly Parser<SearchToken, SearchNode> FreePhrase =
|
||||
PhraseText.Select(text => (SearchNode)new SearchNode.FreeText(text));
|
||||
|
||||
// A bare word: a "key:value" qualifier when the prefix matches, otherwise free text.
|
||||
private static readonly Parser<SearchToken, SearchNode> WordAtom =
|
||||
NonKeywordWord.Bind(QualifierFrom);
|
||||
|
||||
// '(' orExpr ')' — the deferred method call breaks the
|
||||
// Parenthesized → OrExpr → AndExpr → Operand → Parenthesized recursion cycle.
|
||||
private static readonly Parser<SearchToken, SearchNode> Parenthesized =
|
||||
OpenParen.Then(_ => OrExprDeferred()).Before(CloseParen);
|
||||
|
||||
// operand := '(' orExpr ')' | qualifier-or-word | phrase
|
||||
private static readonly Parser<SearchToken, SearchNode> Operand =
|
||||
Parenthesized.Or(WordAtom).Or(FreePhrase);
|
||||
|
||||
// One andExpr operand together with its optional explicit AND keyword.
|
||||
private static readonly Parser<SearchToken, SearchNode> AndPrefixedOperand =
|
||||
AndKeyword.Optional().Then(Operand);
|
||||
|
||||
// andExpr := operand (AND? operand)*
|
||||
private static readonly Parser<SearchToken, SearchNode> AndExpr =
|
||||
Operand.Bind(first =>
|
||||
AndPrefixedOperand.Many()
|
||||
.Select(rest => FoldAnd(first, rest)));
|
||||
|
||||
// orExpr := andExpr (OR andExpr)+
|
||||
private static readonly Parser<SearchToken, SearchNode> OrExpr =
|
||||
AndExpr.SeparatedAtLeastOnce(OrKeyword)
|
||||
.Select(FoldOr);
|
||||
|
||||
// The full query: orExpr consuming the whole token stream.
|
||||
private static readonly Parser<SearchToken, SearchNode> Query =
|
||||
OrExpr.Before(Parser<SearchToken>.End);
|
||||
|
||||
/// <summary>Defers the OrExpr field read to parse time (recursion cycle breaker).</summary>
|
||||
private static Parser<SearchToken, SearchNode> OrExprDeferred() => OrExpr;
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>Parses a search box text; returns null for blank input (meaning: show everything).</summary>
|
||||
/// <exception cref="SearchSyntaxException">The text violates the grammar.</exception>
|
||||
public static SearchNode? Parse(string text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
List<SearchToken> tokens = SearchLexer.Tokenize(text).ToList();
|
||||
return Query.ParseOrThrow(tokens);
|
||||
}
|
||||
catch (ParseException ex)
|
||||
{
|
||||
throw new SearchSyntaxException(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Builds the parser for one word operand: qualifier atom or free text.</summary>
|
||||
private static Parser<SearchToken, SearchNode> QualifierFrom(string word)
|
||||
{
|
||||
foreach ((string key, QualifierKind kind) in Qualifiers)
|
||||
{
|
||||
// Qualifier keys are case-sensitive lowercase grammar tokens.
|
||||
if (!word.StartsWith(key + ":", StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
string value = word[(key.Length + 1)..];
|
||||
|
||||
// "key:" without an inline value takes the value from the following phrase, e.g. tag:"a b".
|
||||
return value.Length == 0
|
||||
? PhraseText.Bind(text => AtomParser(kind, text))
|
||||
: AtomParser(kind, value);
|
||||
}
|
||||
|
||||
// No qualifier prefix: a plain free-text word.
|
||||
return Parser<SearchToken>.Return<SearchNode>(new SearchNode.FreeText(word));
|
||||
}
|
||||
|
||||
/// <summary>Builds the atom parser for a qualifier value, failing strictly on a non-numeric id.</summary>
|
||||
private static Parser<SearchToken, SearchNode> AtomParser(QualifierKind kind, string value)
|
||||
{
|
||||
return AtomFrom(kind, value) is { } atom
|
||||
? Parser<SearchToken>.Return(atom)
|
||||
: Parser<SearchToken>.Fail<SearchNode>($"id: expects an integer, got '{value}'.");
|
||||
}
|
||||
|
||||
/// <summary>Builds the atom for a qualifier value; null when an id value is not an integer.</summary>
|
||||
private static SearchNode? AtomFrom(QualifierKind kind, string value) => kind switch
|
||||
{
|
||||
QualifierKind.Tag => new SearchNode.TagName(value),
|
||||
QualifierKind.Title => new SearchNode.FieldText(SearchField.Title, value),
|
||||
QualifierKind.Content => new SearchNode.FieldText(SearchField.Content, value),
|
||||
QualifierKind.Column => new SearchNode.ColumnTitle(value),
|
||||
QualifierKind.Id when long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out long id) => new SearchNode.CardId(id),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>Collapses an AND chain into a single node.</summary>
|
||||
private static SearchNode FoldAnd(SearchNode first, IEnumerable<SearchNode> rest)
|
||||
{
|
||||
List<SearchNode> terms = [first, .. rest];
|
||||
return terms.Count == 1 ? terms[0] : new SearchNode.And(terms);
|
||||
}
|
||||
|
||||
/// <summary>Collapses an OR chain into a single node.</summary>
|
||||
private static SearchNode FoldOr(IEnumerable<SearchNode> terms)
|
||||
{
|
||||
List<SearchNode> list = terms.ToList();
|
||||
return list.Count == 1 ? list[0] : new SearchNode.Or(list);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
namespace YKanBan.Search;
|
||||
|
||||
/// <summary>A compiled search predicate: a SQL fragment over the "c" (cards) alias plus its bound parameters.</summary>
|
||||
/// <param name="Predicate">SQL boolean expression; intended for "SELECT ... FROM cards c WHERE {Predicate}".</param>
|
||||
/// <param name="Parameters">Named parameters referenced by the predicate, in order.</param>
|
||||
public sealed record CompiledSearch(string Predicate, IReadOnlyList<(string Name, object Value)> Parameters);
|
||||
|
||||
/// <summary>
|
||||
/// Compiles a parsed search AST into a parameterized SQL predicate.
|
||||
/// Matching is case-insensitive with SQLite's built-in ASCII semantics:
|
||||
/// LIKE's default case folding plus COLLATE NOCASE for exact matches.
|
||||
/// LIKE wildcards and the escape character in user text are escaped so they
|
||||
/// match literally.
|
||||
/// </summary>
|
||||
public static class SearchSqlCompiler
|
||||
{
|
||||
/// <summary>Compiles the query into a SQL predicate.</summary>
|
||||
public static CompiledSearch Compile(SearchNode query)
|
||||
{
|
||||
var parameters = new List<(string Name, object Value)>();
|
||||
string predicate = Build(query, parameters);
|
||||
return new CompiledSearch(predicate, parameters);
|
||||
}
|
||||
|
||||
/// <summary>Recursively builds the SQL expression for one node.</summary>
|
||||
private static string Build(SearchNode node, List<(string Name, object Value)> parameters)
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case SearchNode.And and:
|
||||
return "(" + string.Join(" AND ", and.Terms.Select(term => Build(term, parameters))) + ")";
|
||||
|
||||
case SearchNode.Or or:
|
||||
return "(" + string.Join(" OR ", or.Terms.Select(term => Build(term, parameters))) + ")";
|
||||
|
||||
case SearchNode.FreeText freeText:
|
||||
{
|
||||
// A bare word matches a substring of the title OR the content.
|
||||
string titleParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
|
||||
string contentParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
|
||||
return $"(c.title LIKE {titleParam} ESCAPE '\\' OR c.content LIKE {contentParam} ESCAPE '\\')";
|
||||
}
|
||||
|
||||
case SearchNode.FieldText field:
|
||||
{
|
||||
string column = field.Field == SearchField.Title ? "c.title" : "c.content";
|
||||
string param = AddParameter(parameters, "%" + EscapeLike(field.Text) + "%");
|
||||
return $"{column} LIKE {param} ESCAPE '\\'";
|
||||
}
|
||||
|
||||
case SearchNode.TagName tag:
|
||||
{
|
||||
string param = AddParameter(parameters, tag.Name);
|
||||
return "EXISTS (SELECT 1 FROM card_tags ct JOIN tags t ON t.id = ct.tag_id " +
|
||||
$"WHERE ct.card_id = c.id AND t.name COLLATE NOCASE = {param})";
|
||||
}
|
||||
|
||||
case SearchNode.ColumnTitle column:
|
||||
{
|
||||
string param = AddParameter(parameters, column.Title);
|
||||
return $"c.column_id IN (SELECT id FROM columns WHERE title COLLATE NOCASE = {param})";
|
||||
}
|
||||
|
||||
case SearchNode.CardId id:
|
||||
{
|
||||
string param = AddParameter(parameters, id.Id);
|
||||
return $"c.id = {param}";
|
||||
}
|
||||
|
||||
default:
|
||||
throw new InvalidOperationException($"Unsupported search node: {node.GetType().Name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Binds a value under a fresh name and returns the SQL placeholder.</summary>
|
||||
private static string AddParameter(List<(string Name, object Value)> parameters, object value)
|
||||
{
|
||||
string name = "$p" + parameters.Count.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
parameters.Add((name, value));
|
||||
return name;
|
||||
}
|
||||
|
||||
/// <summary>Escapes LIKE wildcards and the escape character inside user text.</summary>
|
||||
private static string EscapeLike(string text) =>
|
||||
text.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_");
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using YKanBan.Platform;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
namespace YKanBan.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Composition root: owns the application-wide configuration, the global
|
||||
/// workspace registry and the workspace connection pool for the whole
|
||||
/// process lifetime. The configuration is persisted once at shutdown.
|
||||
/// </summary>
|
||||
public sealed class AppServices : IDisposable
|
||||
{
|
||||
/// <summary>Maximum number of simultaneously open workspaces.</summary>
|
||||
private const int PoolCapacity = 8;
|
||||
|
||||
/// <summary>Loads the configuration and opens the global services.</summary>
|
||||
public AppServices()
|
||||
{
|
||||
ConfigStore = new AppConfigStore(AppDataPaths.AppConfigJsonPath);
|
||||
Config = ConfigStore.Load();
|
||||
Database = new AppDatabase(AppDataPaths.AppDatabasePath);
|
||||
PathComparison = PathComparer.ForCurrentPlatform();
|
||||
Pool = new WorkspaceConnectionPool(PoolCapacity, Database, PathComparison);
|
||||
}
|
||||
|
||||
/// <summary>The mutable application configuration; persisted by <see cref="SaveConfiguration"/>.</summary>
|
||||
public AppConfig Config { get; }
|
||||
|
||||
/// <summary>Store for app.json.</summary>
|
||||
public AppConfigStore ConfigStore { get; }
|
||||
|
||||
/// <summary>Global workspace registry (app.db).</summary>
|
||||
public AppDatabase Database { get; }
|
||||
|
||||
/// <summary>LRU pool of open workspace sessions.</summary>
|
||||
public WorkspaceConnectionPool Pool { get; }
|
||||
|
||||
/// <summary>Platform path comparison rules.</summary>
|
||||
public PathComparer PathComparison { get; }
|
||||
|
||||
/// <summary>Persists the configuration; called once at shutdown.</summary>
|
||||
public void SaveConfiguration() => ConfigStore.Save(Config);
|
||||
|
||||
/// <summary>Releases the pool and the registry.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Pool.Dispose();
|
||||
Database.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -130,13 +130,16 @@ public sealed class AppConfig
|
||||
/// <summary>Current configuration format version.</summary>
|
||||
public const int CurrentFormatVersion = 1;
|
||||
|
||||
/// <summary>The default UI language code.</summary>
|
||||
public const string DefaultLanguage = "en";
|
||||
|
||||
/// <summary>Configuration format version of this file.</summary>
|
||||
[JsonProperty("version")]
|
||||
public int Version { get; set; } = CurrentFormatVersion;
|
||||
|
||||
/// <summary>UI language code: "en" (default) or "zh-Hans".</summary>
|
||||
[JsonProperty("language")]
|
||||
public string Language { get; set; } = "en";
|
||||
public string Language { get; set; } = DefaultLanguage;
|
||||
|
||||
/// <summary>UI theme selection (default: follow the system).</summary>
|
||||
[JsonProperty("theme")]
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace YKanBan.Storage.AppData;
|
||||
|
||||
/// <summary>Well-known locations under the per-user application data folder.</summary>
|
||||
public static class AppDataPaths
|
||||
{
|
||||
/// <summary>The per-user YKanBan application data folder.</summary>
|
||||
public static string Directory =>
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "YKanBan");
|
||||
|
||||
/// <summary>Full path of app.json.</summary>
|
||||
public static string AppConfigJsonPath => Path.Combine(Directory, "app.json");
|
||||
|
||||
/// <summary>Full path of app.db.</summary>
|
||||
public static string AppDatabasePath => Path.Combine(Directory, "app.db");
|
||||
}
|
||||
@@ -145,7 +145,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
}
|
||||
if (!reader.IsDBNull(6))
|
||||
{
|
||||
tags.Add(new TagModel(reader.GetInt64(6), reader.GetString(7), reader.GetString(8), reader.GetString(9)));
|
||||
tags.Add(new TagModel(reader.GetInt64(6), reader.GetString(7), RgbColor.Parse(reader.GetString(8)), reader.GetString(9)));
|
||||
}
|
||||
}
|
||||
return cards;
|
||||
@@ -183,7 +183,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
}
|
||||
if (!reader.IsDBNull(6))
|
||||
{
|
||||
tags.Add(new TagModel(reader.GetInt64(6), reader.GetString(7), reader.GetString(8), reader.GetString(9)));
|
||||
tags.Add(new TagModel(reader.GetInt64(6), reader.GetString(7), RgbColor.Parse(reader.GetString(8)), reader.GetString(9)));
|
||||
}
|
||||
}
|
||||
return card;
|
||||
@@ -313,13 +313,13 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
}
|
||||
|
||||
/// <summary>Creates a tag.</summary>
|
||||
/// <exception cref="SqliteException">The name is empty/not unique, or the color is not #RRGGBB.</exception>
|
||||
public TagModel AddTag(string name, string color, string description)
|
||||
/// <exception cref="SqliteException">The name is empty/not unique.</exception>
|
||||
public TagModel AddTag(string name, RgbColor color, string description)
|
||||
{
|
||||
using var transaction = _connection.BeginTransaction();
|
||||
long id = ExecuteInsert(transaction,
|
||||
"INSERT INTO tags (name, color, description) VALUES ($name, $color, $description);",
|
||||
("$name", name), ("$color", color), ("$description", description));
|
||||
("$name", name), ("$color", color.ToString()), ("$description", description));
|
||||
transaction.Commit();
|
||||
|
||||
TouchEdited();
|
||||
@@ -328,8 +328,8 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
|
||||
/// <summary>Rewrites name, color and description; a no-change call writes nothing.</summary>
|
||||
/// <exception cref="InvalidOperationException">The tag does not exist.</exception>
|
||||
/// <exception cref="SqliteException">The new name is empty/not unique, or the color is not #RRGGBB.</exception>
|
||||
public TagModel UpdateTag(long tagId, string name, string color, string description)
|
||||
/// <exception cref="SqliteException">The new name is empty/not unique.</exception>
|
||||
public TagModel UpdateTag(long tagId, string name, RgbColor color, string description)
|
||||
{
|
||||
TagModel existing = GetTag(tagId)
|
||||
?? throw new InvalidOperationException($"Tag {tagId} does not exist.");
|
||||
@@ -343,7 +343,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
using var command = CreateCommand(
|
||||
"UPDATE tags SET name = $name, color = $color, description = $description WHERE id = $id;");
|
||||
command.Parameters.AddWithValue("$name", name);
|
||||
command.Parameters.AddWithValue("$color", color);
|
||||
command.Parameters.AddWithValue("$color", color.ToString());
|
||||
command.Parameters.AddWithValue("$description", description);
|
||||
command.Parameters.AddWithValue("$id", tagId);
|
||||
command.ExecuteNonQuery();
|
||||
@@ -394,9 +394,9 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
private static ColumnModel ReadColumn(SqliteDataReader reader) =>
|
||||
new(reader.GetInt64(0), reader.GetString(1), reader.GetString(2), reader.GetInt64(3), reader.GetInt64(4));
|
||||
|
||||
/// <summary>Reads a tags row from the reader cursor.</summary>
|
||||
/// <summary>Reads a tags row from the reader cursor; color text converts to components.</summary>
|
||||
private static TagModel ReadTag(SqliteDataReader reader) =>
|
||||
new(reader.GetInt64(0), reader.GetString(1), reader.GetString(2), reader.GetString(3));
|
||||
new(reader.GetInt64(0), reader.GetString(1), RgbColor.Parse(reader.GetString(2)), reader.GetString(3));
|
||||
|
||||
/// <summary>Creates a command bound to this connection.</summary>
|
||||
private SqliteCommand CreateCommand(string sql, SqliteTransaction? transaction = null)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
using System.Reflection;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>The about dialog data: application identity and version.</summary>
|
||||
public sealed class AboutDialogViewModel : ViewModelBase
|
||||
{
|
||||
/// <summary>Display name of the application.</summary>
|
||||
public string ApplicationName => Resources.App_Name;
|
||||
|
||||
/// <summary>Localized "Version x.y.z" text.</summary>
|
||||
public string VersionText => string.Format(
|
||||
System.Globalization.CultureInfo.CurrentCulture,
|
||||
Resources.About_Version,
|
||||
AssemblyVersion);
|
||||
|
||||
/// <summary>Repository URL (from resources).</summary>
|
||||
public string RepositoryUrl => Resources.About_RepositoryUrl;
|
||||
|
||||
/// <summary>License name (from resources).</summary>
|
||||
public string LicenseValue => Resources.About_LicenseValue;
|
||||
|
||||
/// <summary>The assembly version, formatted as major.minor.patch.</summary>
|
||||
public static string AssemblyVersion =>
|
||||
Assembly.GetExecutingAssembly().GetName().Version?.ToString(3) ?? "0.0.0";
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>A generic confirmation dialog: localized title, message and yes/no answers.</summary>
|
||||
public sealed class ConfirmDialogViewModel : ViewModelBase
|
||||
{
|
||||
public ConfirmDialogViewModel(string title, string message)
|
||||
{
|
||||
Title = title;
|
||||
Message = message;
|
||||
ConfirmText = Resources.Common_Yes;
|
||||
CancelText = Resources.Common_No;
|
||||
}
|
||||
|
||||
/// <summary>Localized dialog heading.</summary>
|
||||
public string Title { get; }
|
||||
|
||||
/// <summary>Localized message body.</summary>
|
||||
public string Message { get; }
|
||||
|
||||
/// <summary>Label of the confirming button.</summary>
|
||||
public string ConfirmText { get; }
|
||||
|
||||
/// <summary>Label of the cancelling button.</summary>
|
||||
public string CancelText { get; }
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage.AppData;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The settings dialog: language (restart to apply), theme (applies
|
||||
/// immediately) and the four confirmation-dialog toggles. All changes write
|
||||
/// straight into the configuration, which persists at shutdown.
|
||||
/// </summary>
|
||||
public partial class SettingsDialogViewModel : ViewModelBase
|
||||
{
|
||||
private readonly AppConfig _config;
|
||||
private readonly string _startupLanguage;
|
||||
|
||||
public SettingsDialogViewModel(AppServices services)
|
||||
{
|
||||
_config = services.Config;
|
||||
_startupLanguage = App.StartupLanguage;
|
||||
|
||||
Languages =
|
||||
[
|
||||
new OptionItem(AppConfig.DefaultLanguage, Resources.Settings_LanguageEnglish),
|
||||
new OptionItem("zh-Hans", Resources.Settings_LanguageChinese),
|
||||
];
|
||||
selectedLanguage = Languages.FirstOrDefault(option => (string)option.Value == _config.Language)
|
||||
?? Languages[0];
|
||||
|
||||
Themes =
|
||||
[
|
||||
new OptionItem(ThemeOption.Light, Resources.Settings_ThemeLight),
|
||||
new OptionItem(ThemeOption.Dark, Resources.Settings_ThemeDark),
|
||||
new OptionItem(ThemeOption.FollowSystem, Resources.Settings_ThemeFollowSystem),
|
||||
];
|
||||
selectedTheme = Themes.FirstOrDefault(option => option.Value.Equals(_config.Theme)) ?? Themes[^1];
|
||||
|
||||
confirmDeleteCard = _config.Confirmations.DeleteCard;
|
||||
confirmDeleteColumn = _config.Confirmations.DeleteColumn;
|
||||
confirmDeleteTag = _config.Confirmations.DeleteTag;
|
||||
confirmDiscardEdit = _config.Confirmations.DiscardEdit;
|
||||
}
|
||||
|
||||
/// <summary>Available languages.</summary>
|
||||
public IReadOnlyList<OptionItem> Languages { get; }
|
||||
|
||||
/// <summary>Available themes.</summary>
|
||||
public IReadOnlyList<OptionItem> Themes { get; }
|
||||
|
||||
/// <summary>The selected language; takes effect after a restart.</summary>
|
||||
[ObservableProperty]
|
||||
private OptionItem? selectedLanguage;
|
||||
|
||||
/// <summary>The selected theme; applies immediately.</summary>
|
||||
[ObservableProperty]
|
||||
private OptionItem? selectedTheme;
|
||||
|
||||
/// <summary>Whether deleting a card asks for confirmation.</summary>
|
||||
[ObservableProperty]
|
||||
private bool confirmDeleteCard;
|
||||
|
||||
/// <summary>Whether deleting a column asks for confirmation.</summary>
|
||||
[ObservableProperty]
|
||||
private bool confirmDeleteColumn;
|
||||
|
||||
/// <summary>Whether deleting a tag asks for confirmation.</summary>
|
||||
[ObservableProperty]
|
||||
private bool confirmDeleteTag;
|
||||
|
||||
/// <summary>Whether discarding card edits asks for confirmation.</summary>
|
||||
[ObservableProperty]
|
||||
private bool confirmDiscardEdit;
|
||||
|
||||
/// <summary>True while the selected language differs from the one applied at startup.</summary>
|
||||
[ObservableProperty]
|
||||
private bool restartNoticeVisible;
|
||||
|
||||
/// <summary>Stores the language and refreshes the restart notice.</summary>
|
||||
partial void OnSelectedLanguageChanged(OptionItem? value)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_config.Language = (string)value.Value;
|
||||
RestartNoticeVisible = _config.Language != _startupLanguage;
|
||||
}
|
||||
|
||||
/// <summary>Stores the theme and applies it immediately.</summary>
|
||||
partial void OnSelectedThemeChanged(OptionItem? value)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_config.Theme = (ThemeOption)value.Value;
|
||||
App.ApplyTheme(_config.Theme);
|
||||
}
|
||||
|
||||
partial void OnConfirmDeleteCardChanged(bool value) => _config.Confirmations.DeleteCard = value;
|
||||
|
||||
partial void OnConfirmDeleteColumnChanged(bool value) => _config.Confirmations.DeleteColumn = value;
|
||||
|
||||
partial void OnConfirmDeleteTagChanged(bool value) => _config.Confirmations.DeleteTag = value;
|
||||
|
||||
partial void OnConfirmDiscardEditChanged(bool value) => _config.Confirmations.DiscardEdit = value;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace YKanBan.ViewModels;
|
||||
|
||||
/// <summary>Input placeholder for interactions that carry no meaningful input.</summary>
|
||||
public readonly record struct Unit;
|
||||
|
||||
/// <summary>
|
||||
/// A view-model side request that the owning view fulfils through a
|
||||
/// registered handler (dialogs, pickers) — the classic MVVM interaction
|
||||
/// pattern, implemented locally without extra dependencies.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The request payload.</typeparam>
|
||||
/// <typeparam name="TOutput">The handler's answer.</typeparam>
|
||||
public sealed class Interaction<TInput, TOutput>
|
||||
{
|
||||
private Func<TInput, Task<TOutput>>? _handler;
|
||||
|
||||
/// <summary>Registers the single handler; the view calls this once.</summary>
|
||||
public void RegisterHandler(Func<TInput, Task<TOutput>> handler) => _handler = handler;
|
||||
|
||||
/// <summary>Invokes the registered handler.</summary>
|
||||
/// <exception cref="InvalidOperationException">No handler has been registered.</exception>
|
||||
public Task<TOutput> Handle(TInput input) =>
|
||||
_handler is null
|
||||
? throw new InvalidOperationException("No handler registered for this interaction.")
|
||||
: _handler(input);
|
||||
}
|
||||
@@ -1,5 +1,103 @@
|
||||
namespace YKanBan.ViewModels;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.ViewModels.Pages;
|
||||
|
||||
namespace YKanBan.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Root view model: owns the sidebar and the current content page (welcome,
|
||||
/// an open workspace, or a failure state page).
|
||||
/// </summary>
|
||||
public partial class MainWindowViewModel : ViewModelBase
|
||||
{
|
||||
public MainWindowViewModel(AppServices services)
|
||||
{
|
||||
Services = services;
|
||||
Sidebar = new SidebarViewModel(this, services);
|
||||
CurrentContent = new WelcomePageViewModel();
|
||||
}
|
||||
|
||||
/// <summary>The composition root.</summary>
|
||||
public AppServices Services { get; }
|
||||
|
||||
/// <summary>The workspace sidebar.</summary>
|
||||
public SidebarViewModel Sidebar { get; }
|
||||
|
||||
/// <summary>The currently displayed content page.</summary>
|
||||
[ObservableProperty]
|
||||
private object? currentContent;
|
||||
|
||||
/// <summary>Shows the welcome page (no workspace active).</summary>
|
||||
public void ShowWelcome()
|
||||
{
|
||||
CurrentContent = new WelcomePageViewModel();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens (or switches to) a workspace from the UI flow: a plain folder
|
||||
/// prompts for initialization before opening.
|
||||
/// </summary>
|
||||
public async Task OpenWorkspaceWithInitializePromptAsync(string folderPath)
|
||||
{
|
||||
string canonical = Services.PathComparison.Normalize(folderPath);
|
||||
|
||||
if (!WorkspaceInitializer.IsWorkspace(canonical))
|
||||
{
|
||||
if (!Directory.Exists(canonical))
|
||||
{
|
||||
ShowFailure(Resources.State_DirectoryMissing_Title, Resources.State_DirectoryMissing_Detail);
|
||||
return;
|
||||
}
|
||||
|
||||
bool confirmed = await Sidebar.ConfirmInitialize.Handle(canonical);
|
||||
if (!confirmed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
WorkspaceInitializer.Initialize(canonical);
|
||||
WorkspacePreset.SeedColumns(canonical);
|
||||
}
|
||||
|
||||
TryOpenWorkspaceSession(canonical);
|
||||
}
|
||||
|
||||
/// <summary>Opens (or switches to) a workspace without any initialization prompt (IPC entry).</summary>
|
||||
public void OpenWorkspaceFromLaunch(string folderPath)
|
||||
{
|
||||
TryOpenWorkspaceSession(Services.PathComparison.Normalize(folderPath));
|
||||
}
|
||||
|
||||
/// <summary>Opens the session through the pool; typed failures map to localized state pages.</summary>
|
||||
public void TryOpenWorkspaceSession(string canonicalPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
WorkspaceSession session = Services.Pool.Open(canonicalPath);
|
||||
CurrentContent = new WorkspacePageViewModel(session);
|
||||
Sidebar.RebuildWorkspaceList();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
(string title, string detail) = DescribeOpenFailure(ex);
|
||||
ShowFailure(title, detail);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Displays a localized failure state page.</summary>
|
||||
private void ShowFailure(string title, string detail)
|
||||
{
|
||||
CurrentContent = new MessagePageViewModel(title, detail);
|
||||
}
|
||||
|
||||
/// <summary>Maps an open failure to localized title/detail text by exception type.</summary>
|
||||
private static (string Title, string Detail) DescribeOpenFailure(Exception exception) => exception switch
|
||||
{
|
||||
WorkspaceLockException => (Resources.State_LockConflict_Title, Resources.State_LockConflict_Detail),
|
||||
WorkspaceNotInitializedException => (Resources.State_NotInitialized_Title, Resources.State_NotInitialized_Detail),
|
||||
WorkspaceDirectoryMissingException => (Resources.State_DirectoryMissing_Title, Resources.State_DirectoryMissing_Detail),
|
||||
SchemaVersionException => (Resources.State_SchemaVersion_Title, Resources.State_SchemaVersion_Detail),
|
||||
_ => (Resources.State_Unknown_Title, exception.Message),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace YKanBan.ViewModels;
|
||||
|
||||
/// <summary>A selectable option item for combo boxes: a value plus its localized label.</summary>
|
||||
/// <param name="Value">The backing value (enum value or language code).</param>
|
||||
/// <param name="Label">The localized display label.</param>
|
||||
public sealed record OptionItem(object Value, string Label);
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace YKanBan.ViewModels.Pages;
|
||||
|
||||
/// <summary>A failure state page: a localized title with a detail line.</summary>
|
||||
public sealed class MessagePageViewModel : ViewModelBase
|
||||
{
|
||||
public MessagePageViewModel(string title, string detail)
|
||||
{
|
||||
Title = title;
|
||||
Detail = detail;
|
||||
}
|
||||
|
||||
/// <summary>Localized failure heading.</summary>
|
||||
public string Title { get; }
|
||||
|
||||
/// <summary>Localized failure explanation.</summary>
|
||||
public string Detail { get; }
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace YKanBan.ViewModels.Pages;
|
||||
|
||||
/// <summary>The welcome page: application identity plus a hint to open a workspace.</summary>
|
||||
public sealed class WelcomePageViewModel : ViewModelBase
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
namespace YKanBan.ViewModels.Pages;
|
||||
|
||||
/// <summary>
|
||||
/// An open workspace page. The board, tags and search views mount here in
|
||||
/// the later UI milestones; the frame shows the workspace identity for now.
|
||||
/// </summary>
|
||||
public sealed class WorkspacePageViewModel : ViewModelBase
|
||||
{
|
||||
public WorkspacePageViewModel(WorkspaceSession session)
|
||||
{
|
||||
FullPath = session.FolderPath;
|
||||
Name = Path.GetFileName(session.FolderPath);
|
||||
}
|
||||
|
||||
/// <summary>Canonical workspace folder path.</summary>
|
||||
public string FullPath { get; }
|
||||
|
||||
/// <summary>Display name: the folder name.</summary>
|
||||
public string Name { get; }
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.ViewModels.Pages;
|
||||
|
||||
namespace YKanBan.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// The sidebar: welcome and open-project buttons, the persistent workspace
|
||||
/// list with its sort options, and the settings/about entries at the bottom.
|
||||
/// </summary>
|
||||
public partial class SidebarViewModel : ViewModelBase
|
||||
{
|
||||
private readonly MainWindowViewModel _owner;
|
||||
private readonly AppServices _services;
|
||||
|
||||
public SidebarViewModel(MainWindowViewModel owner, AppServices services)
|
||||
{
|
||||
_owner = owner;
|
||||
_services = services;
|
||||
|
||||
SortOptions =
|
||||
[
|
||||
new OptionItem(SidebarSortOption.NameAsc, Resources.Sidebar_Sort_NameAsc),
|
||||
new OptionItem(SidebarSortOption.NameDesc, Resources.Sidebar_Sort_NameDesc),
|
||||
new OptionItem(SidebarSortOption.RecentlyUpdated, Resources.Sidebar_Sort_RecentlyUpdated),
|
||||
];
|
||||
selectedSort = SortOptions.Single(option => option.Value.Equals(services.Config.Sort.Sidebar));
|
||||
|
||||
RebuildWorkspaceList();
|
||||
}
|
||||
|
||||
/// <summary>Known workspaces in display order.</summary>
|
||||
public ObservableCollection<WorkspaceItemViewModel> Workspaces { get; } = [];
|
||||
|
||||
/// <summary>The available list sort modes.</summary>
|
||||
public IReadOnlyList<OptionItem> SortOptions { get; }
|
||||
|
||||
/// <summary>Asks the view for a folder via the system folder picker; null when cancelled.</summary>
|
||||
public Interaction<Unit, string?> PickFolder { get; } = new();
|
||||
|
||||
/// <summary>Asks the view to confirm initializing a plain folder as a workspace.</summary>
|
||||
public Interaction<string, bool> ConfirmInitialize { get; } = new();
|
||||
/// <summary>The selected list sort mode; persisted with the configuration.</summary>
|
||||
[ObservableProperty]
|
||||
private OptionItem? selectedSort;
|
||||
|
||||
/// <summary>Shows the welcome page.</summary>
|
||||
[RelayCommand]
|
||||
private void ShowWelcome()
|
||||
{
|
||||
_owner.ShowWelcome();
|
||||
}
|
||||
|
||||
/// <summary>Picks a folder and opens it as a workspace (offering initialization).</summary>
|
||||
[RelayCommand]
|
||||
private async Task OpenProjectAsync()
|
||||
{
|
||||
string? folder = await PickFolder.Handle(default);
|
||||
if (folder is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
await _owner.OpenWorkspaceWithInitializePromptAsync(folder);
|
||||
}
|
||||
|
||||
/// <summary>Rebuilds the list from the persistent registry, marking open workspaces.</summary>
|
||||
public void RebuildWorkspaceList()
|
||||
{
|
||||
Workspaces.Clear();
|
||||
foreach (WorkspaceRecord record in _services.Database.GetWorkspaces())
|
||||
{
|
||||
bool isOpen = _services.Pool.Find(record.Path) is not null;
|
||||
Workspaces.Add(new WorkspaceItemViewModel(this, record.Path, Path.GetFileName(record.Path), record.LastEditedAt, isOpen));
|
||||
}
|
||||
ReorderWorkspaceList();
|
||||
}
|
||||
|
||||
/// <summary>Opens a workspace when its sidebar entry is activated.</summary>
|
||||
public void OpenWorkspace(WorkspaceItemViewModel item)
|
||||
{
|
||||
_owner.TryOpenWorkspaceSession(item.FullPath);
|
||||
}
|
||||
|
||||
/// <summary>Releases the workspace resources and forgets its sidebar entry.</summary>
|
||||
public void RemoveWorkspace(WorkspaceItemViewModel item)
|
||||
{
|
||||
_services.Pool.Remove(item.FullPath);
|
||||
RebuildWorkspaceList();
|
||||
|
||||
// Removing the active workspace falls back to the welcome page.
|
||||
if (_owner.CurrentContent is WorkspacePageViewModel active && active.FullPath == item.FullPath)
|
||||
{
|
||||
_owner.ShowWelcome();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Applies the selected sort mode to the list in place.</summary>
|
||||
partial void OnSelectedSortChanged(OptionItem? value)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_services.Config.Sort.Sidebar = (SidebarSortOption)value.Value;
|
||||
ReorderWorkspaceList();
|
||||
}
|
||||
|
||||
/// <summary>Sorts the workspace collection by the current mode.</summary>
|
||||
private void ReorderWorkspaceList()
|
||||
{
|
||||
if (SelectedSort?.Value is not SidebarSortOption mode)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Comparison<WorkspaceItemViewModel> comparison = mode switch
|
||||
{
|
||||
SidebarSortOption.NameAsc => (a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase),
|
||||
SidebarSortOption.NameDesc => (a, b) => string.Compare(b.Name, a.Name, StringComparison.OrdinalIgnoreCase),
|
||||
SidebarSortOption.RecentlyUpdated => (a, b) => b.LastEditedAt.CompareTo(a.LastEditedAt),
|
||||
_ => (a, b) => 0,
|
||||
};
|
||||
|
||||
// Move each item into its sorted position (in-place keeps bindings alive).
|
||||
List<WorkspaceItemViewModel> ordered = Workspaces.ToList();
|
||||
ordered.Sort(comparison);
|
||||
for (int index = 0; index < ordered.Count; index++)
|
||||
{
|
||||
int current = Workspaces.IndexOf(ordered[index]);
|
||||
if (current != index)
|
||||
{
|
||||
Workspaces.Move(current, index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
namespace YKanBan.ViewModels;
|
||||
|
||||
/// <summary>One sidebar workspace entry.</summary>
|
||||
public partial class WorkspaceItemViewModel : ViewModelBase
|
||||
{
|
||||
private readonly SidebarViewModel _owner;
|
||||
|
||||
public WorkspaceItemViewModel(SidebarViewModel owner, string fullPath, string name, long lastEditedAt, bool isOpen)
|
||||
{
|
||||
_owner = owner;
|
||||
FullPath = fullPath;
|
||||
Name = name;
|
||||
LastEditedAt = lastEditedAt;
|
||||
IsOpen = isOpen;
|
||||
}
|
||||
|
||||
/// <summary>Canonical workspace folder path.</summary>
|
||||
public string FullPath { get; }
|
||||
|
||||
/// <summary>Display name: the folder name.</summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>Last edit time in Unix seconds, used by the "recently updated" sort.</summary>
|
||||
public long LastEditedAt { get; }
|
||||
|
||||
/// <summary>Whether the workspace currently has an open session.</summary>
|
||||
[ObservableProperty]
|
||||
private bool isOpen;
|
||||
|
||||
/// <summary>Opens (or switches to) this workspace.</summary>
|
||||
[RelayCommand]
|
||||
private void Open()
|
||||
{
|
||||
_owner.OpenWorkspace(this);
|
||||
}
|
||||
|
||||
/// <summary>Releases the workspace resources and removes the sidebar entry.</summary>
|
||||
[RelayCommand]
|
||||
private void Remove()
|
||||
{
|
||||
_owner.RemoveWorkspace(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
xmlns:lang="using:YKanBan"
|
||||
x:Class="YKanBan.Views.Dialogs.AboutDialog"
|
||||
x:DataType="vm:AboutDialogViewModel"
|
||||
Title="{x:Static lang:Resources.About_Title}"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
SizeToContent="Height" Width="380" CanResize="False"
|
||||
ShowInTaskbar="False">
|
||||
|
||||
<StackPanel Margin="20" Spacing="10">
|
||||
<TextBlock Text="{Binding ApplicationName}" FontSize="22" FontWeight="Bold"/>
|
||||
|
||||
<TextBlock Text="{Binding VersionText}" Opacity="0.8"/>
|
||||
|
||||
<Grid ColumnDefinitions="Auto,*" Margin="0,6,0,0">
|
||||
<TextBlock Grid.Column="0" Text="{x:Static lang:Resources.About_Repository}" Opacity="0.7" Margin="0,0,8,0"/>
|
||||
<TextBlock Grid.Column="1" Text="{Binding RepositoryUrl}" TextWrapping="Wrap"/>
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="Auto,*">
|
||||
<TextBlock Grid.Column="0" Text="{x:Static lang:Resources.About_License}" Opacity="0.7" Margin="0,0,8,0"/>
|
||||
<TextBlock Grid.Column="1" Text="{Binding LicenseValue}"/>
|
||||
</Grid>
|
||||
|
||||
<Button Content="{x:Static lang:Resources.Common_Close}" IsCancel="True"
|
||||
HorizontalAlignment="Right" MinWidth="90" Margin="0,8,0,0"/>
|
||||
</StackPanel>
|
||||
</Window>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class AboutDialog : Window
|
||||
{
|
||||
public AboutDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
x:Class="YKanBan.Views.Dialogs.ConfirmDialog"
|
||||
x:DataType="vm:ConfirmDialogViewModel"
|
||||
Title="{Binding Title}"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
SizeToContent="Height" Width="440" CanResize="False"
|
||||
ShowInTaskbar="False">
|
||||
|
||||
<StackPanel Margin="20" Spacing="16">
|
||||
<TextBlock Text="{Binding Message}" TextWrapping="Wrap"/>
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" HorizontalAlignment="Right">
|
||||
<Button Content="{Binding CancelText}" MinWidth="90" IsCancel="True" Click="OnCancelClick"/>
|
||||
<Button Content="{Binding ConfirmText}" MinWidth="90" IsDefault="True" Classes="Primary" Click="OnConfirmClick"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Window>
|
||||
@@ -0,0 +1,16 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class ConfirmDialog : Window
|
||||
{
|
||||
public ConfirmDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void OnConfirmClick(object? sender, RoutedEventArgs e) => Close(true);
|
||||
|
||||
private void OnCancelClick(object? sender, RoutedEventArgs e) => Close(false);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
xmlns:vmBase="using:YKanBan.ViewModels"
|
||||
xmlns:lang="using:YKanBan"
|
||||
x:Class="YKanBan.Views.Dialogs.SettingsDialog"
|
||||
x:DataType="vm:SettingsDialogViewModel"
|
||||
Title="{x:Static lang:Resources.Settings_Title}"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
SizeToContent="Height" Width="440" CanResize="False"
|
||||
ShowInTaskbar="False">
|
||||
|
||||
<StackPanel Margin="20" Spacing="14">
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Settings_Language}"/>
|
||||
<ComboBox ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}" HorizontalAlignment="Stretch">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vmBase:OptionItem">
|
||||
<TextBlock Text="{Binding Label}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<TextBlock Text="{x:Static lang:Resources.Settings_Language_RestartNotice}"
|
||||
IsVisible="{Binding RestartNoticeVisible}"
|
||||
FontStyle="Italic" Opacity="0.7"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Settings_Theme}"/>
|
||||
<ComboBox ItemsSource="{Binding Themes}" SelectedItem="{Binding SelectedTheme}" HorizontalAlignment="Stretch">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vmBase:OptionItem">
|
||||
<TextBlock Text="{Binding Label}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="6">
|
||||
<TextBlock Text="{x:Static lang:Resources.Settings_Confirmations}"/>
|
||||
<CheckBox Content="{x:Static lang:Resources.Settings_ConfirmDeleteCard}" IsChecked="{Binding ConfirmDeleteCard}"/>
|
||||
<CheckBox Content="{x:Static lang:Resources.Settings_ConfirmDeleteColumn}" IsChecked="{Binding ConfirmDeleteColumn}"/>
|
||||
<CheckBox Content="{x:Static lang:Resources.Settings_ConfirmDeleteTag}" IsChecked="{Binding ConfirmDeleteTag}"/>
|
||||
<CheckBox Content="{x:Static lang:Resources.Settings_ConfirmDiscardEdit}" IsChecked="{Binding ConfirmDiscardEdit}"/>
|
||||
</StackPanel>
|
||||
|
||||
<Button Content="{x:Static lang:Resources.Common_Close}" IsCancel="True"
|
||||
HorizontalAlignment="Right" MinWidth="90"/>
|
||||
</StackPanel>
|
||||
</Window>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class SettingsDialog : Window
|
||||
{
|
||||
public SettingsDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,107 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels"
|
||||
xmlns:pages="using:YKanBan.Views.Pages"
|
||||
xmlns:lang="using:YKanBan"
|
||||
xmlns:iconPacks="using:IconPacks.Avalonia.Lucide"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
|
||||
mc:Ignorable="d" d:DesignWidth="1000" d:DesignHeight="640"
|
||||
x:Class="YKanBan.Views.MainWindow"
|
||||
x:DataType="vm:MainWindowViewModel"
|
||||
Title="YKanBan">
|
||||
Icon="/Assets/avalonia-logo.ico"
|
||||
Title="{x:Static lang:Resources.App_Name}"
|
||||
Width="1000" Height="640" MinWidth="720" MinHeight="480">
|
||||
|
||||
<Design.DataContext>
|
||||
<vm:MainWindowViewModel/>
|
||||
</Design.DataContext>
|
||||
<Grid ColumnDefinitions="260,*">
|
||||
<!-- Sidebar -->
|
||||
<Border Grid.Column="0"
|
||||
Background="{DynamicResource SidebarBackgroundBrush}"
|
||||
BorderBrush="{DynamicResource SidebarBorderBrush}"
|
||||
BorderThickness="0,0,1,0"
|
||||
Padding="8">
|
||||
<Grid RowDefinitions="Auto,Auto,Auto,Auto,*,Auto">
|
||||
<Button Grid.Row="0" Margin="0,8,0,4" HorizontalAlignment="Stretch" HorizontalContentAlignment="Left"
|
||||
Command="{Binding Sidebar.ShowWelcomeCommand}">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<iconPacks:PackIconLucide Kind="House"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Sidebar_Welcome}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
|
||||
<Button Grid.Row="1" Margin="0,4" HorizontalAlignment="Stretch" HorizontalContentAlignment="Left"
|
||||
Command="{Binding Sidebar.OpenProjectCommand}">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<iconPacks:PackIconLucide Kind="FolderPlus"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Sidebar_OpenProject}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
|
||||
<TextBlock Grid.Row="2" Margin="8,12,0,4" Opacity="0.65"
|
||||
Text="{x:Static lang:Resources.Sidebar_SortLabel}"/>
|
||||
<ComboBox Grid.Row="3" Margin="0,0,0,8" HorizontalAlignment="Stretch"
|
||||
ItemsSource="{Binding Sidebar.SortOptions}"
|
||||
SelectedItem="{Binding Sidebar.SelectedSort}">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:OptionItem">
|
||||
<TextBlock Text="{Binding Label}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
|
||||
<ListBox Grid.Row="4" ItemsSource="{Binding Sidebar.Workspaces}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:WorkspaceItemViewModel">
|
||||
<Button Margin="0,1" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch"
|
||||
Command="{Binding OpenCommand}">
|
||||
<Button.ContextMenu>
|
||||
<ContextMenu>
|
||||
<MenuItem Header="{x:Static lang:Resources.Sidebar_RemoveFromList}"
|
||||
Command="{Binding RemoveCommand}"/>
|
||||
</ContextMenu>
|
||||
</Button.ContextMenu>
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<TextBlock Grid.Column="0" Text="{Binding Name}" TextTrimming="CharacterEllipsis"/>
|
||||
<TextBlock Grid.Column="1" Text="●" Opacity="0.55"
|
||||
IsVisible="{Binding IsOpen}"/>
|
||||
</Grid>
|
||||
</Button>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<StackPanel Grid.Row="5" Orientation="Horizontal" Spacing="8" Margin="0,8">
|
||||
<Button Click="OnSettingsClick">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<iconPacks:PackIconLucide Kind="Settings"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Sidebar_Settings}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button Click="OnAboutClick">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<iconPacks:PackIconLucide Kind="Info"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Sidebar_About}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Content area -->
|
||||
<Border Grid.Column="1">
|
||||
<ContentControl Content="{Binding CurrentContent}">
|
||||
<ContentControl.DataTemplates>
|
||||
<DataTemplate x:DataType="vm:Pages.WelcomePageViewModel">
|
||||
<pages:WelcomePage/>
|
||||
</DataTemplate>
|
||||
<DataTemplate x:DataType="vm:Pages.WorkspacePageViewModel">
|
||||
<pages:WorkspacePage/>
|
||||
</DataTemplate>
|
||||
<DataTemplate x:DataType="vm:Pages.MessagePageViewModel">
|
||||
<pages:MessagePage/>
|
||||
</DataTemplate>
|
||||
</ContentControl.DataTemplates>
|
||||
</ContentControl>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -1,11 +1,76 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Platform.Storage;
|
||||
using YKanBan.ViewModels;
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
using YKanBan.Views.Dialogs;
|
||||
using Resx = YKanBan.Resources;
|
||||
|
||||
namespace YKanBan.Views;
|
||||
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
private bool _interactionsRegistered;
|
||||
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
protected override void OnDataContextChanged(EventArgs e)
|
||||
{
|
||||
base.OnDataContextChanged(e);
|
||||
if (DataContext is MainWindowViewModel viewModel && !_interactionsRegistered)
|
||||
{
|
||||
_interactionsRegistered = true;
|
||||
RegisterInteractionHandlers(viewModel);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Wires the view model's dialog interactions to this window.</summary>
|
||||
private void RegisterInteractionHandlers(MainWindowViewModel viewModel)
|
||||
{
|
||||
viewModel.Sidebar.PickFolder.RegisterHandler(async _ =>
|
||||
{
|
||||
IReadOnlyList<IStorageFolder> folders = await StorageProvider.OpenFolderPickerAsync(
|
||||
new FolderPickerOpenOptions
|
||||
{
|
||||
Title = Resx.Sidebar_OpenProject,
|
||||
AllowMultiple = false,
|
||||
});
|
||||
return folders.Count == 1 ? folders[0].TryGetLocalPath() : null;
|
||||
});
|
||||
|
||||
viewModel.Sidebar.ConfirmInitialize.RegisterHandler(async folderPath =>
|
||||
{
|
||||
var dialog = new ConfirmDialog
|
||||
{
|
||||
DataContext = new ConfirmDialogViewModel(
|
||||
Resx.Dialog_InitializeTitle,
|
||||
string.Format(CultureInfo.CurrentCulture, Resx.Dialog_InitializeMessage, folderPath)),
|
||||
};
|
||||
return await dialog.ShowDialog<bool>(this);
|
||||
});
|
||||
}
|
||||
|
||||
private async void OnSettingsClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
var dialog = new SettingsDialog
|
||||
{
|
||||
DataContext = new SettingsDialogViewModel(App.Services),
|
||||
};
|
||||
await dialog.ShowDialog(this);
|
||||
}
|
||||
|
||||
private async void OnAboutClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
var dialog = new AboutDialog
|
||||
{
|
||||
DataContext = new AboutDialogViewModel(),
|
||||
};
|
||||
await dialog.ShowDialog(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Pages"
|
||||
x:Class="YKanBan.Views.Pages.MessagePage"
|
||||
x:DataType="vm:MessagePageViewModel">
|
||||
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Spacing="10">
|
||||
<TextBlock Text="{Binding Title}" FontSize="20" FontWeight="SemiBold" HorizontalAlignment="Center"/>
|
||||
<TextBlock Text="{Binding Detail}" Opacity="0.7" HorizontalAlignment="Center" TextWrapping="Wrap"/>
|
||||
</StackPanel>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace YKanBan.Views.Pages;
|
||||
|
||||
public partial class MessagePage : UserControl
|
||||
{
|
||||
public MessagePage()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:lang="using:YKanBan"
|
||||
x:Class="YKanBan.Views.Pages.WelcomePage">
|
||||
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Spacing="12">
|
||||
<TextBlock Text="{x:Static lang:Resources.App_Name}" FontSize="32" FontWeight="Bold"
|
||||
HorizontalAlignment="Center"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Welcome_Hint}" Opacity="0.65"
|
||||
HorizontalAlignment="Center"/>
|
||||
</StackPanel>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace YKanBan.Views.Pages;
|
||||
|
||||
public partial class WelcomePage : UserControl
|
||||
{
|
||||
public WelcomePage()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Pages"
|
||||
x:Class="YKanBan.Views.Pages.WorkspacePage"
|
||||
x:DataType="vm:WorkspacePageViewModel">
|
||||
<StackPanel Margin="24,20" Spacing="6">
|
||||
<TextBlock Text="{Binding Name}" FontSize="22" FontWeight="SemiBold"/>
|
||||
<TextBlock Text="{Binding FullPath}" Opacity="0.6" FontSize="12"/>
|
||||
</StackPanel>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace YKanBan.Views.Pages;
|
||||
|
||||
public partial class WorkspacePage : UserControl
|
||||
{
|
||||
public WorkspacePage()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user