Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9f39a3a53 | ||
|
|
60619e0290 | ||
|
|
e3265e3c89 | ||
|
|
157f597eed | ||
|
|
1140cd500b | ||
|
|
7f277d1630 | ||
|
|
647232c447 | ||
|
|
78e5faa3c4 | ||
|
|
97f79db3f1 | ||
|
|
90a7531a27 |
No files matched your search
@@ -0,0 +1,2 @@
|
|||||||
|
# Shell scripts run under bash on every CI runner, including Windows checkouts with autocrlf.
|
||||||
|
*.sh text eol=lf
|
||||||
+31
-18
@@ -1,20 +1,25 @@
|
|||||||
|
# Manual-only release build (PLAN §7.2): no push or pull_request trigger.
|
||||||
|
# Each RID job runs build -> test -> publish/pack -> upload; a failing step
|
||||||
|
# skips the rest of that job, so a RID whose tests fail produces no artifact.
|
||||||
|
# No GitHub Release is created.
|
||||||
name: Build
|
name: Build
|
||||||
|
|
||||||
# Manual trigger only. There is no push/pull_request trigger on purpose:
|
|
||||||
# the project must not depend on push-triggered CI.
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
# Least privilege: the workflow only reads the repository and uploads artifacts.
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
|
||||||
|
env:
|
||||||
|
DOTNET_NOLOGO: "true"
|
||||||
|
DOTNET_CLI_TELEMETRY_OPTOUT: "true"
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
name: ${{ matrix.rid }}
|
name: ${{ matrix.rid }}
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
# One failing RID must not cancel the others.
|
# Every RID stands on its own: one failure does not cancel the others.
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
@@ -22,35 +27,43 @@ jobs:
|
|||||||
os: windows-latest
|
os: windows-latest
|
||||||
- rid: linux-x64
|
- rid: linux-x64
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
|
- rid: osx-x64
|
||||||
|
os: macos-15-intel
|
||||||
- rid: osx-arm64
|
- rid: osx-arm64
|
||||||
os: macos-latest
|
os: macos-15
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Setup .NET
|
- name: Set up .NET
|
||||||
uses: actions/setup-dotnet@v4
|
uses: actions/setup-dotnet@v4
|
||||||
with:
|
with:
|
||||||
dotnet-version: 9.0.x
|
dotnet-version: 10.0.x
|
||||||
|
|
||||||
- name: Restore
|
|
||||||
run: dotnet restore YKanBan.slnx
|
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: dotnet build YKanBan.slnx -c Release --no-restore
|
run: dotnet build YKanBan.slnx -c Release
|
||||||
|
|
||||||
# A failing test fails the job, so the publish and upload steps below are
|
|
||||||
# skipped and this RID produces no artifact.
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: dotnet test YKanBan.slnx -c Release --no-build --no-restore
|
run: dotnet test YKanBan.slnx -c Release --no-build
|
||||||
|
|
||||||
- name: Publish
|
- name: Publish
|
||||||
run: dotnet publish YKanBan/YKanBan.csproj -c Release -r ${{ matrix.rid }} --self-contained true -o publish/${{ matrix.rid }}
|
run: >
|
||||||
|
dotnet publish YKanBan/YKanBan.csproj -c Release -r ${{ matrix.rid }}
|
||||||
|
--self-contained -o publish/${{ matrix.rid }}
|
||||||
|
|
||||||
|
- name: Pack
|
||||||
|
id: pack
|
||||||
|
run: |
|
||||||
|
version="$(dotnet msbuild YKanBan/YKanBan.csproj -getProperty:Version)"
|
||||||
|
bash packaging/package.sh ${{ matrix.rid }} publish/${{ matrix.rid }} dist "$version"
|
||||||
|
echo "name=YKanBan-$version-${{ matrix.rid }}" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Upload artifact
|
- name: Upload artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: YKanBan-${{ matrix.rid }}
|
name: ${{ steps.pack.outputs.name }}
|
||||||
path: publish/${{ matrix.rid }}
|
path: dist/*
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 yyc12345
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -4,11 +4,20 @@ A personal, local/offline kanban board. Cross-platform desktop app built with Av
|
|||||||
|
|
||||||
See [USAGE.md](USAGE.md) for workspaces, backups, the search syntax and command-line usage.
|
See [USAGE.md](USAGE.md) for workspaces, backups, the search syntax and command-line usage.
|
||||||
|
|
||||||
## Build and test
|
## Building
|
||||||
|
|
||||||
|
Requires the .NET 10 SDK.
|
||||||
|
|
||||||
```
|
```
|
||||||
dotnet build YKanBan.slnx
|
dotnet build YKanBan.slnx
|
||||||
dotnet test YKanBan.slnx
|
dotnet test YKanBan.slnx
|
||||||
|
dotnet run --project YKanBan -- <path>
|
||||||
```
|
```
|
||||||
|
|
||||||
Packages are pinned in `YKanBan/YKanBan.csproj`.
|
Packages are pinned in `YKanBan/YKanBan.csproj`.
|
||||||
|
|
||||||
|
Release archives for win-x64, linux-x64, osx-x64 and osx-arm64 are produced by the manually triggered workflow in `.github/workflows/build.yml`; `packaging/package.sh` packs one published RID.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT — see [LICENSE](LICENSE).
|
||||||
@@ -14,9 +14,8 @@ YKanBan is a local/offline kanban board. It works like Git in one respect: all d
|
|||||||
ykanban <path>
|
ykanban <path>
|
||||||
```
|
```
|
||||||
|
|
||||||
- `<path>` is the workspace folder to open.
|
- `<path>` is the workspace folder to open. A relative path is resolved against the current working directory.
|
||||||
- Starting without arguments, or with invalid arguments, shows the argument error page.
|
- Exactly one argument is required. Starting without arguments, with more than one argument, with a blank argument, with an argument starting with `-` (any option form, `--help` included), or with a path that does not exist or is not a folder shows the argument error page.
|
||||||
- If the path does not exist, the folder-missing page is shown.
|
|
||||||
- If the folder exists but has no `.ykanban`, the not-initialized page is shown with an **Initialize Workspace** button. Initializing creates the database and seeds the preset columns and tags in the current interface language.
|
- If the folder exists but has no `.ykanban`, the not-initialized page is shown with an **Initialize Workspace** button. Initializing creates the database and seeds the preset columns and tags in the current interface language.
|
||||||
|
|
||||||
## 2. Do not commit `.ykanban` to Git
|
## 2. Do not commit `.ykanban` to Git
|
||||||
@@ -67,8 +66,8 @@ phrase := '"' any text '"' // escapes: \" to literal quote and
|
|||||||
- `tag:NAME` matches a tag by its **exact** name.
|
- `tag:NAME` matches a tag by its **exact** name.
|
||||||
- `column:TITLE` matches a column by its **exact** title.
|
- `column:TITLE` matches a column by its **exact** title.
|
||||||
- `title:TEXT` matches a substring of the card title, and `content:TEXT` matches a substring of the card content.
|
- `title:TEXT` matches a substring of the card title, and `content:TEXT` matches a substring of the card content.
|
||||||
- `id:N` matches a card by its **exact** numeric id.
|
- `id:N` matches a card by its **exact** positive integer id; an optional leading `#` is allowed (`id:#61`).
|
||||||
- All matching is case-insensitive (SQLite ASCII semantics).
|
- All matching is Unicode case-insensitive (both sides are case-folded before comparing).
|
||||||
- Quotes allow values with spaces, for example `tag:"release notes"` or `column:"In Progress"`.
|
- Quotes allow values with spaces, for example `tag:"release notes"` or `column:"In Progress"`.
|
||||||
- Inside a phrase, `\"` produces a literal quote and `\\` a literal backslash.
|
- Inside a phrase, `\"` produces a literal quote and `\\` a literal backslash.
|
||||||
|
|
||||||
@@ -82,9 +81,15 @@ The following are invalid:
|
|||||||
- a dangling operator, for example `bug AND`;
|
- a dangling operator, for example `bug AND`;
|
||||||
- consecutive operators, for example `a AND OR b`;
|
- consecutive operators, for example `a AND OR b`;
|
||||||
- a qualifier without a value, for example `tag:`;
|
- a qualifier without a value, for example `tag:`;
|
||||||
|
- a qualifier phrase separated from its key by whitespace, for example `tag: "x"` (write `tag:"x"` instead);
|
||||||
- an unterminated phrase, for example `"abc`;
|
- an unterminated phrase, for example `"abc`;
|
||||||
|
- an empty phrase, for example `""`;
|
||||||
|
- a phrase glued to other text, for example `a"b"`;
|
||||||
- an invalid escape inside a phrase (a backslash not followed by `"` or `\`), for example `tag:"a\x"`;
|
- an invalid escape inside a phrase (a backslash not followed by `"` or `\`), for example `tag:"a\x"`;
|
||||||
- an unknown qualifier key. Only `tag`, `title`, `content`, `id` and `column` are valid, and the key is case-sensitive, so `Tag:x` is an error. A word whose colon is not preceded by an identifier (for example `:foo`) is treated as plain text.
|
- a bare backslash in a word, for example `a\b`;
|
||||||
|
- an unquoted qualifier value containing `:` or equal to `AND`/`OR`, for example `tag:a:b` (quote the value instead);
|
||||||
|
- an id value that is not an unquoted positive integer with an optional `#`, for example `id:0`, `id:-1` or `id:"1"`;
|
||||||
|
- an unknown qualifier key. Only `tag`, `title`, `content`, `id` and `column` are valid, and the key is case-sensitive, so `Tag:x` is an error. A colon not preceded by a valid key (for example `:foo` or `http://x`) is an error; quote such text to search for it literally.
|
||||||
|
|
||||||
## 5. Export
|
## 5. Export
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Conventions;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Source-level guards for code-behind conventions (plan §8.1): inside control,
|
||||||
|
/// window and application code-behind a bare <c>Resources.Key</c> resolves to
|
||||||
|
/// the <c>StyledElement.Resources</c> instance property, so the generated class
|
||||||
|
/// must be written as <c>YKanBan.Resources</c> (or through a using alias).
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public partial class CodeBehindConventionTests {
|
||||||
|
/// <summary>A <c>Resources.</c> member access not preceded by a qualifier or identifier character.</summary>
|
||||||
|
[GeneratedRegex(@"(?<![\w.])Resources\.")]
|
||||||
|
private static partial Regex BareResourcesAccess();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Locates the application project's source folder from this file's compile-time path.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="thisFile">Filled in by the compiler.</param>
|
||||||
|
/// <returns>The YKanBan project folder.</returns>
|
||||||
|
private static string ApplicationSourceFolder([CallerFilePath] string thisFile = "") {
|
||||||
|
DirectoryInfo? directory = new FileInfo(thisFile).Directory;
|
||||||
|
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "YKanBan", "YKanBan.csproj"))) {
|
||||||
|
directory = directory.Parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsNotNull(directory, "Repository root not found from the test source path.");
|
||||||
|
return Path.Combine(directory.FullName, "YKanBan");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CodeBehindNeverUsesBareResourcesClassName() {
|
||||||
|
string root = ApplicationSourceFolder();
|
||||||
|
string[] files = Directory.GetFiles(root, "*.axaml.cs", SearchOption.AllDirectories)
|
||||||
|
.Where(path => !path.Split(Path.DirectorySeparatorChar).Any(part => part is "obj" or "bin"))
|
||||||
|
.ToArray();
|
||||||
|
Assert.IsTrue(files.Length > 0, "No code-behind files found.");
|
||||||
|
|
||||||
|
var offenders = new List<string>();
|
||||||
|
foreach (string file in files) {
|
||||||
|
string[] lines = File.ReadAllLines(file);
|
||||||
|
for (int index = 0; index < lines.Length; index++) {
|
||||||
|
if (BareResourcesAccess().IsMatch(lines[index])) {
|
||||||
|
offenders.Add($"{Path.GetRelativePath(root, file)}:{index + 1}: {lines[index].Trim()}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(0, offenders.Count, "Use YKanBan.Resources in code-behind:" + Environment.NewLine + string.Join(Environment.NewLine, offenders));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -81,8 +81,8 @@ public class MarkdownExporterTests {
|
|||||||
/// <param name="culture">The UI culture.</param>
|
/// <param name="culture">The UI culture.</param>
|
||||||
/// <returns>The expected Markdown document.</returns>
|
/// <returns>The expected Markdown document.</returns>
|
||||||
private static string BuildExpected(CultureInfo culture) {
|
private static string BuildExpected(CultureInfo culture) {
|
||||||
string created = Local(2026, 9, 1, 10, 0).ToString(Resources.Export_CardTimePattern, culture);
|
string created = Local(2026, 9, 1, 10, 0).ToString(Resources.Export_TimePattern, culture);
|
||||||
string updated = Local(2026, 9, 28, 18, 30).ToString(Resources.Export_CardTimePattern, culture);
|
string updated = Local(2026, 9, 28, 18, 30).ToString(Resources.Export_TimePattern, culture);
|
||||||
|
|
||||||
var builder = new StringBuilder();
|
var builder = new StringBuilder();
|
||||||
|
|
||||||
@@ -181,7 +181,64 @@ public class MarkdownExporterTests {
|
|||||||
[(tag, 0L)],
|
[(tag, 0L)],
|
||||||
ExportedAt);
|
ExportedAt);
|
||||||
|
|
||||||
StringAssert.Contains(markdown, "| a\\|b | #112233 | first second | 0 |");
|
StringAssert.Contains(markdown, "| a\\|b | #112233 | first<br>second | 0 |");
|
||||||
|
} finally {
|
||||||
|
Resources.Culture = original;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TagTableCellsEscapeBackslashes() {
|
||||||
|
CultureInfo? original = Resources.Culture;
|
||||||
|
try {
|
||||||
|
Resources.Culture = new CultureInfo("en");
|
||||||
|
var tag = new TagModel(1, "a\\b", RgbColor.Parse("#112233"), "c\\|d");
|
||||||
|
string markdown = MarkdownExporter.Export(
|
||||||
|
"W",
|
||||||
|
[new ColumnModel(1, "C", string.Empty, 1, 1)],
|
||||||
|
[],
|
||||||
|
[(tag, 0L)],
|
||||||
|
ExportedAt);
|
||||||
|
|
||||||
|
StringAssert.Contains(markdown, "| a\\\\b | #112233 | c\\\\\\|d | 0 |");
|
||||||
|
} finally {
|
||||||
|
Resources.Culture = original;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TagNameWithBacktickUsesLongerFence() {
|
||||||
|
CultureInfo? original = Resources.Culture;
|
||||||
|
try {
|
||||||
|
Resources.Culture = new CultureInfo("en");
|
||||||
|
var tag = new TagModel(1, "a`b", RgbColor.Parse("#112233"), string.Empty);
|
||||||
|
string markdown = MarkdownExporter.Export(
|
||||||
|
"W",
|
||||||
|
[new ColumnModel(1, "C", string.Empty, 1, 1)],
|
||||||
|
[new CardModel(1, 1, "T", string.Empty, 1, 1, [tag])],
|
||||||
|
[(tag, 1L)],
|
||||||
|
ExportedAt);
|
||||||
|
|
||||||
|
StringAssert.Contains(markdown, "``a`b``");
|
||||||
|
} finally {
|
||||||
|
Resources.Culture = original;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void FileNameDropsInvalidCharactersAndFallsBackToAppName() {
|
||||||
|
CultureInfo? original = Resources.Culture;
|
||||||
|
try {
|
||||||
|
Resources.Culture = new CultureInfo("en");
|
||||||
|
|
||||||
|
// A drive root workspace name "D:\" must not leak ':' or '\' into the file name.
|
||||||
|
string name = MarkdownExporter.BuildFileName("D:\\", ExportedAt);
|
||||||
|
Assert.IsFalse(name.Contains(':'));
|
||||||
|
Assert.IsFalse(name.Contains('\\'));
|
||||||
|
|
||||||
|
// A name made only of invalid characters falls back to the application name.
|
||||||
|
string fallback = MarkdownExporter.BuildFileName("///", ExportedAt);
|
||||||
|
StringAssert.StartsWith(fallback, Resources.App_Name);
|
||||||
} finally {
|
} finally {
|
||||||
Resources.Culture = original;
|
Resources.Culture = original;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
using YKanBan.Launching;
|
using YKanBan.Launching;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
namespace YKanBan.Tests.Launching;
|
namespace YKanBan.Tests.Launching;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Tests for the <c>ykanban <path></c> command-line contract across its
|
/// Tests for the <c>ykanban <path></c> command-line contract: exactly one
|
||||||
/// three branches: no argument, one valid path, and invalid input.
|
/// existing folder, resolved to an absolute path; everything else is rejected.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[TestClass]
|
[TestClass]
|
||||||
public class LaunchArgumentsTests {
|
public class LaunchArgumentsTests {
|
||||||
@@ -27,9 +28,58 @@ public class LaunchArgumentsTests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void SinglePathIsAccepted() {
|
[DataRow("--help")]
|
||||||
bool parsed = LaunchArguments.TryParse([@"C:\Repo\MyProject"], out string? path);
|
[DataRow("-x")]
|
||||||
|
public void OptionLikeArgumentIsRejected(string argument) {
|
||||||
|
Assert.IsFalse(LaunchArguments.TryParse([argument], out string? path));
|
||||||
|
Assert.IsNull(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void NonExistentFolderIsRejected() {
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string missing = Path.Combine(directory.FullPath, "nope");
|
||||||
|
|
||||||
|
Assert.IsFalse(LaunchArguments.TryParse([missing], out string? path));
|
||||||
|
Assert.IsNull(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void FileInsteadOfFolderIsRejected() {
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string file = Path.Combine(directory.FullPath, "file.txt");
|
||||||
|
File.WriteAllText(file, "x");
|
||||||
|
|
||||||
|
Assert.IsFalse(LaunchArguments.TryParse([file], out string? path));
|
||||||
|
Assert.IsNull(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ExistingFolderIsAcceptedAsAnAbsolutePath() {
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
|
||||||
|
bool parsed = LaunchArguments.TryParse([directory.FullPath], out string? path);
|
||||||
|
|
||||||
Assert.IsTrue(parsed);
|
Assert.IsTrue(parsed);
|
||||||
Assert.AreEqual(@"C:\Repo\MyProject", path);
|
Assert.AreEqual(Path.GetFullPath(directory.FullPath), path);
|
||||||
|
Assert.IsTrue(Path.IsPathRooted(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void RelativePathIsResolvedToAbsolute() {
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string relative = Path.GetRelativePath(Environment.CurrentDirectory, directory.FullPath);
|
||||||
|
|
||||||
|
bool parsed = LaunchArguments.TryParse([relative], out string? path);
|
||||||
|
|
||||||
|
Assert.IsTrue(parsed);
|
||||||
|
Assert.IsTrue(Path.IsPathRooted(path));
|
||||||
|
Assert.AreEqual(Path.GetFullPath(relative), path);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void MalformedPathIsRejected() {
|
||||||
|
Assert.IsFalse(LaunchArguments.TryParse(["bad\0path"], out string? path));
|
||||||
|
Assert.IsNull(path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -130,8 +130,9 @@ public class SearchQueryParserTests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void QualifierValueMayContainColons() {
|
public void QuotedQualifierValueMayContainColonsAndOperators() {
|
||||||
AssertParsesTo(new SearchNode.TagName("a:b"), "tag:a:b");
|
AssertParsesTo(new SearchNode.TagName("a:b"), "tag:\"a:b\"");
|
||||||
|
AssertParsesTo(new SearchNode.TagName("AND"), "tag:\"AND\"");
|
||||||
}
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
@@ -148,12 +149,18 @@ public class SearchQueryParserTests {
|
|||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void IdQualifierParsesNumber() {
|
public void IdQualifierParsesNumber() {
|
||||||
AssertParsesTo(new SearchNode.CardId(42), "id:42");
|
AssertParsesTo(new SearchNode.CardId(42), "id:42");
|
||||||
AssertParsesTo(new SearchNode.CardId(12), "id:\"12\"");
|
AssertParsesTo(new SearchNode.CardId(61), "id:#61");
|
||||||
}
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void ColonWithoutKeyPrefixIsFreeText() {
|
public void QuotedTextWithColonIsFreeText() {
|
||||||
AssertParsesTo(new SearchNode.FreeText(":foo"), ":foo");
|
AssertParsesTo(new SearchNode.FreeText("http://x"), "\"http://x\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void WordMayContainHashAndPunctuation() {
|
||||||
|
AssertParsesTo(new SearchNode.FreeText("#61"), "#61");
|
||||||
|
AssertParsesTo(new SearchNode.FreeText("c#/.net"), "c#/.net");
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -227,8 +234,84 @@ public class SearchQueryParserTests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void NonNumericIdIsAnError() {
|
[DataRow("tag: \"x\"")]
|
||||||
AssertSyntaxError("id:12x");
|
[DataRow("title: \"a b\"")]
|
||||||
|
public void SpacedQualifierPhraseValueIsAnError(string text) {
|
||||||
|
AssertSyntaxError(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("a\"b\"")]
|
||||||
|
[DataRow("\"a\"b")]
|
||||||
|
[DataRow("\"a\"\"b\"")]
|
||||||
|
[DataRow("tag:\"x\"y")]
|
||||||
|
[DataRow("tag:\"x\"\"y\"")]
|
||||||
|
public void PhraseGluedToOtherTextIsAnError(string text) {
|
||||||
|
AssertSyntaxError(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("\"\"")]
|
||||||
|
[DataRow("a \"\"")]
|
||||||
|
[DataRow("tag:\"\"")]
|
||||||
|
public void EmptyPhraseIsAnError(string text) {
|
||||||
|
AssertSyntaxError(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void PhraseMayTouchParentheses() {
|
||||||
|
AssertParsesTo(
|
||||||
|
new SearchNode.And([new SearchNode.FreeText("a b"), new SearchNode.FreeText("c")]),
|
||||||
|
"(\"a b\")(c)");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("id:12x")]
|
||||||
|
[DataRow("id:abc")]
|
||||||
|
[DataRow("id:0")]
|
||||||
|
[DataRow("id:-1")]
|
||||||
|
[DataRow("id:+1")]
|
||||||
|
[DataRow("id:#")]
|
||||||
|
[DataRow("id:##1")]
|
||||||
|
[DataRow("id:1.5")]
|
||||||
|
[DataRow("id:٣")]
|
||||||
|
[DataRow("id:99999999999999999999")]
|
||||||
|
public void InvalidIdValueIsAnError(string text) {
|
||||||
|
AssertSyntaxError(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void QuotedIdValueIsAnError() {
|
||||||
|
AssertSyntaxError("id:\"61\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("tag:AND")]
|
||||||
|
[DataRow("tag:OR")]
|
||||||
|
[DataRow("title:AND")]
|
||||||
|
public void BareOperatorAsQualifierValueIsAnError(string text) {
|
||||||
|
AssertSyntaxError(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UnquotedQualifierValueWithColonIsAnError() {
|
||||||
|
AssertSyntaxError("tag:a:b");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow(":foo")]
|
||||||
|
[DataRow("http://x")]
|
||||||
|
[DataRow("a:")]
|
||||||
|
public void ColonAfterNonKeyIsAnError(string text) {
|
||||||
|
AssertSyntaxError(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("a\\b")]
|
||||||
|
[DataRow("\\")]
|
||||||
|
[DataRow("tag:a\\b")]
|
||||||
|
public void BackslashInBareWordIsAnError(string text) {
|
||||||
|
AssertSyntaxError(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
|
|||||||
@@ -26,12 +26,14 @@ public class SearchSqlCompilerTests {
|
|||||||
// Columns: 1 "To Do", 2 "In Progress".
|
// 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 ('To Do', '', 1, 1);");
|
||||||
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('In Progress', '', 1, 1);");
|
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('In Progress', '', 1, 1);");
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Archive', '', 1, 1);");
|
||||||
|
|
||||||
// Cards: 1 titled, 2 title-or-content matches, 3 untitled, 4 wildcard chars.
|
// 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 (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, '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 (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);");
|
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, '100% done', 'a_b test', 1, 1);");
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (3, 'ÄÖÜ Straße', '', 1, 1);");
|
||||||
|
|
||||||
// Tags: mixed case names plus one containing spaces.
|
// 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 ('Bug', '#ff0000', '');");
|
||||||
@@ -143,20 +145,27 @@ public class SearchSqlCompilerTests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void LikeWildcardsInUserTextMatchLiterally() {
|
public void PercentAndUnderscoreInUserTextMatchLiterally() {
|
||||||
using var fixture = new SearchFixture();
|
using var fixture = new SearchFixture();
|
||||||
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("100%"));
|
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("100%"));
|
||||||
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("a_b"));
|
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("a_b"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UnicodeCaseFoldingMatchesNonAscii() {
|
||||||
|
using var fixture = new SearchFixture();
|
||||||
|
|
||||||
|
// SQLite's LIKE would only fold ASCII; the ykb_fold function folds these too.
|
||||||
|
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("äöü"));
|
||||||
|
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("straße"));
|
||||||
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void CompiledPredicateUsesNamedParameters() {
|
public void CompiledPredicateUsesNamedParameters() {
|
||||||
CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("x"));
|
CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("x"));
|
||||||
|
|
||||||
StringAssert.Contains(compiled.Predicate, "$p0");
|
StringAssert.Contains(compiled.Predicate, "$p0");
|
||||||
StringAssert.Contains(compiled.Predicate, "$p1");
|
Assert.AreEqual(1, compiled.Parameters.Count);
|
||||||
Assert.AreEqual(2, compiled.Parameters.Count);
|
Assert.AreEqual("x", compiled.Parameters[0].Value);
|
||||||
Assert.AreEqual("%x%", compiled.Parameters[0].Value);
|
|
||||||
Assert.AreEqual("%x%", compiled.Parameters[1].Value);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -53,6 +53,39 @@ public class AppConfigStoreTests {
|
|||||||
Assert.AreEqual(AppConfig.CurrentFormatVersion, store.Load().Version);
|
Assert.AreEqual(AppConfig.CurrentFormatVersion, store.Load().Version);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void LoadNumericEnumValueIsRejectedAndBackedUp() {
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string path = Path.Combine(directory.FullPath, "app.json");
|
||||||
|
|
||||||
|
// Integer enum values are not accepted; the file is treated like corrupt.
|
||||||
|
File.WriteAllText(path, """{ "theme": 1 }""");
|
||||||
|
var store = new AppConfigStore(path);
|
||||||
|
|
||||||
|
AppConfig config = store.Load();
|
||||||
|
|
||||||
|
Assert.AreEqual(ThemeOption.FollowSystem, config.Theme);
|
||||||
|
Assert.IsTrue(File.Exists(path + ".bak"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void LoadUnreadableFileReturnsDefaults() {
|
||||||
|
// File sharing is only reliably enforced on Windows, so this branch is exercised there.
|
||||||
|
if (!OperatingSystem.IsWindows()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string path = Path.Combine(directory.FullPath, "app.json");
|
||||||
|
File.WriteAllText(path, """{ "version": 1 }""");
|
||||||
|
|
||||||
|
// Hold the file exclusively so the store's read fails with an I/O error.
|
||||||
|
using FileStream hold = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None);
|
||||||
|
var store = new AppConfigStore(path);
|
||||||
|
|
||||||
|
Assert.AreEqual(AppConfig.CurrentFormatVersion, store.Load().Version);
|
||||||
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void LoadReadsKebabCaseKeysAndEnumValues() {
|
public void LoadReadsKebabCaseKeysAndEnumValues() {
|
||||||
using var directory = new TempDirectory();
|
using var directory = new TempDirectory();
|
||||||
|
|||||||
@@ -41,6 +41,42 @@ public class WorkspaceSessionTests {
|
|||||||
() => WorkspaceSession.Open(directory.FullPath));
|
() => WorkspaceSession.Open(directory.FullPath));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OpenWithoutDatabaseThrowsDatabaseMissing() {
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||||
|
File.Delete(WorkspacePaths.Database(directory.FullPath));
|
||||||
|
|
||||||
|
Assert.ThrowsExactly<WorkspaceDatabaseMissingException>(
|
||||||
|
() => WorkspaceSession.Open(directory.FullPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void InitializeHoldsLockAndSeedsPreset() {
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
|
||||||
|
using WorkspaceSession session = WorkspaceSession.Initialize(directory.FullPath);
|
||||||
|
|
||||||
|
// The lock is held for the whole session, so a second initialize cannot interleave.
|
||||||
|
Assert.ThrowsExactly<WorkspaceLockException>(() => WorkspaceSession.Initialize(directory.FullPath));
|
||||||
|
|
||||||
|
// The preset columns and tags were written under the same lock.
|
||||||
|
Assert.AreEqual(3, session.Repository.GetColumns().Count);
|
||||||
|
Assert.AreEqual(8, session.Repository.GetTags().Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void InitializeExistingWorkspaceThrowsAndReleasesLock() {
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||||
|
|
||||||
|
Assert.ThrowsExactly<InvalidOperationException>(() => WorkspaceSession.Initialize(directory.FullPath));
|
||||||
|
|
||||||
|
// The failed initialize released the lock, so the workspace can still be opened.
|
||||||
|
using WorkspaceSession session = WorkspaceSession.Open(directory.FullPath);
|
||||||
|
Assert.AreEqual(directory.FullPath, session.FolderPath);
|
||||||
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void RepositoryIsUsableThroughSession() {
|
public void RepositoryIsUsableThroughSession() {
|
||||||
using var directory = new TempDirectory();
|
using var directory = new TempDirectory();
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
|
||||||
|
using YKanBan.Storage;
|
||||||
|
using YKanBan.ViewModels.ErrorPages;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.ViewModels;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tests for the open-failed page's exception-type → localized message mapping
|
||||||
|
/// and its English details. Mutates the global <see cref="Resources.Culture"/>,
|
||||||
|
/// therefore marked do-not-parallelize.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
[DoNotParallelize]
|
||||||
|
public class OpenFailedPageViewModelTests {
|
||||||
|
private const string Folder = "/work/repo";
|
||||||
|
|
||||||
|
private static void WithCulture(string language, Action action) {
|
||||||
|
CultureInfo? original = Resources.Culture;
|
||||||
|
try {
|
||||||
|
Resources.Culture = new CultureInfo(language);
|
||||||
|
action();
|
||||||
|
} finally {
|
||||||
|
Resources.Culture = original;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Expected(string pattern, params object[] arguments) =>
|
||||||
|
string.Format(Resources.Culture, pattern, [Folder, .. arguments]);
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("en")]
|
||||||
|
[DataRow("zh-Hans")]
|
||||||
|
public void EachRecognizedExceptionTypeHasItsOwnMessage(string language) {
|
||||||
|
WithCulture(language, () => {
|
||||||
|
Assert.AreEqual(
|
||||||
|
Expected(Resources.Error_OpenFailed_SchemaTooNew, 3L, 1),
|
||||||
|
OpenFailedPageViewModel.BuildMessage(Folder, new SchemaVersionException(3, 1)));
|
||||||
|
Assert.AreEqual(
|
||||||
|
Expected(Resources.Error_OpenFailed_DatabaseMissing),
|
||||||
|
OpenFailedPageViewModel.BuildMessage(Folder, new WorkspaceDatabaseMissingException("/work/repo/.ykanban/ykanban.db")));
|
||||||
|
Assert.AreEqual(
|
||||||
|
Expected(Resources.Error_OpenFailed_Database),
|
||||||
|
OpenFailedPageViewModel.BuildMessage(Folder, new SqliteException("file is not a database", 26)));
|
||||||
|
Assert.AreEqual(
|
||||||
|
Expected(Resources.Error_OpenFailed_AccessDenied),
|
||||||
|
OpenFailedPageViewModel.BuildMessage(Folder, new UnauthorizedAccessException()));
|
||||||
|
Assert.AreEqual(
|
||||||
|
Expected(Resources.Error_OpenFailed_Io),
|
||||||
|
OpenFailedPageViewModel.BuildMessage(Folder, new IOException()));
|
||||||
|
Assert.AreEqual(
|
||||||
|
Expected(Resources.Error_OpenFailed_Io),
|
||||||
|
OpenFailedPageViewModel.BuildMessage(Folder, new DirectoryNotFoundException()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UnrecognizedExceptionGetsTheGenericMessage() {
|
||||||
|
WithCulture("en", () => {
|
||||||
|
Assert.AreEqual(
|
||||||
|
Expected(Resources.Error_OpenFailed_Generic),
|
||||||
|
OpenFailedPageViewModel.BuildMessage(Folder, new InvalidOperationException()));
|
||||||
|
Assert.AreEqual(
|
||||||
|
Expected(Resources.Error_OpenFailed_Generic),
|
||||||
|
OpenFailedPageViewModel.BuildMessage(Folder, new WorkspaceDirectoryMissingException(Folder)));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DetailsCarryTheEnglishExceptionTextInAnyLanguage() {
|
||||||
|
WithCulture("zh-Hans", () => {
|
||||||
|
var exception = new SchemaVersionException(3, 1);
|
||||||
|
var page = new OpenFailedPageViewModel(Folder, exception);
|
||||||
|
|
||||||
|
Assert.AreEqual(Folder, page.FolderPath);
|
||||||
|
StringAssert.Contains(page.Details, typeof(SchemaVersionException).FullName!);
|
||||||
|
StringAssert.Contains(page.Details, exception.Message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<IsPackable>false</IsPackable>
|
<IsPackable>false</IsPackable>
|
||||||
|
|||||||
+14
-7
@@ -28,6 +28,12 @@ public partial class App : Application {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static string StartupLanguage { get; private set; } = AppConfig.DefaultLanguage;
|
public static string StartupLanguage { get; private set; } = AppConfig.DefaultLanguage;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the flow direction of the startup culture. FlowDirection does not
|
||||||
|
/// inherit across windows, so the main window and every modal window apply it.
|
||||||
|
/// </summary>
|
||||||
|
public static FlowDirection UiFlowDirection { get; private set; } = FlowDirection.LeftToRight;
|
||||||
|
|
||||||
public override void Initialize() {
|
public override void Initialize() {
|
||||||
AvaloniaXamlLoader.Load(this);
|
AvaloniaXamlLoader.Load(this);
|
||||||
}
|
}
|
||||||
@@ -42,18 +48,19 @@ public partial class App : Application {
|
|||||||
CultureInfo culture = ResolveCulture(Services.Config.Language);
|
CultureInfo culture = ResolveCulture(Services.Config.Language);
|
||||||
StartupLanguage = Services.Config.Language;
|
StartupLanguage = Services.Config.Language;
|
||||||
Resx.Culture = culture;
|
Resx.Culture = culture;
|
||||||
|
|
||||||
|
// RTL detection drives the flow direction of every window; the two
|
||||||
|
// supported languages are LTR, but the infrastructure stays in
|
||||||
|
// place for future languages.
|
||||||
|
UiFlowDirection = culture.TextInfo.IsRightToLeft
|
||||||
|
? FlowDirection.RightToLeft
|
||||||
|
: FlowDirection.LeftToRight;
|
||||||
ApplyTheme(Services.Config.Theme);
|
ApplyTheme(Services.Config.Theme);
|
||||||
|
|
||||||
var viewModel = new MainWindowViewModel(Services, desktop.Args ?? []);
|
var viewModel = new MainWindowViewModel(Services, desktop.Args ?? []);
|
||||||
desktop.MainWindow = new MainWindow {
|
desktop.MainWindow = new MainWindow {
|
||||||
DataContext = viewModel,
|
DataContext = viewModel,
|
||||||
|
FlowDirection = UiFlowDirection,
|
||||||
// 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,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -265,12 +265,6 @@
|
|||||||
<data name="Error_Argument_Usage" xml:space="preserve">
|
<data name="Error_Argument_Usage" xml:space="preserve">
|
||||||
<value>Usage: ykanban <path></value>
|
<value>Usage: ykanban <path></value>
|
||||||
</data>
|
</data>
|
||||||
<data name="Error_DirectoryMissing_Title" xml:space="preserve">
|
|
||||||
<value>Folder not found</value>
|
|
||||||
</data>
|
|
||||||
<data name="Error_DirectoryMissing_Message" xml:space="preserve">
|
|
||||||
<value>The folder does not exist: {0}</value>
|
|
||||||
</data>
|
|
||||||
<data name="Error_NotInitialized_Title" xml:space="preserve">
|
<data name="Error_NotInitialized_Title" xml:space="preserve">
|
||||||
<value>No workspace here</value>
|
<value>No workspace here</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -415,9 +409,6 @@
|
|||||||
<data name="Export_TimePattern" xml:space="preserve">
|
<data name="Export_TimePattern" xml:space="preserve">
|
||||||
<value>yyyy-MM-dd HH:mm:ss</value>
|
<value>yyyy-MM-dd HH:mm:ss</value>
|
||||||
</data>
|
</data>
|
||||||
<data name="Export_CardTimePattern" xml:space="preserve">
|
|
||||||
<value>yyyy-MM-dd HH:mm</value>
|
|
||||||
</data>
|
|
||||||
<data name="Export_WorkspaceHeading" xml:space="preserve">
|
<data name="Export_WorkspaceHeading" xml:space="preserve">
|
||||||
<value># {0}</value>
|
<value># {0}</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -445,4 +436,28 @@
|
|||||||
<data name="Export_Done_Message" xml:space="preserve">
|
<data name="Export_Done_Message" xml:space="preserve">
|
||||||
<value>Exported to: {0}</value>
|
<value>Exported to: {0}</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Error_OpenFailed_Title" xml:space="preserve">
|
||||||
|
<value>Cannot open workspace</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_SchemaTooNew" xml:space="preserve">
|
||||||
|
<value>The workspace database was created by a newer version of YKanBan (schema version {1}; this version supports up to {2}): {0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_Database" xml:space="preserve">
|
||||||
|
<value>The workspace database cannot be opened or is damaged: {0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_DatabaseMissing" xml:space="preserve">
|
||||||
|
<value>The workspace database (.ykanban/ykanban.db) is missing. Restore it from a backup together with its -wal and -shm files, or delete the .ykanban folder to initialize the workspace again: {0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_AccessDenied" xml:space="preserve">
|
||||||
|
<value>Access to the workspace was denied: {0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_Io" xml:space="preserve">
|
||||||
|
<value>A file system error occurred while opening the workspace: {0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_Generic" xml:space="preserve">
|
||||||
|
<value>An unexpected error occurred while opening the workspace: {0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_Details" xml:space="preserve">
|
||||||
|
<value>Details</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -265,12 +265,6 @@
|
|||||||
<data name="Error_Argument_Usage" xml:space="preserve">
|
<data name="Error_Argument_Usage" xml:space="preserve">
|
||||||
<value>用法:ykanban <路径></value>
|
<value>用法:ykanban <路径></value>
|
||||||
</data>
|
</data>
|
||||||
<data name="Error_DirectoryMissing_Title" xml:space="preserve">
|
|
||||||
<value>目录不存在</value>
|
|
||||||
</data>
|
|
||||||
<data name="Error_DirectoryMissing_Message" xml:space="preserve">
|
|
||||||
<value>目录不存在:{0}</value>
|
|
||||||
</data>
|
|
||||||
<data name="Error_NotInitialized_Title" xml:space="preserve">
|
<data name="Error_NotInitialized_Title" xml:space="preserve">
|
||||||
<value>尚未初始化</value>
|
<value>尚未初始化</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -415,9 +409,6 @@
|
|||||||
<data name="Export_TimePattern" xml:space="preserve">
|
<data name="Export_TimePattern" xml:space="preserve">
|
||||||
<value>yyyy年M月d日 HH:mm</value>
|
<value>yyyy年M月d日 HH:mm</value>
|
||||||
</data>
|
</data>
|
||||||
<data name="Export_CardTimePattern" xml:space="preserve">
|
|
||||||
<value>yyyy年M月d日 HH:mm</value>
|
|
||||||
</data>
|
|
||||||
<data name="Export_WorkspaceHeading" xml:space="preserve">
|
<data name="Export_WorkspaceHeading" xml:space="preserve">
|
||||||
<value># {0}</value>
|
<value># {0}</value>
|
||||||
</data>
|
</data>
|
||||||
@@ -445,4 +436,28 @@
|
|||||||
<data name="Export_Done_Message" xml:space="preserve">
|
<data name="Export_Done_Message" xml:space="preserve">
|
||||||
<value>已导出到:{0}</value>
|
<value>已导出到:{0}</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Error_OpenFailed_Title" xml:space="preserve">
|
||||||
|
<value>无法打开工作区</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_SchemaTooNew" xml:space="preserve">
|
||||||
|
<value>工作区数据库由更新版本的 YKanBan 创建(schema 版本 {1},当前版本最高支持 {2}):{0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_Database" xml:space="preserve">
|
||||||
|
<value>工作区数据库无法打开或已损坏:{0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_DatabaseMissing" xml:space="preserve">
|
||||||
|
<value>工作区数据库(.ykanban/ykanban.db)不存在。请从备份恢复(连同 -wal、-shm 文件),或删除 .ykanban 文件夹后重新初始化:{0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_AccessDenied" xml:space="preserve">
|
||||||
|
<value>没有访问该工作区的权限:{0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_Io" xml:space="preserve">
|
||||||
|
<value>打开工作区时发生文件系统错误:{0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_Generic" xml:space="preserve">
|
||||||
|
<value>打开工作区时发生意外错误:{0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Error_OpenFailed_Details" xml:space="preserve">
|
||||||
|
<value>详细信息</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 172 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
@@ -7,10 +7,14 @@ namespace YKanBan.Export;
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Generates the human-readable Markdown snapshot of a whole board. All
|
/// Generates the human-readable Markdown snapshot of a whole board. All
|
||||||
/// template text and time formats come from the ResX resources in the current
|
/// template text and the one time format come from the ResX resources in the
|
||||||
/// UI language; the export timestamp uses the per-language pattern, card
|
/// current UI language; every timestamp (export time and card created/modified
|
||||||
/// timestamps use the shared minute-precision pattern. The output is meant for
|
/// times) uses that per-language pattern. The document uses the platform's
|
||||||
/// reading only — there is no re-import.
|
/// newline. Card bodies and column descriptions are emitted verbatim; column and
|
||||||
|
/// card titles are collapsed to one line; tag names become inline code with a
|
||||||
|
/// long enough backtick fence; tag table cells escape '\' and '|' and turn line
|
||||||
|
/// breaks into <br>. The output is meant for reading only — there is no
|
||||||
|
/// re-import.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class MarkdownExporter {
|
public static class MarkdownExporter {
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -33,17 +37,19 @@ public static class MarkdownExporter {
|
|||||||
var builder = new StringBuilder();
|
var builder = new StringBuilder();
|
||||||
|
|
||||||
// Header: workspace name and the export timestamp in the UI language's format.
|
// 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_WorkspaceHeading, SingleLine(workspaceName)));
|
||||||
builder.AppendLine(string.Format(
|
builder.AppendLine(string.Format(
|
||||||
culture, Resources.Export_ExportedAtLine, exportedAt.ToString(Resources.Export_TimePattern, culture)));
|
culture, Resources.Export_ExportedAtLine, exportedAt.ToString(Resources.Export_TimePattern, culture)));
|
||||||
builder.AppendLine();
|
builder.AppendLine();
|
||||||
|
|
||||||
// Board body: every column in id order, empty ones included.
|
// Board body: every column in id order, empty ones included; independent of
|
||||||
foreach (ColumnModel column in columns) {
|
// the board's search filter and card sort option.
|
||||||
IReadOnlyList<CardModel> cardsInColumn = cards.Where(card => card.ColumnId == column.Id).ToArray();
|
foreach (ColumnModel column in columns.OrderBy(column => column.Id)) {
|
||||||
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, column.Title, cardsInColumn.Count));
|
IReadOnlyList<CardModel> cardsInColumn =
|
||||||
|
cards.Where(card => card.ColumnId == column.Id).OrderBy(card => card.Id).ToArray();
|
||||||
|
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, SingleLine(column.Title), cardsInColumn.Count));
|
||||||
if (column.Description.Length > 0) {
|
if (column.Description.Length > 0) {
|
||||||
builder.AppendLine(SingleLine(column.Description));
|
builder.AppendLine(column.Description);
|
||||||
}
|
}
|
||||||
builder.AppendLine();
|
builder.AppendLine();
|
||||||
|
|
||||||
@@ -58,16 +64,32 @@ public static class MarkdownExporter {
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Builds the default export file name in the UI language, for example
|
/// Builds the default export file name in the UI language, for example
|
||||||
/// "MyRepo-export-20260930-142537.md".
|
/// "MyRepo-export-20260930-142537.md". Characters that are not allowed in a
|
||||||
|
/// file name on any supported platform are dropped from the workspace name
|
||||||
|
/// (a workspace at a drive root is named "D:\"); a name left empty falls
|
||||||
|
/// back to the application name.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="workspaceName">Workspace display name.</param>
|
/// <param name="workspaceName">Workspace display name.</param>
|
||||||
/// <param name="exportedAt">Export moment.</param>
|
/// <param name="exportedAt">Export moment.</param>
|
||||||
/// <returns>The file name.</returns>
|
/// <returns>The file name.</returns>
|
||||||
public static string BuildFileName(string workspaceName, DateTimeOffset exportedAt) {
|
public static string BuildFileName(string workspaceName, DateTimeOffset exportedAt) {
|
||||||
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
|
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
|
||||||
return string.Format(culture, Resources.Export_FileNamePattern, workspaceName, exportedAt);
|
string safeName = new(workspaceName.Where(character => !IsInvalidFileNameCharacter(character)).ToArray());
|
||||||
|
if (safeName.Length == 0) {
|
||||||
|
safeName = Resources.App_Name;
|
||||||
|
}
|
||||||
|
return string.Format(culture, Resources.Export_FileNamePattern, safeName, exportedAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tells whether a character is invalid in a file name on Windows, Linux or
|
||||||
|
/// macOS; the Windows set is the widest, so the result is the same on every platform.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="character">The character to test.</param>
|
||||||
|
/// <returns><see langword="true"/> when the character must not appear in a file name.</returns>
|
||||||
|
private static bool IsInvalidFileNameCharacter(char character) =>
|
||||||
|
character < ' ' || character is '<' or '>' or ':' or '"' or '/' or '\\' or '|' or '?' or '*';
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Appends one card block: heading, body, tags line and timestamps line.
|
/// Appends one card block: heading, body, tags line and timestamps line.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -85,12 +107,12 @@ public static class MarkdownExporter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (card.Tags.Count > 0) {
|
if (card.Tags.Count > 0) {
|
||||||
string names = string.Join(" ", card.Tags.Select(tag => $"`{tag.Name}`"));
|
string names = string.Join(" ", card.Tags.Select(tag => InlineCode(tag.Name)));
|
||||||
builder.AppendLine(string.Format(culture, Resources.Export_TagsLine, names));
|
builder.AppendLine(string.Format(culture, Resources.Export_TagsLine, names));
|
||||||
}
|
}
|
||||||
|
|
||||||
string created = ToLocalTime(card.CreatedAt).ToString(Resources.Export_CardTimePattern, culture);
|
string created = ToLocalTime(card.CreatedAt).ToString(Resources.Export_TimePattern, culture);
|
||||||
string updated = ToLocalTime(card.UpdatedAt).ToString(Resources.Export_CardTimePattern, culture);
|
string updated = ToLocalTime(card.UpdatedAt).ToString(Resources.Export_TimePattern, culture);
|
||||||
builder.AppendLine(string.Format(culture, Resources.Export_CreatedModifiedLine, created, updated));
|
builder.AppendLine(string.Format(culture, Resources.Export_CreatedModifiedLine, created, updated));
|
||||||
builder.AppendLine();
|
builder.AppendLine();
|
||||||
}
|
}
|
||||||
@@ -115,11 +137,34 @@ public static class MarkdownExporter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Formats a table cell: single line with escaped pipe characters.
|
/// Formats a table cell: escaped backslashes and pipe characters, line breaks as <br>.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="text">The raw cell text.</param>
|
/// <param name="text">The raw cell text.</param>
|
||||||
/// <returns>The escaped single-line text.</returns>
|
/// <returns>The escaped single-line text.</returns>
|
||||||
private static string Cell(string text) => SingleLine(text).Replace("|", "\\|");
|
private static string Cell(string text) =>
|
||||||
|
// Backslashes first: the table splitter reads "\\" as an escaped backslash, so the
|
||||||
|
// '|' after a literal backslash would otherwise end the cell.
|
||||||
|
text.Replace("\\", "\\\\").Replace("|", "\\|").Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Renders text as an inline code span whose backtick fence is one longer than
|
||||||
|
/// the longest backtick run inside, padded with spaces when the text starts or
|
||||||
|
/// ends with a backtick.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text">The raw text.</param>
|
||||||
|
/// <returns>The inline code span.</returns>
|
||||||
|
private static string InlineCode(string text) {
|
||||||
|
int longestRun = 0;
|
||||||
|
int run = 0;
|
||||||
|
foreach (char character in text) {
|
||||||
|
run = character == '`' ? run + 1 : 0;
|
||||||
|
longestRun = Math.Max(longestRun, run);
|
||||||
|
}
|
||||||
|
|
||||||
|
string fence = new('`', longestRun + 1);
|
||||||
|
string padding = text.StartsWith('`') || text.EndsWith('`') ? " " : string.Empty;
|
||||||
|
return fence + padding + text + padding + fence;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Collapses line breaks so the text stays on one Markdown line.
|
/// Collapses line breaks so the text stays on one Markdown line.
|
||||||
|
|||||||
@@ -4,9 +4,11 @@ namespace YKanBan.Launching;
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Parses raw command-line arguments. The only accepted form is a single,
|
/// Parses raw command-line arguments. The only accepted form is a single,
|
||||||
/// non-blank workspace path (<c>ykanban <path></c>); zero arguments,
|
/// non-blank, existing workspace folder (<c>ykanban <path></c>); zero
|
||||||
/// more than one argument, or a blank argument is rejected as an argument
|
/// arguments, more than one argument, a blank argument, an argument starting
|
||||||
/// error. The path itself is not checked for existence here.
|
/// with <c>-</c> (any option form, <c>--help</c> included), a malformed path or
|
||||||
|
/// a path that is not an existing folder is rejected as an argument error. A
|
||||||
|
/// relative path is resolved against the process's current directory.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class LaunchArguments {
|
public static class LaunchArguments {
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -14,15 +16,28 @@ public static class LaunchArguments {
|
|||||||
/// <c>ykanban <path></c> contract.
|
/// <c>ykanban <path></c> contract.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="arguments">The raw arguments, excluding the executable name.</param>
|
/// <param name="arguments">The raw arguments, excluding the executable name.</param>
|
||||||
/// <param name="folderPath">The parsed workspace path on success, otherwise <see langword="null"/>.</param>
|
/// <param name="folderPath">The absolute, existing workspace folder on success, otherwise <see langword="null"/>.</param>
|
||||||
/// <returns><see langword="true"/> when exactly one non-blank path was supplied.</returns>
|
/// <returns><see langword="true"/> when exactly one usable path was supplied.</returns>
|
||||||
public static bool TryParse(IReadOnlyList<string> arguments, [NotNullWhen(true)] out string? folderPath) {
|
public static bool TryParse(IReadOnlyList<string> arguments, [NotNullWhen(true)] out string? folderPath) {
|
||||||
if (arguments.Count == 1 && !string.IsNullOrWhiteSpace(arguments[0])) {
|
folderPath = null;
|
||||||
folderPath = arguments[0];
|
if (arguments.Count != 1 || string.IsNullOrWhiteSpace(arguments[0]) || arguments[0].StartsWith('-')) {
|
||||||
return true;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
folderPath = null;
|
string fullPath;
|
||||||
return false;
|
try {
|
||||||
|
fullPath = Path.GetFullPath(arguments[0]);
|
||||||
|
} catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) {
|
||||||
|
// A path the OS cannot even represent is a bad argument, not a missing folder.
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Existence is checked here so every caller gets an already validated folder.
|
||||||
|
if (!Directory.Exists(fullPath)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
folderPath = fullPath;
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -34,21 +34,20 @@ public abstract record SearchToken {
|
|||||||
/// quoted phrases and parentheses; whitespace only separates tokens.
|
/// quoted phrases and parentheses; whitespace only separates tokens.
|
||||||
///
|
///
|
||||||
/// The lexer is strict: inside a phrase only <c>\"</c> and <c>\\</c> are valid
|
/// The lexer is strict: inside a phrase only <c>\"</c> and <c>\\</c> are valid
|
||||||
/// escapes, a bare backslash or an unknown escape is rejected, and an
|
/// escapes, a bare backslash or an unknown escape is rejected, a backslash in a
|
||||||
/// unterminated phrase is rejected. Any input not covered by the token rules
|
/// bare word is rejected, and an unterminated phrase is rejected. A phrase
|
||||||
/// is rejected rather than silently ignored.
|
/// must not be empty and must be separated from neighbouring words and
|
||||||
|
/// phrases by whitespace or a parenthesis, except as a qualifier value glued to
|
||||||
|
/// its key (<c>tag:"a b"</c>). Any input not covered by the token rules is
|
||||||
|
/// rejected rather than silently ignored.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class SearchLexer {
|
public static class SearchLexer {
|
||||||
/// <summary>
|
/// <summary>A valid phrase escape sequence: <c>\"</c> or <c>\\</c>.</summary>
|
||||||
/// A valid phrase escape sequence: <c>\"</c> or <c>\\</c>.
|
|
||||||
/// </summary>
|
|
||||||
private static readonly Parser<char, char> PhraseEscape =
|
private static readonly Parser<char, char> PhraseEscape =
|
||||||
Parser.Try(Parser.String("\\\"").Select(_ => '"'))
|
Parser.Try(Parser.String("\\\"").Select(_ => '"'))
|
||||||
.Or(Parser.String("\\\\").Select(_ => '\\'));
|
.Or(Parser.String("\\\\").Select(_ => '\\'));
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>One phrase character: an escape or any character except a quote or backslash.</summary>
|
||||||
/// One phrase character: an escape or any character except a quote or backslash.
|
|
||||||
/// </summary>
|
|
||||||
private static readonly Parser<char, char> PhraseCharacter =
|
private static readonly Parser<char, char> PhraseCharacter =
|
||||||
PhraseEscape.Or(Parser<char>.Token(character => character != '"' && character != '\\'));
|
PhraseEscape.Or(Parser<char>.Token(character => character != '"' && character != '\\'));
|
||||||
|
|
||||||
@@ -64,39 +63,99 @@ public static class SearchLexer {
|
|||||||
private static readonly Parser<char, SearchToken> CloseParenParser =
|
private static readonly Parser<char, SearchToken> CloseParenParser =
|
||||||
Parser.Char(')').Select(_ => (SearchToken)new SearchToken.CloseParen());
|
Parser.Char(')').Select(_ => (SearchToken)new SearchToken.CloseParen());
|
||||||
|
|
||||||
|
// ':' stays inside the word token (the parser splits qualifiers); a backslash
|
||||||
|
// is not a word character, so a bare one is left over and rejected by End.
|
||||||
private static readonly Parser<char, SearchToken> WordParser =
|
private static readonly Parser<char, SearchToken> WordParser =
|
||||||
Parser<char>.Token(character =>
|
Parser<char>.Token(character =>
|
||||||
!char.IsWhiteSpace(character) && character != '(' && character != ')' && character != '"')
|
!char.IsWhiteSpace(character) && character != '(' && character != ')' && character != '"' && character != '\\')
|
||||||
.AtLeastOnce()
|
.AtLeastOnce()
|
||||||
.Select(chars => (SearchToken)new SearchToken.Word(new string(chars.ToArray())));
|
.Select(chars => (SearchToken)new SearchToken.Word(new string(chars.ToArray())));
|
||||||
|
|
||||||
private static readonly Parser<char, SearchToken> TokenParser =
|
// Each token with its source span, so adjacency can be checked afterwards.
|
||||||
|
private static readonly Parser<char, PositionedToken> TokenParser =
|
||||||
Parser.SkipWhitespaces.Then(
|
Parser.SkipWhitespaces.Then(
|
||||||
PhraseParser
|
from start in Parser<char>.CurrentOffset
|
||||||
|
from token in PhraseParser
|
||||||
.Or(OpenParenParser)
|
.Or(OpenParenParser)
|
||||||
.Or(CloseParenParser)
|
.Or(CloseParenParser)
|
||||||
.Or(WordParser));
|
.Or(WordParser)
|
||||||
|
from end in Parser<char>.CurrentOffset
|
||||||
|
select new PositionedToken(token, start, end));
|
||||||
|
|
||||||
// Try(...) keeps a failed token non-consuming so Many stops gracefully; End
|
// Try(...) keeps a failed token non-consuming so Many stops gracefully; End
|
||||||
// then rejects any leftover input, which turns dangling quotes or invalid
|
// then rejects any leftover input, which turns dangling quotes or invalid
|
||||||
// escapes into hard failures instead of silently dropped text.
|
// escapes into hard failures instead of silently dropped text.
|
||||||
private static readonly Parser<char, IReadOnlyList<SearchToken>> Lexer =
|
private static readonly Parser<char, IReadOnlyList<PositionedToken>> Lexer =
|
||||||
Parser.Try(TokenParser).Many()
|
Parser.Try(TokenParser).Many()
|
||||||
.Before(Parser.SkipWhitespaces)
|
.Before(Parser.SkipWhitespaces)
|
||||||
.Before(Parser<char>.End)
|
.Before(Parser<char>.End)
|
||||||
.Select(tokens => (IReadOnlyList<SearchToken>)tokens.ToList());
|
.Select(tokens => (IReadOnlyList<PositionedToken>)tokens.ToList());
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Tokenizes the search text.
|
/// Tokenizes the search text.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="input">The raw search text.</param>
|
/// <param name="input">The raw search text.</param>
|
||||||
/// <returns>The token stream.</returns>
|
/// <returns>The token stream.</returns>
|
||||||
/// <exception cref="SearchSyntaxException">The text contains an invalid escape or an unterminated phrase.</exception>
|
/// <exception cref="SearchSyntaxException">
|
||||||
|
/// The text contains an invalid escape, an unterminated or empty phrase, a
|
||||||
|
/// phrase glued to other text, or whitespace between a qualifier and its phrase value.
|
||||||
|
/// </exception>
|
||||||
public static IReadOnlyList<SearchToken> Tokenize(string input) {
|
public static IReadOnlyList<SearchToken> Tokenize(string input) {
|
||||||
|
IReadOnlyList<PositionedToken> tokens;
|
||||||
try {
|
try {
|
||||||
return Lexer.ParseOrThrow(input);
|
tokens = Lexer.ParseOrThrow(input);
|
||||||
} catch (ParseException exception) {
|
} catch (ParseException exception) {
|
||||||
throw new SearchSyntaxException(exception.Message, exception);
|
throw new SearchSyntaxException(exception.Message, exception);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
EnsurePhrasesAreDelimited(tokens);
|
||||||
|
return tokens.Select(positioned => positioned.Token).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Rejects the phrase placements the grammar does not allow but the token
|
||||||
|
/// rules alone would accept: an empty phrase, a phrase touching a word or
|
||||||
|
/// another phrase (<c>a"b"</c>, <c>"a"b</c>, <c>"a""b"</c>), and whitespace
|
||||||
|
/// between <c>key:</c> and its phrase value (<c>tag: "x"</c>). The only
|
||||||
|
/// legal contact is <c>key:"value"</c>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="tokens">The positioned token stream.</param>
|
||||||
|
/// <exception cref="SearchSyntaxException">A phrase is misplaced.</exception>
|
||||||
|
private static void EnsurePhrasesAreDelimited(IReadOnlyList<PositionedToken> tokens) {
|
||||||
|
for (int index = 0; index < tokens.Count; index++) {
|
||||||
|
if (tokens[index].Token is SearchToken.Phrase { Text.Length: 0 }) {
|
||||||
|
throw new SearchSyntaxException("Empty phrase \"\" is not allowed.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (index == 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
PositionedToken previous = tokens[index - 1];
|
||||||
|
PositionedToken current = tokens[index];
|
||||||
|
bool qualifierValue = previous.Token is SearchToken.Word word && word.Text.EndsWith(':')
|
||||||
|
&& current.Token is SearchToken.Phrase;
|
||||||
|
bool touching = previous.End == current.Start;
|
||||||
|
|
||||||
|
if (qualifierValue && !touching) {
|
||||||
|
throw new SearchSyntaxException(
|
||||||
|
$"Qualifier '{((SearchToken.Word)previous.Token).Text}' must be followed directly by its value, without whitespace.");
|
||||||
|
}
|
||||||
|
|
||||||
|
bool phraseInvolved = previous.Token is SearchToken.Phrase || current.Token is SearchToken.Phrase;
|
||||||
|
bool parenInvolved = previous.Token is SearchToken.OpenParen or SearchToken.CloseParen
|
||||||
|
|| current.Token is SearchToken.OpenParen or SearchToken.CloseParen;
|
||||||
|
if (touching && phraseInvolved && !parenInvolved && !qualifierValue) {
|
||||||
|
throw new SearchSyntaxException("A phrase must be separated from adjacent text by whitespace.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A token with its source span.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="Token">The token.</param>
|
||||||
|
/// <param name="Start">Offset of the first character.</param>
|
||||||
|
/// <param name="End">Offset just past the last character.</param>
|
||||||
|
private sealed record PositionedToken(SearchToken Token, int Start, int End);
|
||||||
}
|
}
|
||||||
@@ -7,8 +7,10 @@ namespace YKanBan.Search;
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Parses the search grammar with Pidgin, strictly: any malformed input
|
/// Parses the search grammar with Pidgin, strictly: any malformed input
|
||||||
/// (unbalanced parentheses, dangling or consecutive operators, unterminated
|
/// (unbalanced parentheses, dangling or consecutive operators, unterminated
|
||||||
/// phrases, invalid escapes, qualifier keys without a value or with an
|
/// phrases, invalid escapes, a backslash in a bare word, unknown qualifier
|
||||||
/// unknown/non-numeric id value) raises <see cref="SearchSyntaxException"/>.
|
/// keys, qualifiers without a value, unquoted values containing ':' or equal
|
||||||
|
/// to AND/OR, and id values that are not an unquoted positive integer with an
|
||||||
|
/// optional '#') raises <see cref="SearchSyntaxException"/>.
|
||||||
///
|
///
|
||||||
/// Only uppercase AND/OR are operators (lowercase ones are plain words); AND —
|
/// Only uppercase AND/OR are operators (lowercase ones are plain words); AND —
|
||||||
/// explicit or by adjacency — binds tighter than OR; parentheses group. Blank
|
/// explicit or by adjacency — binds tighter than OR; parentheses group. Blank
|
||||||
@@ -16,9 +18,7 @@ namespace YKanBan.Search;
|
|||||||
/// qualifier keys are fixed English grammar and are never localized.
|
/// qualifier keys are fixed English grammar and are never localized.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class SearchQueryParser {
|
public static class SearchQueryParser {
|
||||||
/// <summary>
|
/// <summary>The recognized qualifier keys; add new entries here to extend the grammar.</summary>
|
||||||
/// The recognized qualifier keys; add new entries here to extend the grammar.
|
|
||||||
/// </summary>
|
|
||||||
private static readonly (string Key, QualifierKind Kind)[] QualifierTable =
|
private static readonly (string Key, QualifierKind Kind)[] QualifierTable =
|
||||||
[
|
[
|
||||||
("tag", QualifierKind.Tag),
|
("tag", QualifierKind.Tag),
|
||||||
@@ -42,16 +42,12 @@ public static class SearchQueryParser {
|
|||||||
private static readonly Parser<SearchToken, SearchToken> CloseParen =
|
private static readonly Parser<SearchToken, SearchToken> CloseParen =
|
||||||
Parser<SearchToken>.Token(token => token is SearchToken.CloseParen);
|
Parser<SearchToken>.Token(token => token is SearchToken.CloseParen);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>The text of a phrase token.</summary>
|
||||||
/// The text of a phrase token.
|
|
||||||
/// </summary>
|
|
||||||
private static readonly Parser<SearchToken, string> PhraseText =
|
private static readonly Parser<SearchToken, string> PhraseText =
|
||||||
Parser<SearchToken>.Token(token => token is SearchToken.Phrase)
|
Parser<SearchToken>.Token(token => token is SearchToken.Phrase)
|
||||||
.Select(token => ((SearchToken.Phrase)token).Text);
|
.Select(token => ((SearchToken.Phrase)token).Text);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>The text of a word token, operator keywords excluded (they never start an operand).</summary>
|
||||||
/// The text of a word token, operator keywords excluded (they never start an operand).
|
|
||||||
/// </summary>
|
|
||||||
private static readonly Parser<SearchToken, string> NonKeywordWord =
|
private static readonly Parser<SearchToken, string> NonKeywordWord =
|
||||||
Parser<SearchToken>.Token(token => token is SearchToken.Word word && word.Text != "AND" && word.Text != "OR")
|
Parser<SearchToken>.Token(token => token is SearchToken.Word word && word.Text != "AND" && word.Text != "OR")
|
||||||
.Select(token => ((SearchToken.Word)token).Text);
|
.Select(token => ((SearchToken.Word)token).Text);
|
||||||
@@ -96,9 +92,7 @@ public static class SearchQueryParser {
|
|||||||
private static readonly Parser<SearchToken, SearchNode> Query =
|
private static readonly Parser<SearchToken, SearchNode> Query =
|
||||||
OrExpr.Before(Parser<SearchToken>.End);
|
OrExpr.Before(Parser<SearchToken>.End);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>Defers the OrExpr field read to parse time (recursion cycle breaker).</summary>
|
||||||
/// Defers the OrExpr field read to parse time (recursion cycle breaker).
|
|
||||||
/// </summary>
|
|
||||||
/// <returns>The OR-expression parser.</returns>
|
/// <returns>The OR-expression parser.</returns>
|
||||||
private static Parser<SearchToken, SearchNode> OrExprDeferred() => OrExpr;
|
private static Parser<SearchToken, SearchNode> OrExprDeferred() => OrExpr;
|
||||||
|
|
||||||
@@ -115,6 +109,11 @@ public static class SearchQueryParser {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// YYC MARK: the expression is deliberately not capped by parenthesis
|
||||||
|
// depth or atom count. The app is local-only with no untrusted search
|
||||||
|
// input, so there is no attack surface; a pathologically deep or long
|
||||||
|
// expression can still overflow the parser stack or exceed SQLite's
|
||||||
|
// expression nesting limit, which is accepted here.
|
||||||
try {
|
try {
|
||||||
List<SearchToken> tokens = SearchLexer.Tokenize(text).ToList();
|
List<SearchToken> tokens = SearchLexer.Tokenize(text).ToList();
|
||||||
return Query.ParseOrThrow(tokens);
|
return Query.ParseOrThrow(tokens);
|
||||||
@@ -133,52 +132,77 @@ public static class SearchQueryParser {
|
|||||||
/// <returns>The parser producing the operand node.</returns>
|
/// <returns>The parser producing the operand node.</returns>
|
||||||
private static Parser<SearchToken, SearchNode> QualifierFrom(string word) {
|
private static Parser<SearchToken, SearchNode> QualifierFrom(string word) {
|
||||||
int colonIndex = word.IndexOf(':');
|
int colonIndex = word.IndexOf(':');
|
||||||
|
if (colonIndex < 0) {
|
||||||
// Only a leading run of letters/digits/underscores before ':' can be a qualifier key.
|
|
||||||
if (colonIndex <= 0 || !IsQualifierKeyCandidate(word.AsSpan(0, colonIndex))) {
|
|
||||||
return Parser<SearchToken>.Return<SearchNode>(new SearchNode.FreeText(word));
|
return Parser<SearchToken>.Return<SearchNode>(new SearchNode.FreeText(word));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Any ':' in a bare word makes it a qualifier, so the text before it must be a known key.
|
||||||
string key = word[..colonIndex];
|
string key = word[..colonIndex];
|
||||||
string value = word[(colonIndex + 1)..];
|
string value = word[(colonIndex + 1)..];
|
||||||
|
|
||||||
if (!TryLookupQualifier(key, out QualifierKind kind)) {
|
if (!TryLookupQualifier(key, out QualifierKind kind)) {
|
||||||
return Parser<SearchToken>.Fail<SearchNode>($"Unknown qualifier key '{key}'.");
|
return Parser<SearchToken>.Fail<SearchNode>($"Unknown qualifier key '{key}'; quote the text to search for it literally.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// "key:" without an inline value takes the value from the following phrase, e.g. tag:"a b".
|
// "key:" without an inline value takes the value from the following phrase, e.g. tag:"a b".
|
||||||
return value.Length == 0
|
if (value.Length == 0) {
|
||||||
? PhraseText.Bind(text => AtomParser(kind, text))
|
return kind == QualifierKind.Id
|
||||||
: AtomParser(kind, value);
|
? Parser<SearchToken>.Fail<SearchNode>("The id qualifier expects an unquoted positive integer.")
|
||||||
|
: PhraseText.Select(phrase => TextAtom(kind, phrase));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.Contains(':')) {
|
||||||
|
return Parser<SearchToken>.Fail<SearchNode>($"Unquoted value '{value}' of qualifier '{key}' contains ':'; quote the value.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value is "AND" or "OR") {
|
||||||
|
return Parser<SearchToken>.Fail<SearchNode>($"Operator {value} cannot be a qualifier value; quote it to search for it literally.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kind == QualifierKind.Id) {
|
||||||
|
return TryParseCardId(value, out long id)
|
||||||
|
? Parser<SearchToken>.Return<SearchNode>(new SearchNode.CardId(id))
|
||||||
|
: Parser<SearchToken>.Fail<SearchNode>($"The id qualifier expects a positive integer, got '{value}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Parser<SearchToken>.Return(TextAtom(kind, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Builds the atom parser for a qualifier value, failing strictly on a non-numeric id.
|
/// Builds the atom for a textual qualifier value.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="kind">The qualifier kind.</param>
|
/// <param name="kind">The qualifier kind; never <see cref="QualifierKind.Id"/>.</param>
|
||||||
/// <param name="value">The qualifier value.</param>
|
/// <param name="value">The qualifier value.</param>
|
||||||
/// <returns>The parser producing the atom node.</returns>
|
/// <returns>The atom node.</returns>
|
||||||
private static Parser<SearchToken, SearchNode> AtomParser(QualifierKind kind, string value) =>
|
private static SearchNode TextAtom(QualifierKind kind, string value) => kind switch {
|
||||||
AtomFrom(kind, value) is { } atom
|
|
||||||
? Parser<SearchToken>.Return(atom)
|
|
||||||
: Parser<SearchToken>.Fail<SearchNode>($"The id qualifier expects an integer, got '{value}'.");
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Builds the atom for a qualifier value; null when an id value is not an integer.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="kind">The qualifier kind.</param>
|
|
||||||
/// <param name="value">The qualifier value.</param>
|
|
||||||
/// <returns>The atom node, or <see langword="null"/> for an invalid id value.</returns>
|
|
||||||
private static SearchNode? AtomFrom(QualifierKind kind, string value) => kind switch {
|
|
||||||
QualifierKind.Tag => new SearchNode.TagName(value),
|
QualifierKind.Tag => new SearchNode.TagName(value),
|
||||||
QualifierKind.Title => new SearchNode.FieldText(SearchField.Title, value),
|
QualifierKind.Title => new SearchNode.FieldText(SearchField.Title, value),
|
||||||
QualifierKind.Content => new SearchNode.FieldText(SearchField.Content, value),
|
QualifierKind.Content => new SearchNode.FieldText(SearchField.Content, value),
|
||||||
QualifierKind.Column => new SearchNode.ColumnTitle(value),
|
QualifierKind.Column => new SearchNode.ColumnTitle(value),
|
||||||
QualifierKind.Id when long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out long id) =>
|
_ => throw new InvalidOperationException($"Qualifier kind {kind} has no textual value."),
|
||||||
new SearchNode.CardId(id),
|
|
||||||
_ => null,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Parses an id qualifier value: decimal digits with an optional leading
|
||||||
|
/// <c>#</c>, denoting a positive integer.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">The inline qualifier value.</param>
|
||||||
|
/// <param name="id">The parsed card id.</param>
|
||||||
|
/// <returns><see langword="true"/> when the value is a valid positive card id.</returns>
|
||||||
|
private static bool TryParseCardId(string value, out long id) {
|
||||||
|
ReadOnlySpan<char> digits = value.AsSpan();
|
||||||
|
if (digits.StartsWith("#")) {
|
||||||
|
digits = digits[1..];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Digits only: the span check rules out signs, whitespace and other NumberStyles leniency.
|
||||||
|
id = 0;
|
||||||
|
return digits.Length > 0
|
||||||
|
&& !digits.ContainsAnyExceptInRange('0', '9')
|
||||||
|
&& long.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out id)
|
||||||
|
&& id > 0;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Looks up a qualifier key in the extension table with ordinal (case-sensitive) matching.
|
/// Looks up a qualifier key in the extension table with ordinal (case-sensitive) matching.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -197,22 +221,6 @@ public static class SearchQueryParser {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns whether the text looks like a qualifier key: a non-empty run of
|
|
||||||
/// letters, digits or underscores.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="text">The candidate key text.</param>
|
|
||||||
/// <returns><see langword="true"/> when every character is a word character.</returns>
|
|
||||||
private static bool IsQualifierKeyCandidate(ReadOnlySpan<char> text) {
|
|
||||||
foreach (char character in text) {
|
|
||||||
if (!(char.IsLetterOrDigit(character) || character == '_')) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Collapses an AND chain into a single node.
|
/// Collapses an AND chain into a single node.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -236,9 +244,7 @@ public static class SearchQueryParser {
|
|||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>The recognized qualifier kinds.</summary>
|
||||||
/// The recognized qualifier kinds.
|
|
||||||
/// </summary>
|
|
||||||
private enum QualifierKind {
|
private enum QualifierKind {
|
||||||
Tag,
|
Tag,
|
||||||
Title,
|
Title,
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
using YKanBan.Storage;
|
||||||
|
|
||||||
namespace YKanBan.Search;
|
namespace YKanBan.Search;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -10,10 +12,11 @@ public sealed record CompiledSearch(string Predicate, IReadOnlyList<(string Name
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Compiles a parsed search AST into a parameterized SQL predicate. Matching is
|
/// Compiles a parsed search AST into a parameterized SQL predicate. Matching is
|
||||||
/// case-insensitive with SQLite's built-in semantics: LIKE's default case
|
/// Unicode case-insensitive: both sides are folded with
|
||||||
/// folding for substring matches plus COLLATE NOCASE for exact matches. LIKE
|
/// <see cref="SqliteDatabase.Fold"/> (the column side through the per-connection
|
||||||
/// wildcards and the escape character in user text are escaped so they match
|
/// <see cref="SqliteDatabase.FoldFunctionName"/> function) and then compared
|
||||||
/// literally.
|
/// ordinally — <c>instr</c> for substrings, <c>=</c> for exact matches. LIKE is
|
||||||
|
/// deliberately not used, so <c>%</c> and <c>_</c> carry no wildcard meaning.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class SearchSqlCompiler {
|
public static class SearchSqlCompiler {
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -43,26 +46,25 @@ public static class SearchSqlCompiler {
|
|||||||
|
|
||||||
case SearchNode.FreeText freeText: {
|
case SearchNode.FreeText freeText: {
|
||||||
// A bare word matches a substring of the title OR the content.
|
// A bare word matches a substring of the title OR the content.
|
||||||
string titleParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
|
string param = AddParameter(parameters, SqliteDatabase.Fold(freeText.Text));
|
||||||
string contentParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
|
return $"({Contains("c.title", param)} OR {Contains("c.content", param)})";
|
||||||
return $"(c.title LIKE {titleParam} ESCAPE '\\' OR c.content LIKE {contentParam} ESCAPE '\\')";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
case SearchNode.FieldText field: {
|
case SearchNode.FieldText field: {
|
||||||
string column = field.Field == SearchField.Title ? "c.title" : "c.content";
|
string column = field.Field == SearchField.Title ? "c.title" : "c.content";
|
||||||
string param = AddParameter(parameters, "%" + EscapeLike(field.Text) + "%");
|
string param = AddParameter(parameters, SqliteDatabase.Fold(field.Text));
|
||||||
return $"{column} LIKE {param} ESCAPE '\\'";
|
return Contains(column, param);
|
||||||
}
|
}
|
||||||
|
|
||||||
case SearchNode.TagName tag: {
|
case SearchNode.TagName tag: {
|
||||||
string param = AddParameter(parameters, tag.Name);
|
string param = AddParameter(parameters, SqliteDatabase.Fold(tag.Name));
|
||||||
return "EXISTS (SELECT 1 FROM card_tags ct JOIN tags t ON t.id = ct.tag_id " +
|
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})";
|
$"WHERE ct.card_id = c.id AND {Folded("t.name")} = {param})";
|
||||||
}
|
}
|
||||||
|
|
||||||
case SearchNode.ColumnTitle column: {
|
case SearchNode.ColumnTitle column: {
|
||||||
string param = AddParameter(parameters, column.Title);
|
string param = AddParameter(parameters, SqliteDatabase.Fold(column.Title));
|
||||||
return $"c.column_id IN (SELECT id FROM columns WHERE title COLLATE NOCASE = {param})";
|
return $"c.column_id IN (SELECT id FROM columns WHERE {Folded("title")} = {param})";
|
||||||
}
|
}
|
||||||
|
|
||||||
case SearchNode.CardId id: {
|
case SearchNode.CardId id: {
|
||||||
@@ -88,10 +90,17 @@ public static class SearchSqlCompiler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Escapes LIKE wildcards and the escape character inside user text.
|
/// Wraps a column expression in the case-folding SQL function.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="text">The raw user text.</param>
|
/// <param name="column">The column expression.</param>
|
||||||
/// <returns>The text with <c>\</c>, <c>%</c> and <c>_</c> escaped.</returns>
|
/// <returns>The folded column expression.</returns>
|
||||||
private static string EscapeLike(string text) =>
|
private static string Folded(string column) => $"{SqliteDatabase.FoldFunctionName}({column})";
|
||||||
text.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_");
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds an ordinal substring test of a folded column against an already folded parameter.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="column">The column expression.</param>
|
||||||
|
/// <param name="param">The placeholder of the folded search text.</param>
|
||||||
|
/// <returns>The SQL boolean expression.</returns>
|
||||||
|
private static string Contains(string column, string param) => $"instr({Folded(column)}, {param}) > 0";
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,14 @@ namespace YKanBan.Search;
|
|||||||
/// localized.
|
/// localized.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class SearchSyntaxException : Exception {
|
public sealed class SearchSyntaxException : Exception {
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes the exception with a descriptive English message.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="message">The English diagnostic message.</param>
|
||||||
|
public SearchSyntaxException(string message)
|
||||||
|
: base(message) {
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes the exception with a descriptive English message.
|
/// Initializes the exception with a descriptive English message.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -45,9 +45,33 @@ public sealed class AppServices : IDisposable {
|
|||||||
return Session;
|
return Session;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a fresh workspace and opens it, holding the lock throughout.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="folderPath">The folder to initialize.</param>
|
||||||
|
/// <returns>The open session.</returns>
|
||||||
|
/// <exception cref="YKanBan.Storage.WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
||||||
|
/// <exception cref="YKanBan.Storage.WorkspaceLockException">Another instance already holds the lock.</exception>
|
||||||
|
public WorkspaceSession InitializeWorkspace(string folderPath) {
|
||||||
|
Session = WorkspaceSession.Initialize(folderPath);
|
||||||
|
return Session;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Releases the workspace session, if any, and forgets it.
|
||||||
|
/// </summary>
|
||||||
|
public void CloseWorkspace() {
|
||||||
|
Session?.Dispose();
|
||||||
|
Session = null;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Persists the configuration; called once at shutdown.
|
/// Persists the configuration; called once at shutdown.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
// YYC MARK: the whole app.json is rewritten unconditionally at shutdown.
|
||||||
|
// Running several instances would make the last one to exit overwrite every
|
||||||
|
// field with its own in-memory state. Multi-instance use is not supported,
|
||||||
|
// so this last-writer-wins behavior is accepted.
|
||||||
public void SaveConfiguration() => ConfigStore.Save(Config);
|
public void SaveConfiguration() => ConfigStore.Save(Config);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -4,18 +4,23 @@ using Newtonsoft.Json.Converters;
|
|||||||
namespace YKanBan.Storage.AppData;
|
namespace YKanBan.Storage.AppData;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Loads and saves app.json with graceful degradation: a missing file yields
|
/// Loads and saves app.json with graceful degradation: a missing or unreadable
|
||||||
/// defaults; a corrupt file is backed up to app.json.bak and then defaults are
|
/// file yields defaults; a corrupt file is backed up to app.json.bak and then
|
||||||
/// used. Saving writes the file directly (no atomic replace) — losing the last
|
/// defaults are used. Saving writes the file directly (no atomic replace) —
|
||||||
/// session's settings to a crash is an accepted trade-off.
|
/// losing the last session's settings to a crash is an accepted trade-off.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class AppConfigStore {
|
public sealed class AppConfigStore {
|
||||||
private static readonly JsonSerializerSettings SerializerSettings = new() {
|
private static readonly JsonSerializerSettings SerializerSettings = new() {
|
||||||
Formatting = Formatting.Indented,
|
Formatting = Formatting.Indented,
|
||||||
NullValueHandling = NullValueHandling.Ignore,
|
NullValueHandling = NullValueHandling.Ignore,
|
||||||
|
|
||||||
// Enums round-trip through the kebab-case strings declared via [EnumMember].
|
// Enums round-trip through the kebab-case strings declared via [EnumMember];
|
||||||
Converters = { new StringEnumConverter() },
|
// numeric enum values are rejected like any other unknown value.
|
||||||
|
// YYC MARK: non-enum fields (bool/int/string) are still coerced by
|
||||||
|
// Newtonsoft (for example 0 or "true" to bool, "500" or 500.0 to int);
|
||||||
|
// a wrongly typed non-enum value is accepted and converted rather than
|
||||||
|
// treated as invalid. That leniency is accepted here.
|
||||||
|
Converters = { new StringEnumConverter { AllowIntegerValues = false } },
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -31,17 +36,24 @@ public sealed class AppConfigStore {
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Loads the configuration. A missing file yields defaults; a corrupt file
|
/// Loads the configuration. A missing file yields defaults; a corrupt file
|
||||||
/// is backed up to app.json.bak and then defaults are used.
|
/// is backed up to app.json.bak and then defaults are used; a file that
|
||||||
|
/// exists but cannot be read (I/O or permission error) also yields defaults.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>The loaded configuration, or defaults when none could be read.</returns>
|
/// <returns>The loaded configuration, or defaults when none could be read.</returns>
|
||||||
/// <exception cref="IOException">The file exists but cannot be read.</exception>
|
|
||||||
public AppConfig Load() {
|
public AppConfig Load() {
|
||||||
// Missing file is a normal first-run state: run with defaults.
|
// Missing file is a normal first-run state: run with defaults.
|
||||||
if (!File.Exists(FilePath)) {
|
if (!File.Exists(FilePath)) {
|
||||||
return new AppConfig();
|
return new AppConfig();
|
||||||
}
|
}
|
||||||
|
|
||||||
string json = File.ReadAllText(FilePath);
|
string json;
|
||||||
|
try {
|
||||||
|
json = File.ReadAllText(FilePath);
|
||||||
|
} catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) {
|
||||||
|
// A bad app.json must not stop startup.
|
||||||
|
return new AppConfig();
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// A JSON null literal deserializes to null; treat it like defaults.
|
// A JSON null literal deserializes to null; treat it like defaults.
|
||||||
AppConfig? config = JsonConvert.DeserializeObject<AppConfig>(json, SerializerSettings);
|
AppConfig? config = JsonConvert.DeserializeObject<AppConfig>(json, SerializerSettings);
|
||||||
@@ -54,8 +66,12 @@ public sealed class AppConfigStore {
|
|||||||
config.Confirmations ??= new ConfirmationSettings();
|
config.Confirmations ??= new ConfirmationSettings();
|
||||||
return config;
|
return config;
|
||||||
} catch (JsonException) {
|
} catch (JsonException) {
|
||||||
// Corrupt: keep a copy for inspection, then continue with defaults.
|
// Corrupt: keep a copy for inspection (best effort), then continue with defaults.
|
||||||
File.Copy(FilePath, FilePath + ".bak", overwrite: true);
|
try {
|
||||||
|
File.Copy(FilePath, FilePath + ".bak", overwrite: true);
|
||||||
|
} catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) {
|
||||||
|
// The backup is only a diagnostic aid; starting with defaults matters more.
|
||||||
|
}
|
||||||
return new AppConfig();
|
return new AppConfig();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,20 @@ namespace YKanBan.Storage;
|
|||||||
/// foreign keys on) and applies incremental <c>user_version</c> migrations.
|
/// foreign keys on) and applies incremental <c>user_version</c> migrations.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class SqliteDatabase {
|
public static class SqliteDatabase {
|
||||||
|
/// <summary>
|
||||||
|
/// Name of the per-connection SQL function that applies <see cref="Fold"/>;
|
||||||
|
/// search uses it for Unicode case-insensitive matching.
|
||||||
|
/// </summary>
|
||||||
|
public const string FoldFunctionName = "ykb_fold";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Unicode case folding shared by the SQL function and the search
|
||||||
|
/// parameters it is compared against; comparisons after folding are ordinal.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text">The text to fold.</param>
|
||||||
|
/// <returns>The invariant lowercase form.</returns>
|
||||||
|
public static string Fold(string text) => text.ToLowerInvariant();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Opens (creating if needed) a database file, applies the mandatory
|
/// Opens (creating if needed) a database file, applies the mandatory
|
||||||
/// PRAGMAs and runs any pending migrations.
|
/// PRAGMAs and runs any pending migrations.
|
||||||
@@ -27,6 +41,7 @@ public static class SqliteDatabase {
|
|||||||
connection.Open();
|
connection.Open();
|
||||||
try {
|
try {
|
||||||
ApplyPragmas(connection);
|
ApplyPragmas(connection);
|
||||||
|
RegisterFunctions(connection);
|
||||||
ApplyMigrations(connection, migrations);
|
ApplyMigrations(connection, migrations);
|
||||||
return connection;
|
return connection;
|
||||||
} catch {
|
} catch {
|
||||||
@@ -59,6 +74,17 @@ public static class SqliteDatabase {
|
|||||||
Execute(connection, "PRAGMA foreign_keys=ON;");
|
Execute(connection, "PRAGMA foreign_keys=ON;");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Registers the custom SQL functions; like the PRAGMAs they live on the
|
||||||
|
/// connection and must be registered on every one.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="connection">An open database connection.</param>
|
||||||
|
internal static void RegisterFunctions(SqliteConnection connection) {
|
||||||
|
// NULL never reaches it from the NOT NULL text columns, but stays NULL-safe regardless.
|
||||||
|
connection.CreateFunction<string?, string?>(
|
||||||
|
FoldFunctionName, text => text is null ? null : Fold(text), isDeterministic: true);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Runs every migration newer than the stored <c>user_version</c>, each in
|
/// Runs every migration newer than the stored <c>user_version</c>, each in
|
||||||
/// its own transaction together with its version bump.
|
/// its own transaction together with its version bump.
|
||||||
|
|||||||
@@ -55,6 +55,26 @@ public sealed class WorkspaceNotInitializedException : YKanBanException {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Signals that .ykanban exists but its database file does not, so the
|
||||||
|
/// workspace data is missing; a new empty database is never created silently.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class WorkspaceDatabaseMissingException : YKanBanException {
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the database file that was expected to exist.
|
||||||
|
/// </summary>
|
||||||
|
public string DatabasePath { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes the exception for a missing workspace database.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="databasePath">The missing database file path.</param>
|
||||||
|
public WorkspaceDatabaseMissingException(string databasePath)
|
||||||
|
: base($"The workspace database is missing: {databasePath}") {
|
||||||
|
DatabasePath = databasePath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Signals that another instance already holds the workspace lock, so this
|
/// Signals that another instance already holds the workspace lock, so this
|
||||||
/// process must not touch the workspace.
|
/// process must not touch the workspace.
|
||||||
|
|||||||
@@ -25,6 +25,12 @@ public static class WorkspaceInitializer {
|
|||||||
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
||||||
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
|
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
|
||||||
public static void Initialize(string folderPath) {
|
public static void Initialize(string folderPath) {
|
||||||
|
// YYC MARK: this class is deliberately a lock-free, functional unit; it
|
||||||
|
// does not acquire the workspace lock. Ensuring the lock is held before
|
||||||
|
// initialization is the caller's responsibility (see
|
||||||
|
// WorkspaceSession.Initialize). The schema migration and the later preset
|
||||||
|
// writes are also not one transaction, so a crash mid-initialization can
|
||||||
|
// leave a partially built database; that is accepted here.
|
||||||
if (!Directory.Exists(folderPath)) {
|
if (!Directory.Exists(folderPath)) {
|
||||||
throw new WorkspaceDirectoryMissingException(folderPath);
|
throw new WorkspaceDirectoryMissingException(folderPath);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,9 +38,55 @@ public sealed class WorkspaceSession : IDisposable {
|
|||||||
/// <param name="folderPath">The workspace folder to open.</param>
|
/// <param name="folderPath">The workspace folder to open.</param>
|
||||||
/// <returns>The opened session; dispose it to release the lock and connection.</returns>
|
/// <returns>The opened session; dispose it to release the lock and connection.</returns>
|
||||||
/// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
|
/// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
|
||||||
|
/// <exception cref="WorkspaceDatabaseMissingException">.ykanban exists but its database file does not.</exception>
|
||||||
/// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception>
|
/// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception>
|
||||||
public static WorkspaceSession Open(string folderPath) {
|
public static WorkspaceSession Open(string folderPath) {
|
||||||
WorkspaceLock workspaceLock = WorkspaceLock.Acquire(folderPath);
|
WorkspaceLock workspaceLock = WorkspaceLock.Acquire(folderPath);
|
||||||
|
|
||||||
|
// Opening would otherwise create an empty database and show an empty board as if nothing was lost.
|
||||||
|
string databasePath = WorkspacePaths.Database(folderPath);
|
||||||
|
if (!File.Exists(databasePath)) {
|
||||||
|
workspaceLock.Dispose();
|
||||||
|
throw new WorkspaceDatabaseMissingException(databasePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
return OpenLocked(folderPath, workspaceLock);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a workspace with its preset columns and tags, then opens it.
|
||||||
|
/// The lock is taken right after .ykanban is created and is never released in
|
||||||
|
/// between, so no other instance can interleave with the initialization.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="folderPath">The existing folder to initialize.</param>
|
||||||
|
/// <returns>The opened session; dispose it to release the lock and connection.</returns>
|
||||||
|
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
||||||
|
/// <exception cref="WorkspaceLockException">Another instance holds the workspace lock.</exception>
|
||||||
|
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
|
||||||
|
public static WorkspaceSession Initialize(string folderPath) {
|
||||||
|
// .ykanban first: the lock file lives inside it. Taking the lock here,
|
||||||
|
// before any database work, keeps two instances from initializing the same
|
||||||
|
// folder at once; WorkspaceInitializer stays a lock-free functional class.
|
||||||
|
Directory.CreateDirectory(WorkspacePaths.Root(folderPath));
|
||||||
|
WorkspaceLock workspaceLock = WorkspaceLock.Acquire(folderPath);
|
||||||
|
try {
|
||||||
|
WorkspaceInitializer.Initialize(folderPath);
|
||||||
|
WorkspacePreset.AddPresetColumns(folderPath);
|
||||||
|
WorkspacePreset.AddPresetTags(folderPath);
|
||||||
|
return OpenLocked(folderPath, workspaceLock);
|
||||||
|
} catch {
|
||||||
|
workspaceLock.Dispose();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Opens the repository under an already held lock; the lock is released if that fails.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="folderPath">The workspace folder.</param>
|
||||||
|
/// <param name="workspaceLock">The held workspace lock.</param>
|
||||||
|
/// <returns>The opened session.</returns>
|
||||||
|
private static WorkspaceSession OpenLocked(string folderPath, WorkspaceLock workspaceLock) {
|
||||||
try {
|
try {
|
||||||
var repository = new WorkspaceRepository(folderPath);
|
var repository = new WorkspaceRepository(folderPath);
|
||||||
return new WorkspaceSession(folderPath, workspaceLock, repository);
|
return new WorkspaceSession(folderPath, workspaceLock, repository);
|
||||||
|
|||||||
@@ -20,6 +20,10 @@ public class ViewLocator : IDataTemplate {
|
|||||||
return (Control)Activator.CreateInstance(type)!;
|
return (Control)Activator.CreateInstance(type)!;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// YYC MARK: the missing-view placeholder is a programmer error (a view
|
||||||
|
// model without its matching view), not a user-facing message. It must be
|
||||||
|
// caught by the code-behind convention test before release, so it is kept
|
||||||
|
// as a hard-coded English diagnostic and is deliberately not localized.
|
||||||
return new TextBlock { Text = "Not Found: " + name };
|
return new TextBlock { Text = "Not Found: " + name };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
using System.Globalization;
|
|
||||||
|
|
||||||
namespace YKanBan.ViewModels.ErrorPages;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// The full-window page shown when the folder passed on the command line does
|
|
||||||
/// not exist. It has no operations.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class DirectoryMissingPageViewModel : ViewModelBase {
|
|
||||||
/// <summary>
|
|
||||||
/// Initializes the page for a missing folder.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="folderPath">The folder path that does not exist.</param>
|
|
||||||
public DirectoryMissingPageViewModel(string folderPath) {
|
|
||||||
FolderPath = folderPath;
|
|
||||||
Message = string.Format(
|
|
||||||
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Error_DirectoryMissing_Message, folderPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets the folder path that does not exist.
|
|
||||||
/// </summary>
|
|
||||||
public string FolderPath { get; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets the localized explanatory message.
|
|
||||||
/// </summary>
|
|
||||||
public string Message { get; }
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
|
||||||
|
using YKanBan.Storage;
|
||||||
|
|
||||||
|
namespace YKanBan.ViewModels.ErrorPages;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The full-window page shown when a workspace cannot be opened or initialized:
|
||||||
|
/// a schema newer than this build, a missing, unopenable or damaged database, an
|
||||||
|
/// I/O or permission error, or any unrecognized failure. It shows a localized
|
||||||
|
/// message chosen by exception type plus the read-only, copyable English
|
||||||
|
/// exception details, and has no operations.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class OpenFailedPageViewModel : ViewModelBase {
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes the page for a failed open or initialization.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="folderPath">The workspace folder.</param>
|
||||||
|
/// <param name="exception">The failure.</param>
|
||||||
|
public OpenFailedPageViewModel(string folderPath, Exception exception) {
|
||||||
|
FolderPath = folderPath;
|
||||||
|
Message = BuildMessage(folderPath, exception);
|
||||||
|
|
||||||
|
// Exception texts are English: ours by convention, .NET and SQLite ones by design.
|
||||||
|
Details = exception.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the workspace folder.
|
||||||
|
/// </summary>
|
||||||
|
public string FolderPath { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the localized explanatory message.
|
||||||
|
/// </summary>
|
||||||
|
public string Message { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the English exception details for diagnosis.
|
||||||
|
/// </summary>
|
||||||
|
public string Details { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Maps the exception type to its localized message; unrecognized types get the generic one.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="folderPath">The workspace folder.</param>
|
||||||
|
/// <param name="exception">The failure.</param>
|
||||||
|
/// <returns>The localized message.</returns>
|
||||||
|
public static string BuildMessage(string folderPath, Exception exception) {
|
||||||
|
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentCulture;
|
||||||
|
return exception switch {
|
||||||
|
SchemaVersionException schema => string.Format(
|
||||||
|
culture, Resources.Error_OpenFailed_SchemaTooNew, folderPath, schema.StoredVersion, schema.SupportedVersion),
|
||||||
|
WorkspaceDatabaseMissingException => string.Format(culture, Resources.Error_OpenFailed_DatabaseMissing, folderPath),
|
||||||
|
SqliteException => string.Format(culture, Resources.Error_OpenFailed_Database, folderPath),
|
||||||
|
UnauthorizedAccessException => string.Format(culture, Resources.Error_OpenFailed_AccessDenied, folderPath),
|
||||||
|
IOException => string.Format(culture, Resources.Error_OpenFailed_Io, folderPath),
|
||||||
|
_ => string.Format(culture, Resources.Error_OpenFailed_Generic, folderPath),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -69,17 +69,16 @@ public sealed partial class MainWindowViewModel : ViewModelBase {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!Directory.Exists(folderPath)) {
|
|
||||||
Content = new DirectoryMissingPageViewModel(folderPath);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
OpenWorkspace(folderPath);
|
OpenWorkspace(folderPath);
|
||||||
} catch (WorkspaceNotInitializedException) {
|
} catch (WorkspaceNotInitializedException) {
|
||||||
Content = new NotInitializedPageViewModel(folderPath, InitializeWorkspace);
|
Content = new NotInitializedPageViewModel(folderPath, InitializeWorkspace);
|
||||||
} catch (WorkspaceLockException) {
|
} catch (WorkspaceLockException) {
|
||||||
Content = new LockConflictPageViewModel(folderPath);
|
Content = new LockConflictPageViewModel(folderPath);
|
||||||
|
} catch (Exception exception) {
|
||||||
|
// Newer schema, damaged database, I/O or permission errors, and anything unrecognized.
|
||||||
|
Debug.WriteLine(exception);
|
||||||
|
Content = new OpenFailedPageViewModel(folderPath, exception);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,9 +86,22 @@ public sealed partial class MainWindowViewModel : ViewModelBase {
|
|||||||
/// Opens the workspace and switches the content to the normal view.
|
/// Opens the workspace and switches the content to the normal view.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="folderPath">The workspace folder to open.</param>
|
/// <param name="folderPath">The workspace folder to open.</param>
|
||||||
private void OpenWorkspace(string folderPath) {
|
private void OpenWorkspace(string folderPath) => OpenWorkspace(folderPath, _services.OpenWorkspace(folderPath));
|
||||||
WorkspaceSession session = _services.OpenWorkspace(folderPath);
|
|
||||||
Content = new WorkspaceViewModel(_services, session, ShowSettings, ShowAbout);
|
/// <summary>
|
||||||
|
/// Switches the content to the normal view of an already opened workspace.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="folderPath">The workspace folder.</param>
|
||||||
|
/// <param name="session">The opened workspace session.</param>
|
||||||
|
private void OpenWorkspace(string folderPath, WorkspaceSession session) {
|
||||||
|
try {
|
||||||
|
Content = new WorkspaceViewModel(_services, session, ShowSettings, ShowAbout);
|
||||||
|
} catch {
|
||||||
|
// The first board read failed: the caller shows an error page, which holds no workspace.
|
||||||
|
_services.CloseWorkspace();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
Title = $"{new DirectoryInfo(folderPath).Name} - {Resources.App_Name}";
|
Title = $"{new DirectoryInfo(folderPath).Name} - {Resources.App_Name}";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,10 +116,7 @@ public sealed partial class MainWindowViewModel : ViewModelBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
WorkspaceInitializer.Initialize(page.FolderPath);
|
OpenWorkspace(page.FolderPath, _services.InitializeWorkspace(page.FolderPath));
|
||||||
WorkspacePreset.AddPresetColumns(page.FolderPath);
|
|
||||||
WorkspacePreset.AddPresetTags(page.FolderPath);
|
|
||||||
OpenWorkspace(page.FolderPath);
|
|
||||||
} catch (Exception exception) when (exception is YKanBanException or IOException or UnauthorizedAccessException) {
|
} catch (Exception exception) when (exception is YKanBanException or IOException or UnauthorizedAccessException) {
|
||||||
// Initialization failed; the page remains so the user can retry.
|
// Initialization failed; the page remains so the user can retry.
|
||||||
Debug.WriteLine(exception);
|
Debug.WriteLine(exception);
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ public partial class BoardView : UserControl {
|
|||||||
var dialog = new ColumnEditorDialog {
|
var dialog = new ColumnEditorDialog {
|
||||||
DataContext = new ColumnEditorViewModel(board.Repository, column?.Model),
|
DataContext = new ColumnEditorViewModel(board.Repository, column?.Model),
|
||||||
};
|
};
|
||||||
if (await dialog.ShowDialog<bool>(owner)) {
|
if (await ModalWindow.ShowAsync<bool>(owner, dialog)) {
|
||||||
board.Reload();
|
board.Reload();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -62,7 +62,7 @@ public partial class BoardView : UserControl {
|
|||||||
var dialog = new DeleteColumnConfirmDialog {
|
var dialog = new DeleteColumnConfirmDialog {
|
||||||
DataContext = new DeleteColumnConfirmViewModel(column.Title, column.CardCount),
|
DataContext = new DeleteColumnConfirmViewModel(column.Title, column.CardCount),
|
||||||
};
|
};
|
||||||
confirmed = await dialog.ShowDialog<bool>(owner);
|
confirmed = await ModalWindow.ShowAsync<bool>(owner, dialog);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!confirmed) {
|
if (!confirmed) {
|
||||||
@@ -85,7 +85,7 @@ public partial class BoardView : UserControl {
|
|||||||
var dialog = new CardEditorDialog {
|
var dialog = new CardEditorDialog {
|
||||||
DataContext = new CardEditorViewModel(board.Repository, columnId, card?.Model),
|
DataContext = new CardEditorViewModel(board.Repository, columnId, card?.Model),
|
||||||
};
|
};
|
||||||
if (await dialog.ShowDialog<bool>(owner)) {
|
if (await ModalWindow.ShowAsync<bool>(owner, dialog)) {
|
||||||
board.Reload();
|
board.Reload();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -103,7 +103,7 @@ public partial class BoardView : UserControl {
|
|||||||
var dialog = new DeleteCardConfirmDialog {
|
var dialog = new DeleteCardConfirmDialog {
|
||||||
DataContext = new DeleteCardConfirmViewModel(card.Id),
|
DataContext = new DeleteCardConfirmViewModel(card.Id),
|
||||||
};
|
};
|
||||||
confirmed = await dialog.ShowDialog<bool>(owner);
|
confirmed = await ModalWindow.ShowAsync<bool>(owner, dialog);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!confirmed) {
|
if (!confirmed) {
|
||||||
@@ -125,7 +125,7 @@ public partial class BoardView : UserControl {
|
|||||||
var dialog = new MoveCardDialog {
|
var dialog = new MoveCardDialog {
|
||||||
DataContext = new MoveCardViewModel(board.Repository.GetColumns(), card.ColumnId),
|
DataContext = new MoveCardViewModel(board.Repository.GetColumns(), card.ColumnId),
|
||||||
};
|
};
|
||||||
if (await dialog.ShowDialog<long?>(owner) is long targetColumnId) {
|
if (await ModalWindow.ShowAsync<long?>(owner, dialog) is long targetColumnId) {
|
||||||
board.Repository.MoveCard(card.Id, targetColumnId);
|
board.Repository.MoveCard(card.Id, targetColumnId);
|
||||||
board.Reload();
|
board.Reload();
|
||||||
}
|
}
|
||||||
@@ -142,6 +142,6 @@ public partial class BoardView : UserControl {
|
|||||||
var dialog = new SearchErrorDialog {
|
var dialog = new SearchErrorDialog {
|
||||||
DataContext = new SearchErrorViewModel(detail),
|
DataContext = new SearchErrorViewModel(detail),
|
||||||
};
|
};
|
||||||
await dialog.ShowDialog(owner);
|
await ModalWindow.ShowAsync(owner, dialog);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -35,7 +35,7 @@ public partial class CardEditorDialog : Window {
|
|||||||
viewModel.Repository,
|
viewModel.Repository,
|
||||||
viewModel.AssignedTags.Select(row => row.Tag.Id).ToList()),
|
viewModel.AssignedTags.Select(row => row.Tag.Id).ToList()),
|
||||||
};
|
};
|
||||||
return await dialog.ShowDialog<TagModel?>(this);
|
return await ModalWindow.ShowAsync<TagModel?>(this, dialog);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -76,7 +76,7 @@ public partial class CardEditorDialog : Window {
|
|||||||
private async Task RequestCloseAsync() {
|
private async Task RequestCloseAsync() {
|
||||||
if (HasUnsavedChanges && DiscardConfirmEnabled) {
|
if (HasUnsavedChanges && DiscardConfirmEnabled) {
|
||||||
var dialog = new DiscardEditConfirmDialog { DataContext = new DiscardEditConfirmViewModel() };
|
var dialog = new DiscardEditConfirmDialog { DataContext = new DiscardEditConfirmViewModel() };
|
||||||
if (!await dialog.ShowDialog<bool>(this)) {
|
if (!await ModalWindow.ShowAsync<bool>(this, dialog)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,9 +16,9 @@
|
|||||||
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
|
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
|
||||||
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||||
<Button Content="{x:Static lang:Resources.Common_Delete}" Click="OnConfirmClick"
|
<Button Content="{x:Static lang:Resources.Common_Delete}" Click="OnConfirmClick"
|
||||||
MinWidth="90" IsDefault="True"/>
|
MinWidth="90"/>
|
||||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
|
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
|
||||||
MinWidth="90" IsCancel="True"/>
|
MinWidth="90" IsDefault="True" IsCancel="True"/>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</Grid>
|
</Grid>
|
||||||
</Window>
|
</Window>
|
||||||
@@ -16,9 +16,9 @@
|
|||||||
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
|
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
|
||||||
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||||
<Button Content="{x:Static lang:Resources.Common_Delete}" Click="OnConfirmClick"
|
<Button Content="{x:Static lang:Resources.Common_Delete}" Click="OnConfirmClick"
|
||||||
MinWidth="90" IsDefault="True"/>
|
MinWidth="90"/>
|
||||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
|
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
|
||||||
MinWidth="90" IsCancel="True"/>
|
MinWidth="90" IsDefault="True" IsCancel="True"/>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</Grid>
|
</Grid>
|
||||||
</Window>
|
</Window>
|
||||||
@@ -16,9 +16,9 @@
|
|||||||
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
|
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
|
||||||
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||||
<Button Content="{x:Static lang:Resources.Common_Delete}" Click="OnConfirmClick"
|
<Button Content="{x:Static lang:Resources.Common_Delete}" Click="OnConfirmClick"
|
||||||
MinWidth="90" IsDefault="True"/>
|
MinWidth="90"/>
|
||||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
|
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
|
||||||
MinWidth="90" IsCancel="True"/>
|
MinWidth="90" IsDefault="True" IsCancel="True"/>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</Grid>
|
</Grid>
|
||||||
</Window>
|
</Window>
|
||||||
@@ -16,9 +16,9 @@
|
|||||||
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
|
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
|
||||||
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||||
<Button Content="{x:Static lang:Resources.Common_Ok}" Click="OnConfirmClick"
|
<Button Content="{x:Static lang:Resources.Common_Ok}" Click="OnConfirmClick"
|
||||||
MinWidth="90" IsDefault="True"/>
|
MinWidth="90"/>
|
||||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
|
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
|
||||||
MinWidth="90" IsCancel="True"/>
|
MinWidth="90" IsDefault="True" IsCancel="True"/>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</Grid>
|
</Grid>
|
||||||
</Window>
|
</Window>
|
||||||
+10
-4
@@ -5,14 +5,20 @@
|
|||||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
mc:Ignorable="d" d:DesignWidth="1000" d:DesignHeight="640"
|
mc:Ignorable="d" d:DesignWidth="1000" d:DesignHeight="640"
|
||||||
x:Class="YKanBan.Views.ErrorPages.DirectoryMissingPageView"
|
x:Class="YKanBan.Views.ErrorPages.OpenFailedPageView"
|
||||||
x:DataType="vm:DirectoryMissingPageViewModel">
|
x:DataType="vm:OpenFailedPageViewModel">
|
||||||
|
|
||||||
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Spacing="12"
|
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Spacing="12"
|
||||||
MaxWidth="560" Margin="32">
|
MaxWidth="720" Margin="32">
|
||||||
<TextBlock Text="{x:Static lang:Resources.Error_DirectoryMissing_Title}"
|
<TextBlock Text="{x:Static lang:Resources.Error_OpenFailed_Title}"
|
||||||
FontSize="20" FontWeight="SemiBold" HorizontalAlignment="Center"/>
|
FontSize="20" FontWeight="SemiBold" HorizontalAlignment="Center"/>
|
||||||
<TextBlock Text="{Binding Message}"
|
<TextBlock Text="{Binding Message}"
|
||||||
TextWrapping="Wrap" HorizontalAlignment="Center" TextAlignment="Center"/>
|
TextWrapping="Wrap" HorizontalAlignment="Center" TextAlignment="Center"/>
|
||||||
|
<TextBlock Text="{x:Static lang:Resources.Error_OpenFailed_Details}" FontWeight="SemiBold"/>
|
||||||
|
<!-- English diagnostics stay left-to-right whatever the UI flow direction. -->
|
||||||
|
<TextBox Text="{Binding Details, Mode=OneWay}"
|
||||||
|
IsReadOnly="True" TextWrapping="Wrap" AcceptsReturn="True"
|
||||||
|
FlowDirection="LeftToRight"
|
||||||
|
FontFamily="Consolas,Menlo,monospace" MaxHeight="240"/>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</UserControl>
|
</UserControl>
|
||||||
+2
-2
@@ -2,8 +2,8 @@ using Avalonia.Controls;
|
|||||||
|
|
||||||
namespace YKanBan.Views.ErrorPages;
|
namespace YKanBan.Views.ErrorPages;
|
||||||
|
|
||||||
public partial class DirectoryMissingPageView : UserControl {
|
public partial class OpenFailedPageView : UserControl {
|
||||||
public DirectoryMissingPageView() {
|
public OpenFailedPageView() {
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
mc:Ignorable="d" d:DesignWidth="1000" d:DesignHeight="640"
|
mc:Ignorable="d" d:DesignWidth="1000" d:DesignHeight="640"
|
||||||
x:Class="YKanBan.Views.MainWindow"
|
x:Class="YKanBan.Views.MainWindow"
|
||||||
x:DataType="vm:MainWindowViewModel"
|
x:DataType="vm:MainWindowViewModel"
|
||||||
Icon="/Assets/avalonia-logo.ico"
|
Icon="/Assets/ykanban.ico"
|
||||||
Title="{Binding Title}"
|
Title="{Binding Title}"
|
||||||
Width="1000" Height="640" MinWidth="720" MinHeight="480">
|
Width="1000" Height="640" MinWidth="720" MinHeight="480">
|
||||||
|
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ public partial class MainWindow : Window {
|
|||||||
var dialog = new SettingsDialog {
|
var dialog = new SettingsDialog {
|
||||||
DataContext = new SettingsDialogViewModel(App.Services.Config, App.StartupLanguage),
|
DataContext = new SettingsDialogViewModel(App.Services.Config, App.StartupLanguage),
|
||||||
};
|
};
|
||||||
await dialog.ShowDialog(this);
|
await ModalWindow.ShowAsync(this, dialog);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -43,6 +43,6 @@ public partial class MainWindow : Window {
|
|||||||
var dialog = new AboutDialog {
|
var dialog = new AboutDialog {
|
||||||
DataContext = new AboutDialogViewModel(),
|
DataContext = new AboutDialogViewModel(),
|
||||||
};
|
};
|
||||||
await dialog.ShowDialog(this);
|
await ModalWindow.ShowAsync(this, dialog);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
using Avalonia.Controls;
|
||||||
|
|
||||||
|
namespace YKanBan.Views;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Shows a modal window owned by another window, applying the startup culture's
|
||||||
|
/// flow direction first. FlowDirection does not inherit across windows, so every
|
||||||
|
/// modal must apply it explicitly.
|
||||||
|
/// </summary>
|
||||||
|
internal static class ModalWindow {
|
||||||
|
/// <summary>
|
||||||
|
/// Shows a modal window that returns a result.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="owner">The owning window.</param>
|
||||||
|
/// <param name="dialog">The modal window to show.</param>
|
||||||
|
/// <typeparam name="TResult">The dialog result type.</typeparam>
|
||||||
|
/// <returns>A task completing with the dialog result.</returns>
|
||||||
|
public static Task<TResult> ShowAsync<TResult>(Window owner, Window dialog) {
|
||||||
|
dialog.FlowDirection = App.UiFlowDirection;
|
||||||
|
return dialog.ShowDialog<TResult>(owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Shows a modal window that has no result.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="owner">The owning window.</param>
|
||||||
|
/// <param name="dialog">The modal window to show.</param>
|
||||||
|
/// <returns>A task completing when the dialog closes.</returns>
|
||||||
|
public static Task ShowAsync(Window owner, Window dialog) {
|
||||||
|
dialog.FlowDirection = App.UiFlowDirection;
|
||||||
|
return dialog.ShowDialog(owner);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -39,7 +39,7 @@ public partial class TagsView : UserControl {
|
|||||||
var dialog = new TagEditorDialog {
|
var dialog = new TagEditorDialog {
|
||||||
DataContext = new TagEditorViewModel(tags.Repository, item?.Tag),
|
DataContext = new TagEditorViewModel(tags.Repository, item?.Tag),
|
||||||
};
|
};
|
||||||
if (await dialog.ShowDialog<bool>(owner)) {
|
if (await ModalWindow.ShowAsync<bool>(owner, dialog)) {
|
||||||
tags.RefreshAfterChange();
|
tags.RefreshAfterChange();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -57,7 +57,7 @@ public partial class TagsView : UserControl {
|
|||||||
var dialog = new DeleteTagConfirmDialog {
|
var dialog = new DeleteTagConfirmDialog {
|
||||||
DataContext = new DeleteTagConfirmViewModel(item.Name, item.UsageCount),
|
DataContext = new DeleteTagConfirmViewModel(item.Name, item.UsageCount),
|
||||||
};
|
};
|
||||||
confirmed = await dialog.ShowDialog<bool>(owner);
|
confirmed = await ModalWindow.ShowAsync<bool>(owner, dialog);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!confirmed) {
|
if (!confirmed) {
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ public partial class WorkspaceView : UserControl {
|
|||||||
var dialog = new ExportDoneDialog {
|
var dialog = new ExportDoneDialog {
|
||||||
DataContext = new ExportDoneViewModel(file.TryGetLocalPath() ?? file.Name),
|
DataContext = new ExportDoneViewModel(file.TryGetLocalPath() ?? file.Name),
|
||||||
};
|
};
|
||||||
await dialog.ShowDialog(owner);
|
await ModalWindow.ShowAsync(owner, dialog);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+10
-9
@@ -1,12 +1,13 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>WinExe</OutputType>
|
<OutputType>WinExe</OutputType>
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
<Version>0.1.0</Version>
|
<Version>0.2.0</Version>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
||||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||||
|
<ApplicationIcon>Assets\ykanban.ico</ApplicationIcon>
|
||||||
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
@@ -37,19 +38,19 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Avalonia" Version="11.3.6" />
|
<PackageReference Include="Avalonia" Version="11.3.22" />
|
||||||
<PackageReference Include="Avalonia.Desktop" Version="11.3.6" />
|
<PackageReference Include="Avalonia.Desktop" Version="11.3.22" />
|
||||||
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.3.6" />
|
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.3.22" />
|
||||||
<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
|
<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
|
||||||
<PackageReference Include="Avalonia.Diagnostics" Version="11.3.6">
|
<PackageReference Include="Avalonia.Diagnostics" Version="11.3.22">
|
||||||
<IncludeAssets Condition="'$(Configuration)' != 'Debug'">None</IncludeAssets>
|
<IncludeAssets Condition="'$(Configuration)' != 'Debug'">None</IncludeAssets>
|
||||||
<PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets>
|
<PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.1" />
|
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.1" />
|
||||||
<PackageReference Include="Semi.Avalonia" Version="11.2.1.10" />
|
<PackageReference Include="Semi.Avalonia" Version="11.3.14" />
|
||||||
<PackageReference Include="Semi.Avalonia.ColorPicker" Version="11.2.1.10" />
|
<PackageReference Include="Semi.Avalonia.ColorPicker" Version="11.3.14" />
|
||||||
<PackageReference Include="IconPacks.Avalonia.Lucide" Version="2.0.0" />
|
<PackageReference Include="IconPacks.Avalonia.Lucide" Version="2.0.0" />
|
||||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.20" />
|
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.12" />
|
||||||
<PackageReference Include="Pidgin" Version="3.5.1" />
|
<PackageReference Include="Pidgin" Version="3.5.1" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>CFBundleName</key>
|
||||||
|
<string>YKanBan</string>
|
||||||
|
<key>CFBundleDisplayName</key>
|
||||||
|
<string>YKanBan</string>
|
||||||
|
<key>CFBundleIdentifier</key>
|
||||||
|
<string>cn.blumia.code.yyc12345.ykanban</string>
|
||||||
|
<key>CFBundleIconFile</key>
|
||||||
|
<string>ykanban.icns</string>
|
||||||
|
<key>CFBundleExecutable</key>
|
||||||
|
<string>YKanBan</string>
|
||||||
|
<key>CFBundlePackageType</key>
|
||||||
|
<string>APPL</string>
|
||||||
|
<key>CFBundleShortVersionString</key>
|
||||||
|
<string>@VERSION@</string>
|
||||||
|
<key>CFBundleVersion</key>
|
||||||
|
<string>@VERSION@</string>
|
||||||
|
<key>CFBundleInfoDictionaryVersion</key>
|
||||||
|
<string>6.0</string>
|
||||||
|
<key>NSHighResolutionCapable</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
Binary file not shown.
Executable
+69
@@ -0,0 +1,69 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Packs one published RID into a release archive.
|
||||||
|
#
|
||||||
|
# packaging/package.sh <rid> <publish-dir> <output-dir> <version>
|
||||||
|
#
|
||||||
|
# win-x64 -> YKanBan-<version>-win-x64.zip (folder YKanBan-<version>-win-x64/)
|
||||||
|
# linux-x64 -> YKanBan-<version>-linux-x64.tar.gz (folder YKanBan-<version>-linux-x64/)
|
||||||
|
# osx-* -> YKanBan-<version>-<rid>.tar.gz (YKanBan.app bundle, ad-hoc signed when possible)
|
||||||
|
#
|
||||||
|
# tar.gz keeps the executable bit, which a plain zip artifact upload would lose.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
if [ "$#" -ne 4 ]; then
|
||||||
|
echo "usage: $0 <rid> <publish-dir> <output-dir> <version>" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
rid="$1"
|
||||||
|
publish_dir="$(cd "$2" && pwd)"
|
||||||
|
mkdir -p "$3"
|
||||||
|
output_dir="$(cd "$3" && pwd)"
|
||||||
|
version="$4"
|
||||||
|
script_dir="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
name="YKanBan-${version}-${rid}"
|
||||||
|
staging="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$staging"' EXIT
|
||||||
|
|
||||||
|
case "$rid" in
|
||||||
|
win-*)
|
||||||
|
cp -R "$publish_dir" "$staging/$name"
|
||||||
|
rm -f "$output_dir/$name.zip"
|
||||||
|
# 7-Zip ships on the Windows runners and writes '/' entry separators;
|
||||||
|
# Windows PowerShell 5.1's Compress-Archive writes '\', which breaks
|
||||||
|
# extraction outside Windows.
|
||||||
|
if ! command -v 7z > /dev/null 2>&1; then
|
||||||
|
echo "7z not found" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
(cd "$staging" && 7z a -tzip -bso0 -bsp0 "$output_dir/$name.zip" "$name")
|
||||||
|
;;
|
||||||
|
linux-*)
|
||||||
|
cp -R "$publish_dir" "$staging/$name"
|
||||||
|
chmod +x "$staging/$name/YKanBan"
|
||||||
|
tar -C "$staging" -czf "$output_dir/$name.tar.gz" "$name"
|
||||||
|
;;
|
||||||
|
osx-*)
|
||||||
|
app="$staging/YKanBan.app"
|
||||||
|
mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources"
|
||||||
|
cp -R "$publish_dir/." "$app/Contents/MacOS/"
|
||||||
|
cp "$script_dir/macos/ykanban.icns" "$app/Contents/Resources/"
|
||||||
|
chmod +x "$app/Contents/MacOS/YKanBan"
|
||||||
|
sed "s/@VERSION@/${version}/g" "$script_dir/macos/Info.plist" > "$app/Contents/Info.plist"
|
||||||
|
if command -v codesign > /dev/null 2>&1; then
|
||||||
|
# Ad-hoc signature for the bundle. Not fatal: the SDK already ad-hoc
|
||||||
|
# signs the apphost, which is all arm64 needs to run, and --deep may
|
||||||
|
# trip over the non-Mach-O files in Contents/MacOS.
|
||||||
|
if ! codesign --force --deep --sign - "$app"; then
|
||||||
|
echo "warning: ad-hoc signing of YKanBan.app failed; packing it unsigned" >&2
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
tar -C "$staging" -czf "$output_dir/$name.tar.gz" YKanBan.app
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "unsupported RID: $rid" >&2
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
echo "packed $rid -> $output_dir"
|
||||||
Reference in new issue
Block a user