Author SHA1 Message Date
yyc12345 62a3c96dc0 feat(m5): gui shell
- AppServices composition root: owns config, global workspace registry
  (app.db), platform path comparer and the LRU workspace connection pool;
  configuration persisted once at shutdown and services disposed
- AppDataPaths centralizes app.json / app.db locations; AppConfig gains
  a DefaultLanguage constant
- MVVM shell: MainWindowViewModel hosts SidebarViewModel and the current
  content page (welcome / workspace / localized failure state), mapping
  typed open failures to ResX messages
- SidebarViewModel: persistent workspace list with name-asc, name-desc
  and recently-updated sorting (selection persisted), open-project folder
  picker and initialize confirmation via Interaction<TInput,TOutput>
  handlers registered by the view; workspace entries open/remove
- Pages (welcome, workspace, message), dialogs (settings, about, confirm)
  with their view models; settings/about opened from the window
- App startup applies configured culture (RTL flow direction) and theme
  before the main window; forwarded IPC commands activate the window and
  switch workspace from the launch path
- Full UI text sourced from ResX in both en and zh-Hans; no hardcoded
  strings, theme colors via ThemeDictionaries
2026-10-02 18:02:22 +08:00
yyc12345 4fc8fdda6f feat(m4): single instance IPC
- LaunchCommand: ShowMain / OpenWorkspace(path), doubles as IPC message
- LaunchArguments: first non-blank arg wins, blank-only args -> ShowMain
- IpcProtocol: strict newline-line codec (show / open+path), tolerant
  of trailing-newline framing only
- SingleInstanceService: per-session named mutex decides primary;
  primary serves a named-pipe loop (decode -> dispatch -> ack) with
  handler failures contained; secondary retries send, exits on ack
- Program/App wiring: secondary forwards command and exits; primary
  activates the main window for forwarded commands (workspace switch
  deferred to the workspace UI milestone)
- 15 new tests (protocol codec, argument parsing); smoke-verified:
  instance 1 stays alive, instance 2 self-exits with code 0
2026-10-02 14:29:42 +08:00
yyc12345 b5614ff59b feat(m3): search and export
- Pidgin lexer: words, escaped phrases (strict closing), parens
- Full-Pidgin token-level parser, strict: malformed input throws
  SearchSyntaxException (BREAKING: lenient degradation removed from
  the plan; M7 must surface the error, M8 USAGE.md documents strict
  behavior)
- AST with reference-equality collection terms; structural
  comparison lives in the test-side SearchNodeComparer (YYC MARK
  note records the record-equality pitfall)
- SQL compiler: parameterized predicate over cards alias, LIKE
  escaping, COLLATE NOCASE exact matches, tag EXISTS / column IN
  subqueries
- Markdown exporter: ResX-driven templates, per-language export
  time AND card time patterns, kebab i18n file names, table cell
  escaping
- New RgbColor value type (byte components, strict #RRGGBB parse,
  canonical lowercase text) wired through TagModel and repository
- 57 new tests (grammar branches, strict errors, SQL end-to-end,
  en/zh export snapshots, color conversions)
2026-10-01 22:20:56 +08:00
yyc12345 e2bb0298b1 fix(m2): fix repository tag model issue 2026-10-01 21:34:58 +08:00
yyc12345 01367edaa9 feat(m2): repository layer
- Data models: ColumnModel, CardModel (tags loaded), TagModel
- PathComparer: platform-parameterized path normalization
  (case rule injected, trailing separator trimmed, roots kept)
- WorkspaceRepository: column/card/tag CRUD, card moves, tag
  assignment; single-transaction edit confirmation with atomic
  rollback; no-change confirmations write nothing; move refreshes
  last_edited_at but not card updated_at; write-through to app.db
  after every successful data write
- WorkspaceConnectionPool: fixed-capacity LRU session pool
  (lock + repository); eviction releases resources only; typed
  folder state errors; sidebar registry registration on open
- 35 new unit tests: cascade chains, atomicity, timestamp rules,
  LRU behavior, lock conflicts, path equivalence
2026-10-01 20:39:20 +08:00
yyc12345 31fc58d9c7 feat(m1): storage layer
- Shared SQLite plumbing: PRAGMAs (WAL/NORMAL/foreign_keys) and
  user_version migrations with typed SchemaVersionException
- Workspace folder: .ykanban initialization, empty schema with
  DDL-level constraints, preset column seeding (ResX-driven),
  exclusive lock file with holder diagnostics
- AppData folder: app.db workspace registry (injectable clock),
  app.json config store with kebab-case JSON names via explicit
  [JsonProperty]/[EnumMember], nested sections, corrupt-file backup
- ResX infrastructure under Assets/Locales (en + zh-Hans) with
  MSBuild strongly-typed public Resources class
- 54 unit tests: DDL constraints, migrations, PRAGMAs, lock
  exclusivity, config degradation, culture-aware presets
2026-10-01 18:17:47 +08:00
yyc12345 e934eb9629 refactor(m0): restructure project and install dependencies
- Clean Avalonia template content (ViewLocator, greeting, empty Models folder)
- Add YKanBan.Tests (MSTest 4.4.1) to solution
- Install packages per plan version table (Semi.Avalonia, Lucide icons,
  Microsoft.Data.Sqlite, Pidgin, Newtonsoft.Json 13.0.4 fallback)
2026-10-01 16:57:12 +08:00
yyc12345 6050a70f4b doc: submit plan 2026-10-01 16:44:18 +08:00
158 changed files with 3239 additions and 9387 deletions

No files matched your search

-2
View File
@@ -1,2 +0,0 @@
# Shell scripts run under bash on every CI runner, including Windows checkouts with autocrlf.
*.sh text eol=lf
-69
View File
@@ -1,69 +0,0 @@
# 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
on:
workflow_dispatch:
permissions:
contents: read
env:
DOTNET_NOLOGO: "true"
DOTNET_CLI_TELEMETRY_OPTOUT: "true"
jobs:
build:
name: ${{ matrix.rid }}
runs-on: ${{ matrix.os }}
strategy:
# Every RID stands on its own: one failure does not cancel the others.
fail-fast: false
matrix:
include:
- rid: win-x64
os: windows-latest
- rid: linux-x64
os: ubuntu-latest
- rid: osx-x64
os: macos-15-intel
- rid: osx-arm64
os: macos-15
defaults:
run:
shell: bash
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 10.0.x
- name: Build
run: dotnet build YKanBan.slnx -c Release
- name: Test
run: dotnet test YKanBan.slnx -c Release --no-build
- name: Publish
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
uses: actions/upload-artifact@v4
with:
name: ${{ steps.pack.outputs.name }}
path: dist/*
if-no-files-found: error
+1 -27
View File
@@ -2,30 +2,4 @@
My personal used local/offline kanban. My personal used local/offline kanban.
- Cross-platform desktop app (Windows / Linux / macOS) built with Avalonia. WIP.
- Git-like storage: the board lives in a `.ykanban` folder inside the project
folder it manages; start it with `ykanban <path>`.
- One board per workspace with columns, cards and colored tags; strict search
expressions (`tag:bug OR title:login`); Markdown export.
- English and Simplified Chinese interface; light, dark or system theme.
See **[USAGE.md](USAGE.md)** for installing, starting YKanBan, backups and
Git, and the full search syntax.
## Building
Requires the .NET 10 SDK.
```sh
dotnet build
dotnet test
dotnet run --project YKanBan -- <path>
```
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
-260
View File
@@ -1,260 +0,0 @@
# YKanBan usage
YKanBan is a local, offline kanban board. Like Git, it keeps its data in a
`.ykanban` folder inside the project folder it manages (the **workspace**).
Each YKanBan window manages exactly one workspace; several windows can run at
the same time on different workspaces.
- [Installing](#installing)
- [Starting YKanBan](#starting-ykanban)
- [macOS](#macos)
- [Workspaces, Git and backups](#workspaces-git-and-backups)
- [Search syntax](#search-syntax)
- [Settings file](#settings-file)
## Installing
Each release build is a self-contained archive; no .NET runtime is needed.
| Platform | Archive | Executable |
|---|---|---|
| Windows x64 | `YKanBan-<version>-win-x64.zip` | `YKanBan.exe` |
| Linux x64 | `YKanBan-<version>-linux-x64.tar.gz` | `YKanBan` |
| macOS Intel | `YKanBan-<version>-osx-x64.tar.gz` | `YKanBan.app` (see [macOS](#macos)) |
| macOS Apple silicon | `YKanBan-<version>-osx-arm64.tar.gz` | `YKanBan.app` (see [macOS](#macos)) |
Extract the archive anywhere. To type `ykanban <path>` as shown below, put the
executable on your `PATH` under that name, for example:
```sh
# Linux
ln -s /opt/YKanBan-<version>-linux-x64/YKanBan ~/.local/bin/ykanban
# macOS
ln -s /Applications/YKanBan.app/Contents/MacOS/YKanBan /usr/local/bin/ykanban
```
On Windows, add the extracted folder to `PATH`; `ykanban` then finds
`YKanBan.exe` because Windows ignores case.
## Starting YKanBan
The only way to start YKanBan is with the workspace path:
```sh
ykanban <path>
```
- Exactly one argument is accepted. A relative path is resolved against the
current working directory, so `ykanban .` opens the current folder (but see
[macOS](#macos) when starting through `open`).
- YKanBan looks for `.ykanban` **only in `<path>` itself**; it does not search
parent folders the way Git does.
- There are no command-line options. An argument starting with `-` is never
treated as a path; to open a folder whose name starts with `-`, write it as
`./-name`.
When the board cannot be shown, the whole window shows one of these pages
instead:
| Page | When |
|---|---|
| Invalid arguments | No argument, more than one argument, an empty or whitespace-only argument, an argument starting with `-` (including `--help`), or a path the operating system cannot represent (for example one containing a NUL character). Shows the usage line. |
| Folder not found | `<path>` does not exist or is not a folder. |
| No workspace here | `<path>` exists but has no `.ykanban`. The **Initialize workspace** button creates one, with the columns To Do / In Progress / Done (named in the current interface language). |
| Workspace locked | Another YKanBan window already has this workspace open. Close that window first. Also shown when another window takes the lock while you initialize. |
| Cannot open workspace | `.ykanban` exists but `ykanban.db` in it is missing (restore it from a backup, or delete `.ykanban` and initialize again; YKanBan never silently creates an empty board), the database was created by a newer YKanBan, is damaged or cannot be opened, or a file-system or permission error occurred (also when initializing fails for a reason other than the lock). The English error details can be selected and copied. |
The window title is `<workspace name> - YKanBan` while a workspace is open and
just `YKanBan` on these pages.
## macOS
The app is not notarized. After extracting, remove the download quarantine
once, or macOS refuses to open it:
```sh
xattr -dr com.apple.quarantine YKanBan.app
```
Double-clicking `YKanBan.app` starts it without a path, so it only shows the
**Invalid arguments** page. Start it from a terminal instead, either through
Launch Services or by running the executable inside the bundle:
```sh
open -n -a YKanBan --args /path/to/project
/Applications/YKanBan.app/Contents/MacOS/YKanBan /path/to/project
```
- Keep `-n`: without it, `open` only brings an already running YKanBan to
the front and drops the path, instead of starting another window.
- Give `open` an **absolute** path. An app started by `open` runs in `/`, so
`open -n -a YKanBan --args .` opens `/`, not the current folder. Running the
executable inside the bundle resolves relative paths normally.
- `open -a YKanBan` finds the app once it is in `/Applications` (or another
folder Launch Services knows about).
## Workspaces, Git and backups
- **Do not commit `.ykanban` to Git.** Add it to your global ignore file once,
so no repository picks it up. If `git config --global core.excludesFile`
prints a file, add the line `.ykanban/` to that file; otherwise create one:
```sh
echo ".ykanban/" >> ~/.gitignore_global
git config --global core.excludesFile ~/.gitignore_global
```
- **Back up or move all three database files together**: `ykanban.db`,
`ykanban.db-wal` and `ykanban.db-shm` in `.ykanban/`. Recent changes may
still be in the `-wal` file; copying only `ykanban.db` can lose them. The
simplest safe backup is to close YKanBan and copy the whole `.ykanban`
folder.
- **Network shares (SMB, NFS, …) are not supported.** The database and the
workspace lock rely on local file-system features that do not work reliably
over a network. YKanBan does not detect this; keep workspaces on a local
disk.
- `.ykanban/ykanban.lock` is held while a window has the workspace open and is
released automatically when YKanBan exits or crashes.
## Search syntax
Type an expression in the search box on the **Board** tab and click
**Search** (or press Enter). Searching only happens then; there is no search
while typing. The **×** button clears the box and shows every card again.
- Columns are always shown, even when none of their cards match.
- An empty or blank expression shows every card.
- After any change (adding, editing, moving or deleting cards, columns or
tags), the board re-runs the **last expression that searched successfully**,
not whatever is in the box at that moment. Cards that stop matching
disappear; new cards that do not match are not shown.
### Examples
| Expression | Finds cards… |
|---|---|
| `login` | whose title or content contains "login" |
| `login crash` | containing both words (anywhere in title or content) |
| `login OR signup` | containing either word |
| `tag:bug title:login` | tagged `bug` whose title contains "login" |
| `tag:bug OR tag:ui` | tagged `bug` or `ui` |
| `(tag:bug OR tag:ui) column:Done` | tagged `bug` or `ui` in the column titled "Done" |
| `"dark mode"` | whose title or content contains "dark mode" |
| `tag:"needs review"` | tagged `needs review` |
| `id:61` or `id:#61` | number 61 |
| `"http://example.com"` | containing the URL (a `:` must be quoted) |
| `"AND"` | containing the text "AND" |
### Grammar
```
query := orExpr
orExpr := andExpr ( OR andExpr )*
andExpr := operand ( (AND)? operand )* -- neighbours are joined by AND
operand := atom | '(' orExpr ')'
atom := word | phrase | qualifier
qualifier := key ':' value
key := tag | title | content | id | column
value := word | phrase -- tag / title / content / column
| '#'? digit+ -- id: a positive decimal integer
word := one or more characters, except whitespace and ( ) " : \ ;
not equal to AND or OR
phrase := '"' one or more characters '"' -- escapes: \" and \\
```
### Operators
- `AND` and `OR` are operators **only in uppercase**. `and` and `or` are
ordinary words.
- Writing words next to each other means `AND`: `a b` is `a AND b`.
- `AND` binds tighter than `OR`: `a OR b c` is `a OR (b AND c)`. Use
parentheses to group differently: `(a OR b) c`.
- To search for the literal text `AND` or `OR`, quote it: `"AND"`,
`tag:"OR"`.
- The search keywords (`AND`, `OR`, `tag`, `title`, `content`, `id`,
`column`) are always English, whatever the interface language. Qualifier
keys are lowercase only: `Tag:bug` is an unknown qualifier.
### What each atom matches
| Atom | Matches when |
|---|---|
| word or phrase | the card title **or** content contains the text |
| `title:` value | the card title contains the text |
| `content:` value | the card content contains the text |
| `tag:` value | the card has a tag whose name **equals** the text |
| `column:` value | the card is in a column whose title **equals** the text |
| `id:` value | the card number equals the value |
- A qualifier value can be a word (`tag:bug`) or a phrase
(`tag:"needs review"`). Use a phrase for values containing spaces, `(`,
`)`, `:` or `\`, and for the values `AND` / `OR`.
- `id:` takes an unquoted positive integer, optionally prefixed with `#`:
`id:61`, `id:#61`.
### Quoting and escapes
- A phrase is text in double quotes. Inside it, `\"` stands for a quote and
`\\` for a backslash; any other backslash is an error.
- Outside quotes, `\` is not allowed at all, and `:` always starts a
qualifier. Quote any text containing them: `"C:\\temp"`, `"a:b"`.
- A phrase cannot be empty, and must be separated from neighbouring words
and phrases by a space or a parenthesis: write `a "b"`, not `a"b"`.
- A qualifier's phrase value follows the `:` directly: `tag:"needs review"`,
not `tag: "needs review"`.
### Case
All matching ignores case, for letters of every language: `tag:BUG` finds
`bug`, and `ÄRGER` finds `ärger`. Text is otherwise compared literally: `%`,
`_` and `*` have no special meaning.
Tag names and column titles must be unique ignoring case for the letters A–Z
only. Two tags such as `Ä` and `ä` can therefore both exist, and `tag:ä`
matches both.
### Invalid expressions
An invalid expression does not search. A dialog shows "The query expression is
invalid. Details: …" followed by the parser's message (always in English).
After closing it, the box keeps your text for correcting and the board keeps
the previous result.
These are invalid:
| Problem | Example |
|---|---|
| Unbalanced parentheses | `(tag:bug`, `tag:bug)` |
| Parentheses nested more than 64 levels deep | `((((…a…))))` with 65 `(` |
| An operator with a missing side | `bug AND`, `OR bug` |
| Consecutive operators | `a AND OR b` |
| A qualifier without a value | `tag:` |
| `AND` / `OR` as an unquoted qualifier value | `tag:AND` (write `tag:"AND"`) |
| An unterminated phrase | `"dark mode` |
| An empty phrase | `""`, `tag:""` |
| A phrase touching other text | `a"b"`, `"a"b`, `"a""b"` |
| A space between a qualifier and its phrase value | `tag: "needs review"` |
| An invalid escape in a phrase | `tag:"a\x"` |
| A backslash outside a phrase | `C:\temp` |
| An unknown qualifier key | `label:bug`, `Tag:bug`, `http://x` |
| An unquoted value containing `:` | `title:a:b` |
| An `id:` value that is not an unquoted positive integer | `id:abc`, `id:0`, `id:"61"` |
## Settings file
Settings (language, theme, card sort order, column width and the confirmation
switches) are stored in `app.json`:
| Platform | Location |
|---|---|
| Windows | `%APPDATA%\YKanBan\app.json` |
| Linux, macOS | `~/.config/YKanBan/app.json` (`$XDG_CONFIG_HOME/YKanBan/app.json` when that is set) |
- The file is written when YKanBan exits, and only if a setting was changed in
that session. With several windows open, the last one closed after changing
a setting wins.
- A language change takes effect after restarting YKanBan; a theme change
applies immediately.
- If the file cannot be parsed, it is saved as `app.json.bak` and the defaults
are used. A single invalid value falls back to its default; the other
values are kept.
@@ -1,60 +0,0 @@
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));
}
}
+72 -287
View File
@@ -1,16 +1,13 @@
using System.Globalization; using System.Globalization;
using System.Text;
using YKanBan.Export; using YKanBan.Export;
using YKanBan.Models; using YKanBan.Models;
namespace YKanBan.Tests.Export; namespace YKanBan.Tests.Export;
/// <summary> /// <summary>
/// Tests for the Markdown exporter. Mutates the global /// Tests for the Markdown exporter. Mutates the global Resources.Culture,
/// <see cref="Resources.Culture"/>, therefore marked do-not-parallelize. /// therefore marked DoNotParallelize. Asserts real localized output for
/// Expected documents are assembled from the same ResX template keys as the /// both supported languages.
/// exporter (plus fixed fixture values), so no localized text is hard-coded
/// here.
/// </summary> /// </summary>
[TestClass] [TestClass]
[DoNotParallelize] [DoNotParallelize]
@@ -18,34 +15,15 @@ public class MarkdownExporterTests
{ {
private static readonly DateTimeOffset ExportedAt = new(2026, 9, 30, 14, 25, 37, TimeSpan.Zero); private static readonly DateTimeOffset ExportedAt = new(2026, 9, 30, 14, 25, 37, TimeSpan.Zero);
/// <summary> /// <summary>A local wall-clock moment, matching the exporter's conversion path.</summary>
/// Builds a local wall-clock moment, matching the exporter's conversion path.
/// </summary>
/// <param name="year">The year.</param>
/// <param name="month">The month.</param>
/// <param name="day">The day.</param>
/// <param name="hour">The hour.</param>
/// <param name="minute">The minute.</param>
/// <returns>The local time.</returns>
private static DateTimeOffset Local(int year, int month, int day, int hour, int minute) => private static DateTimeOffset Local(int year, int month, int day, int hour, int minute) =>
new DateTimeOffset(new DateTime(year, month, day, hour, minute, 0)).ToLocalTime(); new DateTimeOffset(new DateTime(year, month, day, hour, minute, 0)).ToLocalTime();
/// <summary> /// <summary>Unix seconds for a local wall-clock time.</summary>
/// Converts a local wall-clock time to Unix seconds.
/// </summary>
/// <param name="year">The year.</param>
/// <param name="month">The month.</param>
/// <param name="day">The day.</param>
/// <param name="hour">The hour.</param>
/// <param name="minute">The minute.</param>
/// <returns>The Unix timestamp.</returns>
private static long UnixTimeOf(int year, int month, int day, int hour, int minute) => private static long UnixTimeOf(int year, int month, int day, int hour, int minute) =>
Local(year, month, day, hour, minute).ToUnixTimeSeconds(); Local(year, month, day, hour, minute).ToUnixTimeSeconds();
/// <summary> /// <summary>Builds the board fixture: one working column with two cards, one empty column, two tags.</summary>
/// Builds the board fixture: one working column with two cards, one empty column and two tags.
/// </summary>
/// <returns>The columns, cards and tag/usage tuples.</returns>
private static (IReadOnlyList<ColumnModel> Columns, IReadOnlyList<CardModel> Cards, IReadOnlyList<(TagModel, long)> Tags) CreateBoard() private static (IReadOnlyList<ColumnModel> Columns, IReadOnlyList<CardModel> Cards, IReadOnlyList<(TagModel, long)> Tags) CreateBoard()
{ {
long created = UnixTimeOf(2026, 9, 1, 10, 0); long created = UnixTimeOf(2026, 9, 1, 10, 0);
@@ -67,79 +45,14 @@ public class MarkdownExporterTests
return (columns, cards, tags); return (columns, cards, tags);
} }
/// <summary> private static string Export(CultureInfo culture)
/// Renders the fixture board with the exporter under the current culture.
/// </summary>
/// <returns>The produced Markdown document.</returns>
private static string ExportBoard()
{
(IReadOnlyList<ColumnModel> columns, IReadOnlyList<CardModel> cards, IReadOnlyList<(TagModel, long)> tags) = CreateBoard();
return MarkdownExporter.Export("MyRepo", columns, cards, tags, ExportedAt);
}
/// <summary>
/// Assembles the expected document from the ResX template keys under the current culture.
/// </summary>
/// <param name="culture">The UI culture.</param>
/// <returns>The expected Markdown document.</returns>
private static string BuildExpected(CultureInfo 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_TimePattern, culture);
var builder = new StringBuilder();
// Header: workspace name and the export timestamp.
builder.AppendLine(string.Format(culture, Resources.Export_WorkspaceHeading, "MyRepo"));
builder.AppendLine(string.Format(
culture, Resources.Export_ExportedAtLine, ExportedAt.ToString(Resources.Export_TimePattern, culture)));
builder.AppendLine();
// First column with its two cards.
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, "In Progress", 2));
builder.AppendLine("The work column");
builder.AppendLine();
builder.AppendLine("### #61 Fix login");
builder.AppendLine("Body text");
builder.AppendLine(string.Format(culture, Resources.Export_TagsLine, "`bug` `ui`"));
builder.AppendLine(string.Format(culture, Resources.Export_CreatedModifiedLine, created, updated));
builder.AppendLine();
builder.AppendLine("### #62");
builder.AppendLine(string.Format(culture, Resources.Export_CreatedModifiedLine, created, updated));
builder.AppendLine();
// Empty column is kept.
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, "Empty", 0));
builder.AppendLine();
// Tag summary table.
builder.AppendLine(Resources.Export_TagsSummaryHeading);
builder.AppendLine(Resources.Export_TagsTableHeader);
builder.AppendLine("|---|---|---|---|");
builder.AppendLine("| bug | #ff0000 | | 1 |");
builder.AppendLine("| ui | #00ff00 | Interface work | 1 |");
return builder.ToString();
}
/// <summary>
/// Normalizes the expected document, built with the platform newline, to the exporter's LF.
/// </summary>
/// <param name="text">The text to normalize.</param>
/// <returns>The text with normalized line endings.</returns>
private static string Normalize(string text) => text.Replace("\r\n", "\n");
/// <summary>
/// Asserts that the exporter output matches the resource-built expected document.
/// </summary>
/// <param name="culture">The UI culture to test.</param>
private static void AssertOutputMatches(CultureInfo culture)
{ {
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try
{ {
Resources.Culture = culture; Resources.Culture = culture;
Assert.AreEqual(Normalize(BuildExpected(culture)), ExportBoard()); (IReadOnlyList<ColumnModel> columns, IReadOnlyList<CardModel> cards, IReadOnlyList<(TagModel, long)> tags) = CreateBoard();
return MarkdownExporter.Export("MyRepo", columns, cards, tags, ExportedAt);
} }
finally finally
{ {
@@ -147,16 +60,73 @@ public class MarkdownExporterTests
} }
} }
private static string Normalize(string text) => text.Replace("\r\n", "\n");
[TestMethod] [TestMethod]
public void EnglishOutputMatchesTemplate() public void EnglishOutputMatchesTemplate()
{ {
AssertOutputMatches(new CultureInfo("en")); string created = Local(2026, 9, 1, 10, 0).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
string updated = Local(2026, 9, 28, 18, 30).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
string expected = Normalize($"""
# MyRepo
> Exported at: 2026-09-30 14:25:37
## Column: In Progress (2)
The work column
### #61 Fix login
Body text
- Tags: `bug` `ui`
- Created: {created} Modified: {updated}
### #62
- Created: {created} Modified: {updated}
## Column: Empty (0)
## Tags
| Name | Color | Description | Usage |
|---|---|---|---|
| bug | #ff0000 | | 1 |
| ui | #00ff00 | Interface work | 1 |
""");
Assert.AreEqual(expected + "\n", Normalize(Export(new CultureInfo("en"))));
} }
[TestMethod] [TestMethod]
public void ChineseOutputMatchesTemplate() public void ChineseOutputMatchesTemplate()
{ {
AssertOutputMatches(new CultureInfo("zh-Hans")); var chinese = new CultureInfo("zh-Hans");
string created = Local(2026, 9, 1, 10, 0).ToString("yyyy年M月d日 HH:mm", chinese);
string updated = Local(2026, 9, 28, 18, 30).ToString("yyyy年M月d日 HH:mm", chinese);
string expected = Normalize($"""
# MyRepo
> 导出时间:2026年9月30日 14:25
## 列:In Progress(2)
The work column
### #61 Fix login
Body text
- 标签:`bug` `ui`
- 创建:{created} 修改:{updated}
### #62
- 创建:{created} 修改:{updated}
## 列:Empty(0)
## 标签总表
| 名称 | 颜色 | 描述 | 使用数 |
|---|---|---|---|
| bug | #ff0000 | | 1 |
| ui | #00ff00 | Interface work | 1 |
""");
Assert.AreEqual(expected + "\n", Normalize(Export(new CultureInfo("zh-Hans"))));
} }
[TestMethod] [TestMethod]
@@ -166,14 +136,10 @@ public class MarkdownExporterTests
try try
{ {
Resources.Culture = new CultureInfo("en"); Resources.Culture = new CultureInfo("en");
Assert.AreEqual( Assert.AreEqual("MyRepo-export-20260930-142537.md", MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt),
MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
Resources.Culture = new CultureInfo("zh-Hans"); Resources.Culture = new CultureInfo("zh-Hans");
Assert.AreEqual( Assert.AreEqual("MyRepo-导出-20260930-142537.md", MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt),
MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
} }
finally finally
{ {
@@ -189,194 +155,13 @@ public class MarkdownExporterTests
{ {
Resources.Culture = new CultureInfo("en"); Resources.Culture = new CultureInfo("en");
var tag = new TagModel(1, "a|b", RgbColor.Parse("#112233"), "first\nsecond"); var tag = new TagModel(1, "a|b", RgbColor.Parse("#112233"), "first\nsecond");
string markdown = MarkdownExporter.Export( string markdown = MarkdownExporter.Export("W",
"W",
[new ColumnModel(1, "C", string.Empty, 1, 1)], [new ColumnModel(1, "C", string.Empty, 1, 1)],
[], [],
[(tag, 0L)], [(tag, 0L)],
ExportedAt); ExportedAt);
StringAssert.Contains(markdown, "| a\\|b | #112233 | first<br>second | 0 |"); StringAssert.Contains(markdown, "| a\\|b | #112233 | first second | 0 |");
}
finally
{
Resources.Culture = original;
}
}
[TestMethod]
public void TagTableCellsEscapeBackslashesSoAPipeAfterOneStaysEscaped()
{
CultureInfo? original = Resources.Culture;
try
{
Resources.Culture = new CultureInfo("en");
var tag = new TagModel(1, @"a\|b", RgbColor.Parse("#112233"), @"C:\temp\");
string markdown = MarkdownExporter.Export(
"W",
[new ColumnModel(1, "C", string.Empty, 1, 1)],
[],
[(tag, 0L)],
ExportedAt);
StringAssert.Contains(markdown, @"| a\\\|b | #112233 | C:\\temp\\ | 0 |");
}
finally
{
Resources.Culture = original;
}
}
[TestMethod]
[DataRow("plain", "`plain`")]
[DataRow("a`b", "``a`b``")]
[DataRow("a``b`c", "```a``b`c```")]
[DataRow("`x", "`` `x ``")]
[DataRow("x`", "`` x` ``")]
[DataRow("`", "`` ` ``")]
public void TagNamesUseLongEnoughBacktickFence(string name, string expected)
{
CultureInfo? original = Resources.Culture;
try
{
Resources.Culture = new CultureInfo("en");
var tag = new TagModel(1, name, 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, string.Format(Resources.Culture, Resources.Export_TagsLine, expected) + "\n");
}
finally
{
Resources.Culture = original;
}
}
[TestMethod]
public void CardBodyAndColumnDescriptionAreVerbatim()
{
CultureInfo? original = Resources.Culture;
try
{
Resources.Culture = new CultureInfo("en");
string markdown = MarkdownExporter.Export(
"W",
[new ColumnModel(1, "C", "line one\n# not a heading | pipe", 1, 1)],
[new CardModel(1, 1, "T", "body\n\n## raw | `md`", 1, 1, [])],
[],
ExportedAt);
StringAssert.Contains(markdown, "\nline one\n# not a heading | pipe\n");
StringAssert.Contains(markdown, "\nbody\n\n## raw | `md`\n");
}
finally
{
Resources.Culture = original;
}
}
[TestMethod]
public void LineEndingsAreLfOnEveryPlatform()
{
CultureInfo? original = Resources.Culture;
try
{
Resources.Culture = new CultureInfo("en");
string markdown = MarkdownExporter.Export(
"W",
[new ColumnModel(1, "C", "one\r\ntwo\rthree", 1, 1)],
[new CardModel(1, 1, "T", "a\r\nb", 1, 1, [])],
[],
ExportedAt);
Assert.IsFalse(markdown.Contains('\r'));
StringAssert.Contains(markdown, "\none\ntwo\nthree\n");
StringAssert.Contains(markdown, "\na\nb\n");
}
finally
{
Resources.Culture = original;
}
}
[TestMethod]
public void ColumnTitleIsCollapsedToOneLine()
{
CultureInfo? original = Resources.Culture;
try
{
Resources.Culture = new CultureInfo("en");
string markdown = MarkdownExporter.Export(
"W",
[new ColumnModel(1, "To\r\nDo\nNow", string.Empty, 1, 1)],
[],
[],
ExportedAt);
string heading = string.Format(Resources.Culture, Resources.Export_ColumnHeading, "To Do Now", 0);
StringAssert.Contains(markdown, "\n" + heading + "\n");
}
finally
{
Resources.Culture = original;
}
}
[TestMethod]
public void ColumnsAndCardsAreExportedInIdOrder()
{
CultureInfo? original = Resources.Culture;
try
{
Resources.Culture = new CultureInfo("en");
string markdown = MarkdownExporter.Export(
"W",
[new ColumnModel(2, "Second", string.Empty, 1, 1), new ColumnModel(1, "First", string.Empty, 1, 1)],
[
new CardModel(9, 1, "Nine", string.Empty, 1, 1, []),
new CardModel(3, 2, "Three", string.Empty, 1, 1, []),
new CardModel(4, 1, "Four", string.Empty, 1, 1, []),
],
[],
ExportedAt);
int first = markdown.IndexOf(string.Format(Resources.Culture, Resources.Export_ColumnHeading, "First", 2), StringComparison.Ordinal);
int second = markdown.IndexOf(string.Format(Resources.Culture, Resources.Export_ColumnHeading, "Second", 1), StringComparison.Ordinal);
int four = markdown.IndexOf("### #4 Four", StringComparison.Ordinal);
int nine = markdown.IndexOf("### #9 Nine", StringComparison.Ordinal);
int three = markdown.IndexOf("### #3 Three", StringComparison.Ordinal);
Assert.IsTrue(first >= 0 && first < four && four < nine && nine < second && second < three, markdown);
}
finally
{
Resources.Culture = original;
}
}
[TestMethod]
[DataRow("en", "2026-09-30 14:25:37", "2026-09-01 10:00:05")]
[DataRow("zh-Hans", "2026年9月30日 14:25", "2026年9月1日 10:00")]
public void TimestampsUseThePlannedPerLanguageFormat(string language, string exportedAt, string cardTime)
{
CultureInfo? original = Resources.Culture;
try
{
Resources.Culture = new CultureInfo(language);
long cardSeconds = new DateTimeOffset(new DateTime(2026, 9, 1, 10, 0, 5)).ToUnixTimeSeconds();
var exportMoment = new DateTimeOffset(new DateTime(2026, 9, 30, 14, 25, 37));
string markdown = MarkdownExporter.Export(
"W",
[new ColumnModel(1, "C", string.Empty, 1, 1)],
[new CardModel(1, 1, "T", string.Empty, cardSeconds, cardSeconds, [])],
[],
exportMoment);
StringAssert.Contains(markdown, string.Format(Resources.Culture, Resources.Export_ExportedAtLine, exportedAt));
StringAssert.Contains(markdown, string.Format(Resources.Culture, Resources.Export_CreatedModifiedLine, cardTime, cardTime));
} }
finally finally
{ {
+87
View File
@@ -0,0 +1,87 @@
using YKanBan.Ipc;
namespace YKanBan.Tests.Ipc;
/// <summary>Tests for the IPC wire protocol codec.</summary>
[TestClass]
public class IpcProtocolTests
{
[TestMethod]
public void ShowMainEncodesAsSingleLine()
{
Assert.AreEqual("show\n", IpcProtocol.Encode(new LaunchCommand.ShowMain()));
}
[TestMethod]
public void OpenWorkspaceEncodesCommandAndPathLines()
{
Assert.AreEqual(
"open\nD:\\my repo\n",
IpcProtocol.Encode(new LaunchCommand.OpenWorkspace(@"D:\my repo")));
}
[TestMethod]
public void RoundTripPreservesCommands()
{
LaunchCommand[] commands =
[
new LaunchCommand.ShowMain(),
new LaunchCommand.OpenWorkspace(@"D:\my repo"),
new LaunchCommand.OpenWorkspace("/home/user/仓库"),
];
foreach (LaunchCommand command in commands)
{
Assert.AreEqual(command, IpcProtocol.Decode(IpcProtocol.Encode(command)));
}
}
[TestMethod]
public void DecodeToleratesMissingTrailingNewline()
{
Assert.AreEqual(new LaunchCommand.ShowMain(), IpcProtocol.Decode("show"));
Assert.AreEqual(
new LaunchCommand.OpenWorkspace(@"C:\x"),
IpcProtocol.Decode("open\nC:\\x"));
}
[TestMethod]
public void DecodePreservesPathsWithSpacesAndUnicode()
{
LaunchCommand command = IpcProtocol.Decode("open\nD:\\我的 仓库\n");
Assert.AreEqual(new LaunchCommand.OpenWorkspace(@"D:\我的 仓库"), command);
}
[TestMethod]
public void DecodeRejectsEmptyPayload()
{
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode(string.Empty));
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode("\n"));
}
[TestMethod]
public void DecodeRejectsUnknownCommand()
{
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode("frobnicate\n"));
}
[TestMethod]
public void DecodeRejectsOpenWithoutPath()
{
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode("open\n"));
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode("open"));
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode("open\n\n"));
}
[TestMethod]
public void DecodeRejectsContentAfterShow()
{
Assert.ThrowsExactly<FormatException>(() => IpcProtocol.Decode("show\nextra\n"));
}
[TestMethod]
public void EncodeRejectsNullCommand()
{
Assert.ThrowsExactly<InvalidOperationException>(() => IpcProtocol.Encode(null!));
}
}
+47
View File
@@ -0,0 +1,47 @@
using YKanBan.Ipc;
namespace YKanBan.Tests.Ipc;
/// <summary>Tests for command-line argument parsing.</summary>
[TestClass]
public class LaunchArgumentsTests
{
[TestMethod]
public void NoArgumentsYieldShowMain()
{
Assert.AreEqual(new LaunchCommand.ShowMain(), LaunchArguments.Parse([]));
}
[TestMethod]
public void BlankArgumentsOnlyYieldShowMain()
{
Assert.AreEqual(new LaunchCommand.ShowMain(), LaunchArguments.Parse(["", " "]));
}
[TestMethod]
public void SingleArgumentBecomesWorkspacePath()
{
Assert.AreEqual(
new LaunchCommand.OpenWorkspace(@"D:\repo"),
LaunchArguments.Parse([@"D:\repo"]));
}
[TestMethod]
public void PathWithSpacesIsPreserved()
{
Assert.AreEqual(
new LaunchCommand.OpenWorkspace(@"D:\my repo\ws"),
LaunchArguments.Parse([@"D:\my repo\ws"]));
}
[TestMethod]
public void FirstMeaningfulArgumentWins()
{
Assert.AreEqual(
new LaunchCommand.OpenWorkspace(@"D:\a"),
LaunchArguments.Parse([@"D:\a", @"D:\b"]));
Assert.AreEqual(
new LaunchCommand.OpenWorkspace(@"D:\b"),
LaunchArguments.Parse(["", @"D:\b", @"D:\c"]));
}
}
@@ -1,76 +0,0 @@
using YKanBan.Launching;
namespace YKanBan.Tests.Launching;
/// <summary>
/// Tests for the <c>ykanban &lt;path&gt;</c> command-line contract across its
/// three branches: no argument, one valid path, and invalid input.
/// </summary>
[TestClass]
public class LaunchArgumentsTests
{
[TestMethod]
public void NoArgumentsIsRejected()
{
Assert.IsFalse(LaunchArguments.TryParse([], out string? path));
Assert.IsNull(path);
}
[TestMethod]
public void BlankArgumentIsRejected()
{
Assert.IsFalse(LaunchArguments.TryParse([" "], out string? path));
Assert.IsNull(path);
}
[TestMethod]
public void MoreThanOneArgumentIsRejected()
{
Assert.IsFalse(LaunchArguments.TryParse(["a", "b"], out string? path));
Assert.IsNull(path);
}
[TestMethod]
public void SingleAbsolutePathIsAccepted()
{
string absolute = Path.Combine(Path.GetTempPath(), "Repo", "MyProject");
bool parsed = LaunchArguments.TryParse([absolute], out string? path);
Assert.IsTrue(parsed);
Assert.AreEqual(absolute, path);
}
[TestMethod]
public void RelativePathResolvesAgainstCurrentDirectory()
{
Assert.IsTrue(LaunchArguments.TryParse(["MyProject"], out string? path));
Assert.AreEqual(Path.Combine(Environment.CurrentDirectory, "MyProject"), path);
Assert.IsTrue(LaunchArguments.TryParse(["."], out path));
Assert.AreEqual(Path.GetFullPath(Environment.CurrentDirectory), path);
}
[TestMethod]
[DataRow("-")]
[DataRow("-x")]
[DataRow("--help")]
[DataRow("--path=foo")]
public void OptionLikeArgumentIsRejected(string argument)
{
Assert.IsFalse(LaunchArguments.TryParse([argument], out string? path));
Assert.IsNull(path);
}
[TestMethod]
public void OptionAlongsidePathIsRejected()
{
Assert.IsFalse(LaunchArguments.TryParse(["--help", "MyProject"], out string? path));
Assert.IsNull(path);
}
[TestMethod]
public void MalformedPathIsRejected()
{
Assert.IsFalse(LaunchArguments.TryParse(["a\0b"], out string? path));
Assert.IsNull(path);
}
}
-46
View File
@@ -1,46 +0,0 @@
using YKanBan.Models;
using YKanBan.Storage.AppData;
namespace YKanBan.Tests.Models;
/// <summary>
/// Tests for the in-column card display order: each sort option plus the id
/// ascending tie-breaker.
/// </summary>
[TestClass]
public class CardOrderingTests
{
private static CardModel Card(long id, string title = "", long updatedAt = 0) =>
new(id, 1, title, string.Empty, 0, updatedAt, []);
private static long[] Ids(IEnumerable<CardModel> cards, CardSortOption option) =>
CardOrdering.Sort(cards, option).Select(card => card.Id).ToArray();
[TestMethod]
public void IdSortsAscending()
{
CollectionAssert.AreEqual(new[] { 1L, 2L, 3L }, Ids([Card(3), Card(1), Card(2)], CardSortOption.Id));
}
[TestMethod]
public void UpdatedAtSortsMostRecentFirstThenById()
{
CardModel[] cards = [Card(1, updatedAt: 10), Card(2, updatedAt: 30), Card(3, updatedAt: 10), Card(4, updatedAt: 20)];
CollectionAssert.AreEqual(new[] { 2L, 4L, 1L, 3L }, Ids(cards, CardSortOption.UpdatedAt));
}
[TestMethod]
public void TitleSortsByCodePointWithEmptyFirstThenById()
{
CardModel[] cards = [Card(1, "b"), Card(2, "B"), Card(3, ""), Card(4, "a"), Card(5, "b")];
CollectionAssert.AreEqual(new[] { 3L, 2L, 4L, 1L, 5L }, Ids(cards, CardSortOption.Title));
}
[TestMethod]
public void TitleSortsSupplementaryCharactersAfterBmpPrivateUse()
{
// U+1F600 is a surrogate pair in UTF-16, so ordinal comparison would put it before U+E000.
CardModel[] cards = [Card(1, "\U0001F600"), Card(2, "\uE000")];
CollectionAssert.AreEqual(new[] { 2L, 1L }, Ids(cards, CardSortOption.Title));
}
}
+33 -38
View File
@@ -2,76 +2,71 @@ using YKanBan.Models;
namespace YKanBan.Tests.Models; namespace YKanBan.Tests.Models;
/// <summary> /// <summary>Tests for the RGB color value type and its #RRGGBB text conversions.</summary>
/// Tests for the RGB color value type: component storage and the text
/// boundary in both directions.
/// </summary>
[TestClass] [TestClass]
public class RgbColorTests public class RgbColorTests
{ {
[TestMethod] [TestMethod]
public void ParseSplitsComponents() public void ParseExtractsComponents()
{ {
RgbColor color = RgbColor.Parse("#102030"); RgbColor color = RgbColor.Parse("#ff0a00");
Assert.AreEqual((byte)0x10, color.R); Assert.AreEqual(new RgbColor(0xFF, 0x0A, 0x00), color);
Assert.AreEqual((byte)0x20, color.G);
Assert.AreEqual((byte)0x30, color.B);
} }
[TestMethod] [TestMethod]
[DataRow("#a1B2c3")] public void ParseAcceptsUppercaseAndMixedCaseHex()
[DataRow("#A1B2C3")]
[DataRow("#a1b2c3")]
public void ParseIsCaseInsensitive(string text)
{ {
Assert.AreEqual(new RgbColor(0xA1, 0xB2, 0xC3), RgbColor.Parse(text)); Assert.AreEqual(new RgbColor(0xAB, 0xCD, 0xEF), RgbColor.Parse("#ABCDEF"));
Assert.AreEqual(new RgbColor(0xAB, 0xCD, 0xEF), RgbColor.Parse("#aBcDeF"));
} }
[TestMethod] [TestMethod]
[DataRow("ff0000")]
[DataRow("#ff000")]
[DataRow("#ff00000")]
[DataRow("#gg0000")]
[DataRow("#ff 000")]
[DataRow(" #ff0000")]
[DataRow("#ff0000 ")]
[DataRow("#")]
[DataRow("")] [DataRow("")]
[DataRow("112233")] public void TryParseRejectsMalformedText(string text)
[DataRow("#11223")]
[DataRow("#1122334")]
[DataRow("#GGGGGG")]
[DataRow("#12345g")]
[DataRow(" #112233")]
[DataRow("#112233 ")]
public void ParseRejectsMalformedText(string text)
{ {
Assert.ThrowsExactly<FormatException>(() => RgbColor.Parse(text)); Assert.IsFalse(RgbColor.TryParse(text, out _));
} }
[TestMethod] [TestMethod]
public void TryParseRejectsNull() public void TryParseRejectsNull()
{ {
Assert.IsFalse(RgbColor.TryParse(null, out RgbColor color)); Assert.IsFalse(RgbColor.TryParse(null, out _));
Assert.AreEqual(default, color);
} }
[TestMethod] [TestMethod]
public void TryParseAcceptsValidText() public void ParseThrowsFormatExceptionForMalformedText()
{ {
Assert.IsTrue(RgbColor.TryParse("#010203", out RgbColor color)); Assert.ThrowsExactly<FormatException>(() => RgbColor.Parse("red"));
Assert.AreEqual(new RgbColor(1, 2, 3), color);
} }
[TestMethod] [TestMethod]
public void ToStringUsesCanonicalLowercase() public void ToStringProducesCanonicalLowercaseForm()
{ {
Assert.AreEqual("#ff0a00", new RgbColor(0xFF, 0x0A, 0x00).ToString()); Assert.AreEqual("#ee0a0a", new RgbColor(0xEE, 0x0A, 0x0A).ToString());
}
[TestMethod] // Uppercase input normalizes to the canonical lowercase output.
public void TextRoundTrips() Assert.AreEqual("#ee0a0a", RgbColor.Parse("#EE0A0A").ToString());
{
var color = new RgbColor(0x12, 0xAB, 0xCD);
Assert.AreEqual(color, RgbColor.Parse(color.ToString()));
} }
[TestMethod] [TestMethod]
public void EqualityComparesComponents() public void EqualityComparesComponents()
{ {
Assert.AreEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 3)); Assert.AreEqual(RgbColor.Parse("#ff0000"), RgbColor.Parse("#FF0000"));
Assert.AreNotEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 4)); Assert.AreNotEqual(RgbColor.Parse("#ff0000"), RgbColor.Parse("#ff0001"));
}
[TestMethod]
public void TextRoundTripPreservesColor()
{
RgbColor original = new(0x12, 0x34, 0x56);
Assert.AreEqual(original, RgbColor.Parse(original.ToString()));
} }
} }
@@ -0,0 +1,93 @@
using YKanBan.Platform;
using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Platform;
/// <summary>Tests for path normalization and platform-parameterized comparison.</summary>
[TestClass]
public class PathComparerTests
{
[TestMethod]
public void OrdinalComparerTreatsCaseAsSignificant()
{
// Unix-style rule, injected so it is testable on any host.
var comparer = new PathComparer(ignoreCase: false);
Assert.IsFalse(comparer.Equals(@"C:\A", @"C:\a"));
}
[TestMethod]
public void IgnoreCaseComparerTreatsCaseAsInsignificant()
{
// Windows-style rule.
var comparer = new PathComparer(ignoreCase: true);
Assert.IsTrue(comparer.Equals(@"C:\A", @"c:\a"));
}
[TestMethod]
public void EqualPathsProduceEqualHashCodes()
{
var comparer = new PathComparer(ignoreCase: true);
Assert.AreEqual(
comparer.GetHashCode(@"C:\Users\Data\MyRepo"),
comparer.GetHashCode(@"c:\users\data\myrepo"));
}
[TestMethod]
public void RelativeSegmentsCollapse()
{
var comparer = new PathComparer(ignoreCase: true);
using var directory = new TempDirectory();
string viaParent = Path.Combine(directory.FullPath, "x", "..", "a");
string direct = Path.Combine(directory.FullPath, "a");
Assert.IsTrue(comparer.Equals(viaParent, direct));
}
[TestMethod]
public void SeparatorStylesUnify()
{
var comparer = new PathComparer(ignoreCase: true);
Assert.IsTrue(comparer.Equals(@"C:\a/b\c", @"C:\a\b\c"));
}
[TestMethod]
public void TrailingSeparatorIsTrimmedForNonRoots()
{
var comparer = new PathComparer(ignoreCase: true);
using var directory = new TempDirectory();
string withTrailing = directory.FullPath + Path.DirectorySeparatorChar;
Assert.IsTrue(comparer.Equals(withTrailing, directory.FullPath));
}
[TestMethod]
public void NormalizeReturnsCanonicalAbsoluteForm()
{
var comparer = new PathComparer(ignoreCase: false);
using var directory = new TempDirectory();
string withRelativeSegment = Path.Combine(directory.FullPath, "sub", "..");
Assert.AreEqual(directory.FullPath, comparer.Normalize(withRelativeSegment));
}
[TestMethod]
public void RootPathKeepsItsTrailingSeparator()
{
var comparer = new PathComparer(ignoreCase: true);
Assert.AreEqual(@"C:\", comparer.Normalize(@"C:\"));
Assert.AreEqual(@"C:\x", comparer.Normalize(@"C:\x\"));
}
[TestMethod]
public void ForCurrentPlatformMatchesHostRule()
{
PathComparer comparer = PathComparer.ForCurrentPlatform();
Assert.AreEqual(
OperatingSystem.IsWindows(),
comparer.Equals(@"C:\Same", @"c:\same"));
}
}
-21
View File
@@ -1,21 +0,0 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace YKanBan.Tests;
/// <summary>
/// Smoke tests verifying that the test project is correctly wired to the
/// application project and that the test runner can discover and execute tests.
/// </summary>
[TestClass]
public class ProjectReferenceTests
{
/// <summary>
/// Verifies that a type defined in the application assembly can be
/// referenced from the test project.
/// </summary>
[TestMethod]
public void ApplicationAssemblyIsReferenceable()
{
Assert.IsNotNull(typeof(App));
}
}
+9 -24
View File
@@ -3,23 +3,17 @@ using YKanBan.Search;
namespace YKanBan.Tests.Search; namespace YKanBan.Tests.Search;
/// <summary> /// <summary>
/// Structural comparer for search AST nodes, used by assertions only. The AST /// Structural comparer for search AST nodes, used by assertions only. The
/// records compare by reference for their Terms collections by design (see the /// AST records compare by reference for their Terms collections by design
/// YYC MARK note in SearchNodes.cs), so tests provide equality explicitly. /// (see the YYC MARK note in SearchNodes.cs), so tests provide equality
/// explicitly.
/// </summary> /// </summary>
public sealed class SearchNodeComparer : IEqualityComparer<SearchNode> public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
{ {
/// <summary> /// <summary>Shared comparer instance.</summary>
/// Gets the shared comparer instance.
/// </summary>
public static SearchNodeComparer Instance { get; } = new(); public static SearchNodeComparer Instance { get; } = new();
/// <summary> /// <summary>Determines structural equality of two nodes.</summary>
/// Determines structural equality of two nodes.
/// </summary>
/// <param name="x">The first node.</param>
/// <param name="y">The second node.</param>
/// <returns><see langword="true"/> when the nodes are structurally equal.</returns>
public bool Equals(SearchNode? x, SearchNode? y) public bool Equals(SearchNode? x, SearchNode? y)
{ {
if (ReferenceEquals(x, y)) if (ReferenceEquals(x, y))
@@ -44,26 +38,17 @@ public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
}; };
} }
/// <summary> /// <summary>Not supported: the comparer exists for assertions, not hashing.</summary>
/// Not supported: the comparer exists for assertions, not hashing.
/// </summary>
/// <param name="obj">The node.</param>
/// <returns>Never returns.</returns>
public int GetHashCode(SearchNode obj) => public int GetHashCode(SearchNode obj) =>
throw new NotSupportedException("Structural comparison for assertions only; hashing is not supported."); throw new NotSupportedException("Structural comparison for assertions only; hashing is not supported.");
/// <summary> /// <summary>Order-sensitive element-wise comparison.</summary>
/// Order-sensitive element-wise comparison.
/// </summary>
/// <param name="x">The first sequence.</param>
/// <param name="y">The second sequence.</param>
/// <returns><see langword="true"/> when both sequences match element-wise.</returns>
private static bool SequencesEqual(IReadOnlyList<SearchNode> x, IReadOnlyList<SearchNode> y) private static bool SequencesEqual(IReadOnlyList<SearchNode> x, IReadOnlyList<SearchNode> y)
{ {
if (x.Count != y.Count) if (x.Count != y.Count)
{ {
return false; return false;
} }
return x.Zip(y).All(pair => Instance.Equals(pair.First, pair.Second)); return Enumerable.Zip(x, y, (a, b) => (a, b)).All(pair => Instance.Equals(pair.a, pair.b));
} }
} }
+12 -202
View File
@@ -4,17 +4,12 @@ namespace YKanBan.Tests.Search;
/// <summary> /// <summary>
/// Tests for the search parser: the full grammar branches plus the strict /// Tests for the search parser: the full grammar branches plus the strict
/// failure behavior (malformed input always throws /// failure behavior (malformed input always throws SearchSyntaxException).
/// <see cref="SearchSyntaxException"/>).
/// </summary> /// </summary>
[TestClass] [TestClass]
public class SearchQueryParserTests public class SearchQueryParserTests
{ {
/// <summary> /// <summary>Parses and asserts structural equality against the expected AST.</summary>
/// Parses and asserts structural equality against the expected AST.
/// </summary>
/// <param name="expected">The expected AST.</param>
/// <param name="text">The search text.</param>
private static void AssertParsesTo(SearchNode expected, string text) private static void AssertParsesTo(SearchNode expected, string text)
{ {
SearchNode? parsed = SearchQueryParser.Parse(text); SearchNode? parsed = SearchQueryParser.Parse(text);
@@ -22,17 +17,12 @@ public class SearchQueryParserTests
Assert.AreEqual(expected, parsed, SearchNodeComparer.Instance); Assert.AreEqual(expected, parsed, SearchNodeComparer.Instance);
} }
/// <summary> /// <summary>Asserts that the input violates the grammar.</summary>
/// Asserts that the input violates the grammar.
/// </summary>
/// <param name="text">The search text.</param>
private static void AssertSyntaxError(string text) private static void AssertSyntaxError(string text)
{ {
Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse(text)); Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse(text));
} }
#region Successful parses
[TestMethod] [TestMethod]
public void BlankInputReturnsNull() public void BlankInputReturnsNull()
{ {
@@ -116,22 +106,13 @@ public class SearchQueryParserTests
AssertParsesTo(new SearchNode.FreeText("hello world"), "\"hello world\""); AssertParsesTo(new SearchNode.FreeText("hello world"), "\"hello world\"");
} }
[TestMethod]
public void QuotedOperatorKeywordIsFreeText()
{
// A quoted AND/OR is literal text, not an operator.
AssertParsesTo(new SearchNode.FreeText("AND"), "\"AND\"");
AssertParsesTo(
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("OR")]),
"a \"OR\"");
}
[TestMethod] [TestMethod]
public void PhraseSupportsEscapes() public void PhraseSupportsEscapes()
{ {
// Escaped quote and escaped backslash. // Escaped quote, escaped backslash, and a lone backslash kept literally.
AssertParsesTo(new SearchNode.FreeText("a\"b"), "\"a\\\"b\""); AssertParsesTo(new SearchNode.FreeText("a\"b"), "\"a\\\"b\"");
AssertParsesTo(new SearchNode.FreeText("a\\b"), "\"a\\\\b\""); AssertParsesTo(new SearchNode.FreeText("a\\b"), "\"a\\\\b\"");
AssertParsesTo(new SearchNode.FreeText("C:\\x"), "\"C:\\x\"");
} }
[TestMethod] [TestMethod]
@@ -146,13 +127,6 @@ public class SearchQueryParserTests
AssertParsesTo(new SearchNode.TagName("a b"), "tag:\"a b\""); AssertParsesTo(new SearchNode.TagName("a b"), "tag:\"a b\"");
} }
[TestMethod]
public void QuotedQualifierValueMayContainColonsAndOperators()
{
AssertParsesTo(new SearchNode.TagName("a:b"), "tag:\"a:b\"");
AssertParsesTo(new SearchNode.TagName("AND"), "tag:\"AND\"");
}
[TestMethod] [TestMethod]
public void TitleAndContentQualifiers() public void TitleAndContentQualifiers()
{ {
@@ -170,51 +144,21 @@ public class SearchQueryParserTests
public void IdQualifierParsesNumber() public void IdQualifierParsesNumber()
{ {
AssertParsesTo(new SearchNode.CardId(42), "id:42"); AssertParsesTo(new SearchNode.CardId(42), "id:42");
AssertParsesTo(new SearchNode.CardId(61), "id:#61"); AssertParsesTo(new SearchNode.CardId(12), "id:\"12\"");
} }
[TestMethod] [TestMethod]
public void QuotedTextWithColonIsFreeText() public void QualifierKeysAreCaseSensitive()
{ {
AssertParsesTo(new SearchNode.FreeText("http://x"), "\"http://x\""); AssertParsesTo(new SearchNode.FreeText("Tag:x"), "Tag:x");
} }
[TestMethod]
public void WordMayContainHashAndPunctuation()
{
AssertParsesTo(new SearchNode.FreeText("#61"), "#61");
AssertParsesTo(new SearchNode.FreeText("c#/.net"), "c#/.net");
}
#endregion
#region Strict failures
[TestMethod] [TestMethod]
public void UnterminatedPhraseIsAnError() public void UnterminatedPhraseIsAnError()
{ {
AssertSyntaxError("\"abc def"); AssertSyntaxError("\"abc def");
} }
[TestMethod]
public void TrailingUnterminatedPhraseIsAnError()
{
AssertSyntaxError("a \"abc");
}
[TestMethod]
public void InvalidEscapeInPhraseIsAnError()
{
// A bare backslash (not followed by a quote or another backslash) is invalid.
AssertSyntaxError("\"a\\b\"");
}
[TestMethod]
public void InvalidEscapeInQualifierPhraseIsAnError()
{
AssertSyntaxError("tag:\"a\\x\"");
}
[TestMethod] [TestMethod]
public void UnbalancedOpenParenIsAnError() public void UnbalancedOpenParenIsAnError()
{ {
@@ -227,33 +171,6 @@ public class SearchQueryParserTests
AssertSyntaxError("a)"); AssertSyntaxError("a)");
} }
[TestMethod]
public void NestingAtTheDepthLimitParses()
{
int depth = SearchQueryParser.MaxNestingDepth;
AssertParsesTo(new SearchNode.FreeText("a"), new string('(', depth) + "a" + new string(')', depth));
}
[TestMethod]
public void NestingBeyondTheDepthLimitIsAnError()
{
int depth = SearchQueryParser.MaxNestingDepth + 1;
AssertSyntaxError(new string('(', depth) + "a" + new string(')', depth));
}
[TestMethod]
public void SequentialGroupsDoNotCountTowardsTheDepthLimit()
{
string groups = string.Join(" ", Enumerable.Repeat("(a)", SearchQueryParser.MaxNestingDepth + 1));
Assert.IsNotNull(SearchQueryParser.Parse(groups));
}
[TestMethod]
public void VeryDeepNestingIsAnErrorRatherThanACrash()
{
AssertSyntaxError(new string('(', 100_000) + "a" + new string(')', 100_000));
}
[TestMethod] [TestMethod]
public void EmptyParensAreAnError() public void EmptyParensAreAnError()
{ {
@@ -291,122 +208,15 @@ public class SearchQueryParserTests
} }
[TestMethod] [TestMethod]
public void SpacedQualifierValueIsAnError() public void NonNumericIdIsAnError()
{ {
AssertSyntaxError("tag: bug"); AssertSyntaxError("id:12x");
}
[TestMethod]
[DataRow("tag: \"x\"")]
[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]
public void UnknownQualifierKeyIsAnError()
{
AssertSyntaxError("foo:bar");
}
[TestMethod]
public void QualifierKeysAreCaseSensitive()
{
// "Tag" is a key-like prefix but not the known lowercase "tag", so it is unknown.
AssertSyntaxError("Tag:x");
} }
[TestMethod] [TestMethod]
public void SyntaxErrorCarriesDescriptiveMessage() public void SyntaxErrorCarriesDescriptiveMessage()
{ {
SearchSyntaxException exception = Assert.ThrowsExactly<SearchSyntaxException>( SearchSyntaxException ex = Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse("a AND"));
() => SearchQueryParser.Parse("a AND")); Assert.IsFalse(string.IsNullOrEmpty(ex.Message));
Assert.IsFalse(string.IsNullOrEmpty(exception.Message));
} }
#endregion
} }
+9 -29
View File
@@ -1,20 +1,19 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Search; using YKanBan.Search;
using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Search; namespace YKanBan.Tests.Search;
/// <summary> /// <summary>
/// Tests for the query-to-SQL compiler, executed end-to-end against a fixture /// Tests for the query-to-SQL compiler, executed end-to-end against a
/// workspace database. /// fixture workspace database.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class SearchSqlCompilerTests public class SearchSqlCompilerTests
{ {
/// <summary> /// <summary>Owns a workspace with a fixed card/tag fixture.</summary>
/// Owns a workspace with a fixed card/tag fixture.
/// </summary>
private sealed class SearchFixture : IDisposable private sealed class SearchFixture : IDisposable
{ {
public TempDirectory Directory { get; } = new(); public TempDirectory Directory { get; } = new();
@@ -49,11 +48,7 @@ public class SearchSqlCompilerTests
Connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath); Connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath);
} }
/// <summary> /// <summary>Runs a query and returns the ids of the matching cards.</summary>
/// Runs a query and returns the ids of the matching cards.
/// </summary>
/// <param name="queryText">The search text.</param>
/// <returns>The matching card ids in id order.</returns>
public List<long> Search(string queryText) public List<long> Search(string queryText)
{ {
SearchNode? query = SearchQueryParser.Parse(queryText); SearchNode? query = SearchQueryParser.Parse(queryText);
@@ -169,25 +164,10 @@ public class SearchSqlCompilerTests
{ {
CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("x")); CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("x"));
// One folded parameter shared by the title and content tests.
StringAssert.Contains(compiled.Predicate, "$p0"); StringAssert.Contains(compiled.Predicate, "$p0");
Assert.AreEqual(1, compiled.Parameters.Count); StringAssert.Contains(compiled.Predicate, "$p1");
Assert.AreEqual("x", compiled.Parameters[0].Value); Assert.AreEqual(2, compiled.Parameters.Count);
} Assert.AreEqual("%x%", compiled.Parameters[0].Value);
Assert.AreEqual("%x%", compiled.Parameters[1].Value);
[TestMethod]
public void MatchingFoldsNonAsciiCase()
{
using var fixture = new SearchFixture();
SqliteTestHelper.Exec(fixture.Connection, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Érable', '', 1, 1);");
SqliteTestHelper.Exec(fixture.Connection, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (3, 'Ärger', 'Straße ΣΟΦΙΑ', 1, 1);");
SqliteTestHelper.Exec(fixture.Connection, "INSERT INTO tags (name, color, description) VALUES ('Äpfel', '#123456', '');");
SqliteTestHelper.Exec(fixture.Connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (5, 4);");
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("ärger"));
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("title:ÄRGER"));
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("content:σοφια"));
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("tag:äpfel"));
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("column:érable"));
} }
} }
+13
View File
@@ -0,0 +1,13 @@
namespace YKanBan.Tests;
[TestClass]
public class SmokeTests
{
[TestMethod]
public void ThirdPartyPackagesResolve()
{
Assert.IsNotNull(typeof(Pidgin.Parser).Assembly);
Assert.IsNotNull(typeof(Newtonsoft.Json.JsonConvert).Assembly);
Assert.IsNotNull(typeof(Microsoft.Data.Sqlite.SqliteConnection).Assembly);
}
}
@@ -3,25 +3,22 @@ using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.AppData; namespace YKanBan.Tests.Storage.AppData;
/// <summary> /// <summary>Tests for app.json load/save and its degradation rules.</summary>
/// Tests for app.json round-tripping, kebab-case naming and graceful
/// degradation on a missing or corrupt file.
/// </summary>
[TestClass] [TestClass]
public class AppConfigStoreTests public class AppConfigStoreTests
{ {
[TestMethod] [TestMethod]
public void LoadMissingFileReturnsDefaults() public void MissingFileYieldsDefaults()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
var store = new AppConfigStore(Path.Combine(directory.FullPath, "app.json")); var store = new AppConfigStore(Path.Combine(directory.FullPath, "app.json"));
AppConfig config = store.Load(); AppConfig config = store.Load();
Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version); Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version);
Assert.AreEqual(AppConfig.DefaultLanguage, config.Language); Assert.AreEqual("en", config.Language);
Assert.AreEqual(ThemeOption.FollowSystem, config.Theme); Assert.AreEqual(ThemeOption.FollowSystem, config.Theme);
Assert.AreEqual(CardSortOption.Id, config.Sort.Card); Assert.AreEqual(CardSortOption.Id, config.Sort.Card);
Assert.AreEqual(SidebarSortOption.NameAsc, config.Sort.Sidebar);
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset); Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset);
Assert.AreEqual(320, config.ColumnWidth.CustomPixels); Assert.AreEqual(320, config.ColumnWidth.CustomPixels);
Assert.IsTrue(config.Confirmations.DeleteCard); Assert.IsTrue(config.Confirmations.DeleteCard);
@@ -31,49 +28,136 @@ public class AppConfigStoreTests
} }
[TestMethod] [TestMethod]
public void LoadCorruptFileBacksUpAndReturnsDefaults() public void CorruptJsonIsBackedUpAndDefaultsAreUsed()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, "{ this is not valid json"); File.WriteAllText(path, "{{{ not json");
var store = new AppConfigStore(path);
AppConfig config = store.Load();
Assert.AreEqual("en", config.Language);
Assert.IsTrue(File.Exists(path + ".bak"));
Assert.AreEqual("{{{ not json", File.ReadAllText(path + ".bak"));
}
[TestMethod]
public void WrongShapeJsonIsBackedUpAndDefaultsAreUsed()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, "[1, 2, 3]");
var store = new AppConfigStore(path); var store = new AppConfigStore(path);
AppConfig config = store.Load(); AppConfig config = store.Load();
Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version); Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version);
Assert.IsTrue(File.Exists(path + ".bak")); Assert.IsTrue(File.Exists(path + ".bak"));
Assert.AreEqual("{ this is not valid json", File.ReadAllText(path + ".bak"));
} }
[TestMethod] [TestMethod]
public void LoadJsonNullReturnsDefaults() public void SaveAndLoadRoundTripsAllSettings()
{
using var directory = new TempDirectory();
var store = new AppConfigStore(Path.Combine(directory.FullPath, "app.json"));
store.Save(new AppConfig
{
Language = "zh-Hans",
Theme = ThemeOption.Dark,
Sort = new SortSettings
{
Card = CardSortOption.Title,
Sidebar = SidebarSortOption.RecentlyUpdated,
},
ColumnWidth = new ColumnWidthSettings
{
Preset = ColumnWidthPreset.Custom,
CustomPixels = 500,
},
Confirmations = new ConfirmationSettings
{
DeleteCard = false,
DeleteColumn = false,
DeleteTag = false,
DiscardEdit = false,
},
});
AppConfig loaded = store.Load();
Assert.AreEqual("zh-Hans", loaded.Language);
Assert.AreEqual(ThemeOption.Dark, loaded.Theme);
Assert.AreEqual(CardSortOption.Title, loaded.Sort.Card);
Assert.AreEqual(SidebarSortOption.RecentlyUpdated, loaded.Sort.Sidebar);
Assert.AreEqual(ColumnWidthPreset.Custom, loaded.ColumnWidth.Preset);
Assert.AreEqual(500, loaded.ColumnWidth.CustomPixels);
Assert.IsFalse(loaded.Confirmations.DeleteCard);
Assert.IsFalse(loaded.Confirmations.DeleteColumn);
Assert.IsFalse(loaded.Confirmations.DeleteTag);
Assert.IsFalse(loaded.Confirmations.DiscardEdit);
}
[TestMethod]
public void SaveWritesKebabCaseNamesAndVersionField()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, "null");
var store = new AppConfigStore(path); var store = new AppConfigStore(path);
Assert.AreEqual(AppConfig.CurrentFormatVersion, store.Load().Version); store.Save(new AppConfig());
string json = File.ReadAllText(path);
// Keys and enum values are serialized in kebab-case; "version" is the migration hook.
Assert.IsTrue(json.Contains($"\"version\": {AppConfig.CurrentFormatVersion}"));
Assert.IsTrue(json.Contains("\"language\": \"en\""));
Assert.IsTrue(json.Contains("\"theme\": \"follow-system\""));
Assert.IsTrue(json.Contains("\"sort\":"));
Assert.IsTrue(json.Contains("\"card\": \"id\""));
Assert.IsTrue(json.Contains("\"sidebar\": \"name-asc\""));
Assert.IsTrue(json.Contains("\"column-width\":"));
Assert.IsTrue(json.Contains("\"preset\": \"standard\""));
Assert.IsTrue(json.Contains("\"custom-pixels\": 320"));
Assert.IsTrue(json.Contains("\"confirmations\":"));
Assert.IsTrue(json.Contains("\"delete-card\": true"));
Assert.IsTrue(json.Contains("\"delete-column\": true"));
Assert.IsTrue(json.Contains("\"delete-tag\": true"));
Assert.IsTrue(json.Contains("\"discard-edit\": true"));
} }
[TestMethod] [TestMethod]
public void LoadReadsKebabCaseKeysAndEnumValues() public void MissingSectionsFallBackToTheirDefaults()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, $$""" File.WriteAllText(path, $$"""
{ {
"version": {{AppConfig.CurrentFormatVersion}}, "version": {{AppConfig.CurrentFormatVersion}},
"language": "zh-Hans", "language": "zh-Hans"
"theme": "dark",
"sort": { "card": "title" },
"column-width": { "preset": "custom", "custom-pixels": 400 },
"confirmations": {
"delete-card": false,
"delete-column": false,
"delete-tag": false,
"discard-edit": false
} }
""");
var store = new AppConfigStore(path);
AppConfig config = store.Load();
// The present field loads; absent sections each fall back to defaults.
Assert.AreEqual("zh-Hans", config.Language);
Assert.AreEqual(CardSortOption.Id, config.Sort.Card);
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset);
Assert.IsTrue(config.Confirmations.DeleteCard);
}
[TestMethod]
public void LoadPreservesUnknownFieldsTolerantly()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
// A newer version writes an unknown field plus a known one.
File.WriteAllText(path, $$"""
{
"version": {{AppConfig.CurrentFormatVersion}},
"language": "zh-Hans",
"some-future-field": 42
} }
"""); """);
var store = new AppConfigStore(path); var store = new AppConfigStore(path);
@@ -81,225 +165,5 @@ public class AppConfigStoreTests
AppConfig config = store.Load(); AppConfig config = store.Load();
Assert.AreEqual("zh-Hans", config.Language); Assert.AreEqual("zh-Hans", config.Language);
Assert.AreEqual(ThemeOption.Dark, config.Theme);
Assert.AreEqual(CardSortOption.Title, config.Sort.Card);
Assert.AreEqual(ColumnWidthPreset.Custom, config.ColumnWidth.Preset);
Assert.AreEqual(400, config.ColumnWidth.CustomPixels);
Assert.IsFalse(config.Confirmations.DeleteCard);
Assert.IsFalse(config.Confirmations.DeleteColumn);
Assert.IsFalse(config.Confirmations.DeleteTag);
Assert.IsFalse(config.Confirmations.DiscardEdit);
}
[TestMethod]
public void LoadMissingSectionsFillsDefaults()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, $$"""{ "version": {{AppConfig.CurrentFormatVersion}} }""");
var store = new AppConfigStore(path);
AppConfig config = store.Load();
Assert.IsNotNull(config.Sort);
Assert.IsNotNull(config.ColumnWidth);
Assert.IsNotNull(config.Confirmations);
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset);
}
[TestMethod]
public void SaveWritesKebabCaseKeysAndEnumValues()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
var store = new AppConfigStore(path);
var config = new AppConfig
{
Theme = ThemeOption.FollowSystem,
Sort = new SortSettings { Card = CardSortOption.UpdatedAt },
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Custom, CustomPixels = 500 },
Confirmations = new ConfirmationSettings { DeleteColumn = false },
};
store.Save(config);
string json = File.ReadAllText(path);
StringAssert.Contains(json, "\"delete-column\"");
StringAssert.Contains(json, "\"discard-edit\"");
StringAssert.Contains(json, "\"custom-pixels\"");
StringAssert.Contains(json, "\"follow-system\"");
StringAssert.Contains(json, "\"updated-at\"");
// No member-name CamelCase must leak into the file.
Assert.IsFalse(json.Contains("deleteColumn", StringComparison.Ordinal));
Assert.IsFalse(json.Contains("CustomPixels", StringComparison.Ordinal));
}
[TestMethod]
public void SaveThenLoadRoundTrips()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
var store = new AppConfigStore(path);
var config = new AppConfig
{
Language = "zh-Hans",
Theme = ThemeOption.Light,
Sort = new SortSettings { Card = CardSortOption.Title },
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Wide },
Confirmations = new ConfirmationSettings { DiscardEdit = false },
};
store.Save(config);
AppConfig reloaded = store.Load();
Assert.AreEqual(config.Language, reloaded.Language);
Assert.AreEqual(config.Theme, reloaded.Theme);
Assert.AreEqual(config.Sort.Card, reloaded.Sort.Card);
Assert.AreEqual(config.ColumnWidth.Preset, reloaded.ColumnWidth.Preset);
Assert.AreEqual(config.Confirmations.DiscardEdit, reloaded.Confirmations.DiscardEdit);
}
[TestMethod]
public void LoadNonObjectRootBacksUpAndReturnsDefaults()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, "[1, 2]");
var store = new AppConfigStore(path);
Assert.AreEqual(AppConfig.DefaultLanguage, store.Load().Language);
Assert.AreEqual("[1, 2]", File.ReadAllText(path + ".bak"));
}
[TestMethod]
[DataRow("\"theme\": \"sepia\"")]
[DataRow("\"theme\": 1")]
[DataRow("\"theme\": {}")]
[DataRow("\"language\": \"fr\"")]
[DataRow("\"language\": \"zh-hans\"")]
[DataRow("\"language\": 5")]
[DataRow("\"sort\": { \"card\": \"created-at\" }")]
[DataRow("\"sort\": 7")]
[DataRow("\"column-width\": { \"preset\": \"huge\", \"custom-pixels\": 159 }")]
[DataRow("\"column-width\": { \"custom-pixels\": 721 }")]
[DataRow("\"column-width\": { \"custom-pixels\": \"wide\" }")]
[DataRow("\"confirmations\": { \"delete-card\": \"nope\" }")]
[DataRow("\"version\": \"one\"")]
public void InvalidFieldFallsBackAloneWithoutBackup(string invalidMember)
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
// The valid fields are non-defaults, so any whole-file fallback would show.
File.WriteAllText(path, $$"""
{
"theme": "dark",
"confirmations": { "discard-edit": false },
{{invalidMember}}
}
""");
var store = new AppConfigStore(path);
AppConfig config = store.Load();
Assert.IsFalse(File.Exists(path + ".bak"));
AppConfig defaults = new();
Assert.AreEqual(invalidMember.Contains("theme") ? defaults.Theme : ThemeOption.Dark, config.Theme);
if (!invalidMember.Contains("confirmations"))
{
Assert.IsFalse(config.Confirmations.DiscardEdit);
}
Assert.AreEqual(defaults.Language, config.Language);
Assert.AreEqual(defaults.Sort.Card, config.Sort.Card);
Assert.AreEqual(defaults.ColumnWidth.Preset, config.ColumnWidth.Preset);
Assert.AreEqual(defaults.ColumnWidth.CustomPixels, config.ColumnWidth.CustomPixels);
Assert.AreEqual(defaults.Confirmations.DeleteCard, config.Confirmations.DeleteCard);
Assert.AreEqual(defaults.Version, config.Version);
}
[TestMethod]
public void InvalidNestedFieldKeepsItsSiblings()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, """{ "column-width": { "preset": "bogus", "custom-pixels": 500 } }""");
AppConfig config = new AppConfigStore(path).Load();
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset);
Assert.AreEqual(500, config.ColumnWidth.CustomPixels);
}
[TestMethod]
public void ColumnWidthBoundsAreInclusive()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, """{ "column-width": { "custom-pixels": 160 } }""");
Assert.AreEqual(160, new AppConfigStore(path).Load().ColumnWidth.CustomPixels);
File.WriteAllText(path, """{ "column-width": { "custom-pixels": 720 } }""");
Assert.AreEqual(720, new AppConfigStore(path).Load().ColumnWidth.CustomPixels);
}
[TestMethod]
public void UnchangedConfigurationIsNotWritten()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
var store = new AppConfigStore(path);
AppConfig config = store.Load();
Assert.IsFalse(store.SaveIfChanged(config));
Assert.IsFalse(File.Exists(path));
}
[TestMethod]
public void FieldFallbackAloneDoesNotRewriteTheFile()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
const string original = """{ "theme": "sepia" }""";
File.WriteAllText(path, original);
var store = new AppConfigStore(path);
AppConfig config = store.Load();
Assert.IsFalse(store.SaveIfChanged(config));
Assert.AreEqual(original, File.ReadAllText(path));
}
[TestMethod]
public void ChangedConfigurationIsWrittenOnce()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
var store = new AppConfigStore(path);
AppConfig config = store.Load();
config.Sort.Card = CardSortOption.UpdatedAt;
Assert.IsTrue(store.SaveIfChanged(config));
Assert.AreEqual(CardSortOption.UpdatedAt, new AppConfigStore(path).Load().Sort.Card);
// Saved state is the new baseline.
Assert.IsFalse(store.SaveIfChanged(config));
}
[TestMethod]
public void ChangeRevertedWithinSessionIsNotWritten()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
var store = new AppConfigStore(path);
AppConfig config = store.Load();
config.Theme = ThemeOption.Dark;
config.Theme = ThemeOption.FollowSystem;
Assert.IsFalse(store.SaveIfChanged(config));
Assert.IsFalse(File.Exists(path));
} }
} }
@@ -0,0 +1,136 @@
using Microsoft.Data.Sqlite;
using YKanBan.Storage;
using YKanBan.Storage.AppData;
using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.AppData;
/// <summary>Tests for the global app.db workspace registry.</summary>
[TestClass]
public class AppDatabaseTests
{
private static string DatabasePath(TempDirectory directory)
=> Path.Combine(directory.FullPath, "app.db");
[TestMethod]
public void UpsertInsertsRowWithTimestamps()
{
using var directory = new TempDirectory();
long now = 1000;
using var db = new AppDatabase(DatabasePath(directory), () => now);
db.UpsertWorkspace(@"C:\work\repo");
IReadOnlyList<WorkspaceRecord> records = db.GetWorkspaces();
Assert.AreEqual(1, records.Count);
Assert.AreEqual(@"C:\work\repo", records[0].Path);
Assert.AreEqual(1000L, records[0].AddedAt);
Assert.AreEqual(1000L, records[0].LastEditedAt);
}
[TestMethod]
public void RepeatedUpsertKeepsOriginalAddedAt()
{
using var directory = new TempDirectory();
long now = 1000;
using var db = new AppDatabase(DatabasePath(directory), () => now);
db.UpsertWorkspace(@"C:\work\repo");
now = 2000;
db.UpsertWorkspace(@"C:\work\repo");
WorkspaceRecord record = db.GetWorkspaces().Single();
Assert.AreEqual(1000L, record.AddedAt);
Assert.AreEqual(2000L, record.LastEditedAt);
}
[TestMethod]
public void TouchRefreshesLastEditedAt()
{
using var directory = new TempDirectory();
long now = 1000;
using var db = new AppDatabase(DatabasePath(directory), () => now);
db.UpsertWorkspace(@"C:\work\repo");
now = 2500;
db.TouchLastEdited(@"C:\work\repo");
WorkspaceRecord record = db.GetWorkspaces().Single();
Assert.AreEqual(1000L, record.AddedAt);
Assert.AreEqual(2500L, record.LastEditedAt);
}
[TestMethod]
public void TouchOnUnknownPathRegistersTheWorkspace()
{
using var directory = new TempDirectory();
long now = 3000;
using var db = new AppDatabase(DatabasePath(directory), () => now);
// Self-healing: touching an unregistered workspace still leaves a valid row.
db.TouchLastEdited(@"C:\work\other");
WorkspaceRecord record = db.GetWorkspaces().Single();
Assert.AreEqual(3000L, record.AddedAt);
Assert.AreEqual(3000L, record.LastEditedAt);
}
[TestMethod]
public void RemoveDeletesTheRow()
{
using var directory = new TempDirectory();
using var db = new AppDatabase(DatabasePath(directory));
db.UpsertWorkspace(@"C:\work\repo");
db.RemoveWorkspace(@"C:\work\repo");
Assert.AreEqual(0, db.GetWorkspaces().Count);
}
[TestMethod]
public void RowsPersistAcrossReopen()
{
using var directory = new TempDirectory();
string path = DatabasePath(directory);
using (var db = new AppDatabase(path, () => 1000))
{
db.UpsertWorkspace(@"C:\work\repo");
}
using var reopened = new AppDatabase(path, () => 9999);
WorkspaceRecord record = reopened.GetWorkspaces().Single();
Assert.AreEqual(@"C:\work\repo", record.Path);
Assert.AreEqual(1000L, record.AddedAt);
}
[TestMethod]
public void OpenMigratesToCurrentSchemaVersion()
{
using var directory = new TempDirectory();
string path = DatabasePath(directory);
using (var db = new AppDatabase(path))
{
}
using var raw = new SqliteConnection($"Data Source={path}");
raw.Open();
Assert.AreEqual(AppDatabase.CurrentSchemaVersion, SqliteDatabase.ReadUserVersion(raw));
}
[TestMethod]
public void OpenAppliesWalJournalMode()
{
using var directory = new TempDirectory();
string path = DatabasePath(directory);
using (var db = new AppDatabase(path))
{
}
// WAL is a persistent property of the database file: a plain new
// connection reports it without any PRAGMA replay.
using var raw = new SqliteConnection($"Data Source={path}");
raw.Open();
Assert.AreEqual("wal", SqliteTestHelper.ScalarString(raw, "PRAGMA journal_mode;"));
}
}
+58 -71
View File
@@ -1,127 +1,114 @@
using Microsoft.Data.Sqlite;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage; namespace YKanBan.Tests.Storage;
/// <summary> /// <summary>Tests for PRAGMA application and user_version migration machinery.</summary>
/// Tests for the shared SQLite plumbing: mandatory PRAGMAs and the
/// user_version-driven migration runner.
/// </summary>
[TestClass] [TestClass]
public class SqliteDatabaseTests public class SqliteDatabaseTests
{ {
private static readonly SchemaMigration[] V1Only =
[
new SchemaMigration(1, "v1", "CREATE TABLE t1 (id INTEGER PRIMARY KEY);"),
];
private static readonly SchemaMigration[] V1AndV2 =
[
new SchemaMigration(1, "v1", "CREATE TABLE t1 (id INTEGER PRIMARY KEY);"),
new SchemaMigration(2, "v2", "CREATE TABLE t2 (id INTEGER PRIMARY KEY);"),
];
[TestMethod] [TestMethod]
public void OpenAppliesMandatoryPragmas() public void OpenAppliesMandatedPragmas()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "pragmas.db"); string dbPath = Path.Combine(directory.FullPath, "test.db");
using SqliteConnection connection = SqliteDatabase.Open(databasePath, []); using var connection = SqliteDatabase.Open(dbPath, []);
Assert.AreEqual("wal", SqliteTestHelper.ScalarString(connection, "PRAGMA journal_mode;")); Assert.AreEqual("wal", SqliteTestHelper.ScalarString(connection, "PRAGMA journal_mode;"));
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "PRAGMA synchronous;")); Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "PRAGMA synchronous;"));
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "PRAGMA foreign_keys;")); Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "PRAGMA foreign_keys;"));
} }
[TestMethod] [TestMethod]
public void OpenSetsUserVersionToLatestMigration() public void OpenSetsUserVersionToLatestWorkspaceMigration()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "version.db"); string dbPath = Path.Combine(directory.FullPath, "test.db");
using SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations); using var connection = SqliteDatabase.Open(dbPath, WorkspaceSchema.Migrations);
Assert.AreEqual(WorkspaceSchema.CurrentVersion, SqliteDatabase.ReadUserVersion(connection)); Assert.AreEqual(WorkspaceSchema.CurrentVersion, SqliteDatabase.ReadUserVersion(connection));
} }
[TestMethod] [TestMethod]
public void ReopenKeepsWalJournalMode() public void MigrationsApplyIncrementallyOnReopen()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "wal.db"); string dbPath = Path.Combine(directory.FullPath, "test.db");
using (SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)) // First open with only v1 available: v1 applied, v2 table absent.
using (var connection = SqliteDatabase.Open(dbPath, V1Only))
{ {
Assert.AreEqual(1L, SqliteDatabase.ReadUserVersion(connection));
Assert.IsTrue(SqliteTestHelper.TableExists(connection, "t1"));
Assert.IsFalse(SqliteTestHelper.TableExists(connection, "t2"));
} }
// WAL mode is stored in the database header, so a fresh connection keeps it. // Reopen with v1+v2: only v2 runs, v1 data untouched.
using SqliteConnection reopened = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations); using (var connection = SqliteDatabase.Open(dbPath, V1AndV2))
Assert.AreEqual("wal", SqliteTestHelper.ScalarString(reopened, "PRAGMA journal_mode;")); {
Assert.AreEqual(2L, SqliteDatabase.ReadUserVersion(connection));
Assert.IsTrue(SqliteTestHelper.TableExists(connection, "t1"));
Assert.IsTrue(SqliteTestHelper.TableExists(connection, "t2"));
}
} }
[TestMethod] [TestMethod]
public void OpenRejectsNewerStoredSchemaVersion() public void ReopenWithCurrentSchemaIsIdempotent()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "newer.db"); string dbPath = Path.Combine(directory.FullPath, "test.db");
long newerVersion = WorkspaceSchema.CurrentVersion + 1; SqliteDatabase.Open(dbPath, V1AndV2).Dispose();
using (SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)) using (var connection = SqliteDatabase.Open(dbPath, V1AndV2))
{ {
SqliteTestHelper.Exec(connection, $"PRAGMA user_version={newerVersion};"); // Still at version 2; re-running is a no-op.
Assert.AreEqual(2L, SqliteDatabase.ReadUserVersion(connection));
SqliteTestHelper.Exec(connection, "INSERT INTO t1 (id) VALUES (42);");
} }
SchemaVersionException exception = Assert.ThrowsExactly<SchemaVersionException>( using (var connection = SqliteDatabase.Open(dbPath, V1AndV2))
() => SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)); {
Assert.AreEqual(newerVersion, exception.StoredVersion); Assert.AreEqual(42L, SqliteTestHelper.ScalarLong(connection, "SELECT id FROM t1;"));
Assert.AreEqual(WorkspaceSchema.CurrentVersion, exception.SupportedVersion); }
} }
[TestMethod] [TestMethod]
public void OpenRejectsNonContiguousMigrationList() public void NewerSchemaVersionIsRejected()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "gap.db"); string dbPath = Path.Combine(directory.FullPath, "test.db");
SchemaMigration[] broken = // Simulate a database written by a newer build.
[ using (var connection = SqliteDatabase.Open(dbPath, []))
new SchemaMigration(2, "starts too high", "SELECT 1;"), {
]; SqliteTestHelper.Exec(connection, "PRAGMA user_version=5;");
}
Assert.ThrowsExactly<ArgumentException>(() => SqliteDatabase.Open(databasePath, broken)); SchemaVersionException ex = Assert.ThrowsExactly<SchemaVersionException>(
() => SqliteDatabase.Open(dbPath, V1AndV2));
Assert.AreEqual(5L, ex.StoredVersion);
Assert.AreEqual(2, ex.SupportedVersion);
} }
[TestMethod] [TestMethod]
public void CreateBuildsSchemaAndSeedTogether() public void NonContiguousMigrationListIsRejected()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "create.db"); string dbPath = Path.Combine(directory.FullPath, "test.db");
var bad = new[] { new SchemaMigration(2, "gap", "CREATE TABLE t (id INTEGER);") };
using SqliteConnection connection = SqliteDatabase.Create(databasePath, WorkspaceSchema.Migrations, Assert.ThrowsExactly<ArgumentException>(() => SqliteDatabase.Open(dbPath, bad));
(seedConnection, transaction) =>
{
using SqliteCommand command = seedConnection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "INSERT INTO tags (name, color) VALUES ('seed', '#000000');";
command.ExecuteNonQuery();
});
Assert.AreEqual(WorkspaceSchema.CurrentVersion, SqliteDatabase.ReadUserVersion(connection));
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM tags;"));
Assert.AreEqual("wal", SqliteTestHelper.ScalarString(connection, "PRAGMA journal_mode;"));
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "PRAGMA foreign_keys;"));
}
[TestMethod]
public void CreateWithFailingSeedLeavesNoDatabaseBehind()
{
using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "failed.db");
Assert.ThrowsExactly<InvalidOperationException>(() => SqliteDatabase.Create(
databasePath, WorkspaceSchema.Migrations, (_, _) => throw new InvalidOperationException("seed failed")));
Assert.IsFalse(File.Exists(databasePath));
Assert.IsFalse(File.Exists(databasePath + "-wal"));
Assert.IsFalse(File.Exists(databasePath + "-shm"));
}
[TestMethod]
public void CreateRefusesAnExistingDatabaseAndKeepsIt()
{
using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "existing.db");
SqliteDatabase.Create(databasePath, WorkspaceSchema.Migrations).Dispose();
Assert.ThrowsExactly<InvalidOperationException>(() => SqliteDatabase.Create(databasePath, WorkspaceSchema.Migrations));
Assert.IsTrue(File.Exists(databasePath));
} }
} }
@@ -0,0 +1,59 @@
using System.Globalization;
using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.Workspace;
/// <summary>
/// Verifies that preset column titles follow the UI language active at
/// seeding time and then live as ordinary data. Mutates the global
/// Resources.Culture, therefore marked DoNotParallelize.
/// </summary>
[TestClass]
[DoNotParallelize]
public class PresetColumnCultureTests
{
[TestMethod]
public void PresetTitlesAreEnglishUnderEnglishCulture()
{
CultureInfo? original = Resources.Culture;
try
{
Resources.Culture = new CultureInfo("en");
using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.SeedColumns(directory.FullPath);
using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
CollectionAssert.AreEqual(
new[] { "To Do", "In Progress", "Done" },
SqliteTestHelper.GetColumnTitles(connection));
}
finally
{
Resources.Culture = original;
}
}
[TestMethod]
public void PresetTitlesAreChineseUnderChineseCulture()
{
CultureInfo? original = Resources.Culture;
try
{
Resources.Culture = new CultureInfo("zh-Hans");
using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.SeedColumns(directory.FullPath);
using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
CollectionAssert.AreEqual(
new[] { "待办", "进行中", "已完成" },
SqliteTestHelper.GetColumnTitles(connection));
}
finally
{
Resources.Culture = original;
}
}
}
@@ -0,0 +1,191 @@
using YKanBan.Platform;
using YKanBan.Storage;
using YKanBan.Storage.AppData;
using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.Workspace;
/// <summary>Tests for the fixed-capacity LRU workspace session pool.</summary>
[TestClass]
public class WorkspaceConnectionPoolTests
{
/// <summary>Owns three initialized workspaces (a, b, c), a registry and the pool under test.</summary>
private sealed class PoolFixture : IDisposable
{
public TempDirectory Directory { get; } = new();
public AppDatabase AppDb { get; }
public WorkspaceConnectionPool Pool { get; }
public PoolFixture(int capacity = 2)
{
foreach (string name in new[] { "a", "b", "c" })
{
string path = Path.Combine(Directory.FullPath, name);
System.IO.Directory.CreateDirectory(path);
WorkspaceInitializer.Initialize(path);
}
AppDb = new AppDatabase(Path.Combine(Directory.FullPath, "app.db"));
Pool = new WorkspaceConnectionPool(capacity, AppDb, new PathComparer(ignoreCase: true));
}
/// <summary>Workspace folder path by name.</summary>
public string Workspace(string name) => Path.Combine(Directory.FullPath, name);
public void Dispose()
{
Pool.Dispose();
AppDb.Dispose();
Directory.Dispose();
}
}
[TestMethod]
public void OpenBeyondCapacityEvictsLeastRecentlyUsed()
{
using var fixture = new PoolFixture(capacity: 2);
fixture.Pool.Open(fixture.Workspace("a"));
fixture.Pool.Open(fixture.Workspace("b"));
fixture.Pool.Open(fixture.Workspace("c"));
Assert.AreEqual(2, fixture.Pool.OpenCount);
Assert.IsNull(fixture.Pool.Find(fixture.Workspace("a")));
Assert.IsNotNull(fixture.Pool.Find(fixture.Workspace("b")));
Assert.IsNotNull(fixture.Pool.Find(fixture.Workspace("c")));
}
[TestMethod]
public void OpenTwiceReturnsSameSession()
{
using var fixture = new PoolFixture();
WorkspaceSession first = fixture.Pool.Open(fixture.Workspace("a"));
WorkspaceSession second = fixture.Pool.Open(fixture.Workspace("a"));
Assert.AreSame(first, second);
Assert.AreEqual(1, fixture.Pool.OpenCount);
}
[TestMethod]
public void TouchPromotesRecency()
{
using var fixture = new PoolFixture(capacity: 2);
fixture.Pool.Open(fixture.Workspace("a"));
fixture.Pool.Open(fixture.Workspace("b"));
fixture.Pool.Touch(fixture.Workspace("a"));
fixture.Pool.Open(fixture.Workspace("c"));
// "a" was touched after "b" opened, so "b" is the LRU victim now.
Assert.IsNotNull(fixture.Pool.Find(fixture.Workspace("a")));
Assert.IsNull(fixture.Pool.Find(fixture.Workspace("b")));
}
[TestMethod]
public void EvictedWorkspaceCanBeReopened()
{
using var fixture = new PoolFixture(capacity: 2);
fixture.Pool.Open(fixture.Workspace("a"));
fixture.Pool.Open(fixture.Workspace("b"));
fixture.Pool.Open(fixture.Workspace("c"));
// "a" was evicted; reopening it works and now evicts the LRU "b".
WorkspaceSession reopened = fixture.Pool.Open(fixture.Workspace("a"));
Assert.AreEqual("a", Path.GetFileName(reopened.FolderPath));
Assert.IsNull(fixture.Pool.Find(fixture.Workspace("b")));
}
[TestMethod]
public void OpenRegistersWorkspaceInSidebarRegistry()
{
using var fixture = new PoolFixture();
fixture.Pool.Open(fixture.Workspace("a"));
fixture.Pool.Open(fixture.Workspace("b"));
IReadOnlyList<string> registered = fixture.AppDb.GetWorkspaces().Select(record => record.Path).ToList();
Assert.AreEqual(2, registered.Count);
Assert.IsTrue(registered.Contains(new PathComparer(ignoreCase: true).Normalize(fixture.Workspace("a"))));
Assert.IsTrue(registered.Contains(new PathComparer(ignoreCase: true).Normalize(fixture.Workspace("b"))));
}
[TestMethod]
public void OpenMissingDirectoryThrows()
{
using var fixture = new PoolFixture();
string missing = Path.Combine(fixture.Directory.FullPath, "nowhere");
Assert.ThrowsExactly<WorkspaceDirectoryMissingException>(() => fixture.Pool.Open(missing));
}
[TestMethod]
public void OpenFolderWithoutYkanbanThrows()
{
using var fixture = new PoolFixture();
string plain = Path.Combine(fixture.Directory.FullPath, "plain");
System.IO.Directory.CreateDirectory(plain);
Assert.ThrowsExactly<WorkspaceNotInitializedException>(() => fixture.Pool.Open(plain));
}
[TestMethod]
public void OpenWithLockHeldElsewhereThrowsThenSucceedsAfterRelease()
{
using var fixture = new PoolFixture();
using WorkspaceLock holder = WorkspaceLock.Acquire(fixture.Workspace("a"));
Assert.ThrowsExactly<WorkspaceLockException>(() => fixture.Pool.Open(fixture.Workspace("a")));
holder.Dispose();
WorkspaceSession session = fixture.Pool.Open(fixture.Workspace("a"));
Assert.AreEqual("a", Path.GetFileName(session.FolderPath));
}
[TestMethod]
public void RemoveReleasesResourcesAndForgetsRegistryEntry()
{
using var fixture = new PoolFixture();
fixture.Pool.Open(fixture.Workspace("a"));
Assert.IsTrue(fixture.Pool.Remove(fixture.Workspace("a")));
Assert.IsNull(fixture.Pool.Find(fixture.Workspace("a")));
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
// Resources are truly released: the lock can be taken again.
using WorkspaceLock reacquired = WorkspaceLock.Acquire(fixture.Workspace("a"));
}
[TestMethod]
public void PathEquivalentsShareOneSession()
{
using var fixture = new PoolFixture();
string path = fixture.Workspace("a");
string differentlyCased = Path.Combine(
Path.GetDirectoryName(path)!,
Path.GetFileName(path).ToUpperInvariant());
WorkspaceSession session = fixture.Pool.Open(path);
WorkspaceSession same = fixture.Pool.Open(differentlyCased);
Assert.AreSame(session, same);
Assert.AreEqual(1, fixture.Pool.OpenCount);
}
[TestMethod]
public void DisposeReleasesAllLocks()
{
using var fixture = new PoolFixture();
fixture.Pool.Open(fixture.Workspace("a"));
fixture.Pool.Open(fixture.Workspace("b"));
fixture.Pool.Dispose();
using WorkspaceLock lockA = WorkspaceLock.Acquire(fixture.Workspace("a"));
using WorkspaceLock lockB = WorkspaceLock.Acquire(fixture.Workspace("b"));
}
}
@@ -1,60 +1,49 @@
using Microsoft.Data.Sqlite;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.Workspace; namespace YKanBan.Tests.Storage.Workspace;
/// <summary> /// <summary>Tests for .ykanban folder and empty database creation.</summary>
/// Tests for workspace detection and initialization. Initialization creates
/// the structure and an empty migrated database, but deliberately adds no
/// content.
/// </summary>
[TestClass] [TestClass]
public class WorkspaceInitializerTests public class WorkspaceInitializerTests
{ {
[TestMethod] [TestMethod]
public void IsWorkspaceReflectsInitializationState() public void InitializeCreatesYkanbanFolderAndDatabase()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
Assert.IsFalse(WorkspaceInitializer.IsWorkspace(directory.FullPath)); Assert.IsFalse(WorkspaceInitializer.IsWorkspace(directory.FullPath));
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
Assert.IsTrue(WorkspaceInitializer.IsWorkspace(directory.FullPath)); Assert.IsTrue(WorkspaceInitializer.IsWorkspace(directory.FullPath));
Assert.IsTrue(File.Exists(WorkspacePaths.Database(directory.FullPath)));
// The lock file only appears once a WorkspaceLock is acquired.
Assert.IsFalse(File.Exists(WorkspacePaths.LockFile(directory.FullPath)));
} }
[TestMethod] [TestMethod]
public void InitializeCreatesStructureAndMigratedEmptyDatabase() public void InitializeLeavesDatabaseEmpty()
{ {
// Initialization creates structure only; preset content is seeded separately.
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
Assert.IsTrue(Directory.Exists(WorkspacePaths.Root(directory.FullPath))); using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
Assert.IsTrue(File.Exists(WorkspacePaths.Database(directory.FullPath)));
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
Assert.AreEqual(WorkspaceSchema.CurrentVersion, SqliteDatabase.ReadUserVersion(connection));
Assert.IsTrue(SqliteTestHelper.TableExists(connection, "columns"));
Assert.IsTrue(SqliteTestHelper.TableExists(connection, "cards"));
Assert.IsTrue(SqliteTestHelper.TableExists(connection, "tags"));
Assert.IsTrue(SqliteTestHelper.TableExists(connection, "card_tags"));
// Initialization does not add preset content.
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM columns;")); Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM columns;"));
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM cards;"));
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM tags;"));
} }
[TestMethod] [TestMethod]
public void InitializeMissingFolderThrows() public void InitializeThrowsWhenDirectoryIsMissing()
{ {
using var directory = new TempDirectory(); string missing = Path.Combine(Path.GetTempPath(), "ykanban-tests-" + Guid.NewGuid().ToString("N"));
string missing = Path.Combine(directory.FullPath, "not-created"); Assert.ThrowsExactly<WorkspaceDirectoryMissingException>(() => WorkspaceInitializer.Initialize(missing));
WorkspaceDirectoryMissingException exception = Assert.ThrowsExactly<WorkspaceDirectoryMissingException>(
() => WorkspaceInitializer.Initialize(missing));
Assert.AreEqual(missing, exception.FolderPath);
} }
[TestMethod] [TestMethod]
public void InitializeTwiceThrows() public void InitializeThrowsWhenDatabaseAlreadyExists()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -4,9 +4,7 @@ using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.Workspace; namespace YKanBan.Tests.Storage.Workspace;
/// <summary> /// <summary>Tests for exclusive lock acquisition, diagnostics and release.</summary>
/// Tests for exclusive lock acquisition, diagnostics and release.
/// </summary>
[TestClass] [TestClass]
public class WorkspaceLockTests public class WorkspaceLockTests
{ {
@@ -28,9 +26,9 @@ public class WorkspaceLockTests
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
using WorkspaceLock first = WorkspaceLock.Acquire(directory.FullPath); using WorkspaceLock first = WorkspaceLock.Acquire(directory.FullPath);
WorkspaceLockException exception = Assert.ThrowsExactly<WorkspaceLockException>( WorkspaceLockException ex = Assert.ThrowsExactly<WorkspaceLockException>(
() => WorkspaceLock.Acquire(directory.FullPath)); () => WorkspaceLock.Acquire(directory.FullPath));
Assert.AreEqual(WorkspacePaths.LockFile(directory.FullPath), exception.LockFilePath); Assert.AreEqual(WorkspacePaths.LockFile(directory.FullPath), ex.LockFilePath);
} }
[TestMethod] [TestMethod]
@@ -42,7 +40,7 @@ public class WorkspaceLockTests
} }
[TestMethod] [TestMethod]
public void LockFileContainsHolderDiagnosticsAfterRelease() public void LockFileContainsHolderDiagnostics()
{ {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -1,96 +1,39 @@
using System.Globalization;
using Microsoft.Data.Sqlite;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.Workspace; namespace YKanBan.Tests.Storage.Workspace;
/// <summary> /// <summary>Tests for seeding preset workspace content.</summary>
/// Verifies that the preset column titles follow the UI language active when
/// they are added and then live as ordinary data. These tests mutate the
/// global <see cref="Resources.Culture"/>, so they are marked do-not-parallelize.
/// </summary>
[TestClass] [TestClass]
[DoNotParallelize]
public class WorkspacePresetTests public class WorkspacePresetTests
{ {
[TestMethod] [TestMethod]
public void AddPresetColumnsStoresEnglishTitlesUnderEnglishCulture() public void SeedAddsThreeDistinctPresetColumns()
{ {
CultureInfo? original = Resources.Culture;
try
{
Resources.Culture = new CultureInfo("en");
string[] expected =
[
Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
];
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceSession.Initialize(directory.FullPath).Dispose(); WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.SeedColumns(directory.FullPath);
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath); using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection)); List<string> titles = SqliteTestHelper.GetColumnTitles(connection);
}
finally Assert.AreEqual(3, titles.Count);
{ Assert.AreEqual(titles.Count, titles.Distinct().Count());
Resources.Culture = original; Assert.IsTrue(titles.All(title => title.Length > 0));
}
} }
[TestMethod] [TestMethod]
public void AddPresetColumnsStoresChineseTitlesUnderChineseCulture() public void SeedPresetColumnsShareOneTimestamp()
{ {
CultureInfo? original = Resources.Culture;
try
{
Resources.Culture = new CultureInfo("zh-Hans");
string[] expected =
[
Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
];
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceSession.Initialize(directory.FullPath).Dispose(); WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.SeedColumns(directory.FullPath);
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath); using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection));
}
finally
{
Resources.Culture = original;
}
}
[TestMethod] // Creation writes created_at = updated_at; all three columns share one moment.
public void PresetTitlesAreDataAndIgnoreLaterCultureChanges() Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM columns WHERE created_at <> updated_at;"));
{ Assert.AreEqual(3L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM columns WHERE created_at > 0;"));
CultureInfo? original = Resources.Culture; Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(DISTINCT created_at) FROM columns;"));
try
{
Resources.Culture = new CultureInfo("en");
string[] expected =
[
Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
];
using var directory = new TempDirectory();
WorkspaceSession.Initialize(directory.FullPath).Dispose();
// Switching the language after adding the presets must not rewrite stored data.
Resources.Culture = new CultureInfo("zh-Hans");
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection));
}
finally
{
Resources.Culture = original;
}
} }
} }
@@ -1,7 +1,6 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Models; using YKanBan.Models;
using YKanBan.Search; using YKanBan.Storage.AppData;
using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
@@ -9,21 +8,25 @@ namespace YKanBan.Tests.Storage.Workspace;
/// <summary> /// <summary>
/// Tests for workspace CRUD, the three cascade chains, edit-confirm /// Tests for workspace CRUD, the three cascade chains, edit-confirm
/// transaction atomicity and the timestamp refresh rules. /// transaction atomicity, timestamp refresh rules and the last_edited_at
/// write-through.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class WorkspaceRepositoryTests public class WorkspaceRepositoryTests
{ {
/// <summary> /// <summary>
/// Owns a workspace with fixed-timestamp fixture data (one column, one /// Owns a workspace with fixed-timestamp fixture data (one column, one
/// card, two tags linked to the card) plus the repository under test. /// card, two tags linked to the card), a fake-clock app.db and the
/// Fixture timestamps are small literal values so that any real write, /// repository under test.
/// which stamps the current Unix time, is observable.
/// </summary> /// </summary>
private sealed class RepositoryFixture : IDisposable private sealed class RepositoryFixture : IDisposable
{ {
public TempDirectory Directory { get; } = new(); public TempDirectory Directory { get; } = new();
public long Clock { get; set; } = 1000;
public AppDatabase AppDb { get; }
public WorkspaceRepository Repository { get; } public WorkspaceRepository Repository { get; }
public long ColumnId { get; } = 1; public long ColumnId { get; } = 1;
@@ -38,70 +41,59 @@ public class WorkspaceRepositoryTests
{ {
WorkspaceInitializer.Initialize(Directory.FullPath); WorkspaceInitializer.Initialize(Directory.FullPath);
using (SqliteConnection connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath)) // Fixture rows carry literal timestamps so refresh vs. no-refresh stays observable.
{ using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath);
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Col', '', 100, 100);"); SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Col', '', 100, 100);");
SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, 'T', 'C', 100, 100);"); SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, 'T', 'C', 100, 100);");
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color, description) VALUES ('bug', '#ff0000', '');"); SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color, description) VALUES ('bug', '#ff0000', '');");
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color, description) VALUES ('ui', '#00ff00', '');"); SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color, description) VALUES ('ui', '#00ff00', '');");
SqliteTestHelper.Exec(connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 1);"); SqliteTestHelper.Exec(connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 1);");
SqliteTestHelper.Exec(connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 2);"); SqliteTestHelper.Exec(connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 2);");
AppDb = new AppDatabase(Path.Combine(Directory.FullPath, "app.db"), () => Clock);
Repository = new WorkspaceRepository(Directory.FullPath, AppDb);
} }
Repository = new WorkspaceRepository(Directory.FullPath); /// <summary>The last_edited_at currently mirrored into the registry.</summary>
} public long LastEditedAt => AppDb.GetWorkspaces().Single().LastEditedAt;
public void Dispose() public void Dispose()
{ {
Repository.Dispose(); Repository.Dispose();
AppDb.Dispose();
Directory.Dispose(); Directory.Dispose();
} }
} }
[TestMethod]
public void GetColumnsReturnsTheSeededColumn()
{
using var fixture = new RepositoryFixture();
ColumnModel column = fixture.Repository.GetColumn(fixture.ColumnId)!;
Assert.AreEqual("Col", column.Title);
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
}
[TestMethod]
public void AddColumnSetsEqualTimestamps()
{
using var fixture = new RepositoryFixture();
ColumnModel column = fixture.Repository.AddColumn("New", "desc");
Assert.IsTrue(column.CreatedAt > 0L);
Assert.AreEqual(column.CreatedAt, column.UpdatedAt);
}
[TestMethod] [TestMethod]
public void UpdateColumnWithoutChangeWritesNothing() public void UpdateColumnWithoutChangeWritesNothing()
{ {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
ColumnModel before = fixture.Repository.GetColumn(fixture.ColumnId)!;
ColumnModel result = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col", ""); ColumnModel result = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col", "");
// A no-op must not refresh the fixed fixture timestamp. Assert.AreEqual(before.UpdatedAt, result.UpdatedAt);
Assert.AreEqual(100L, result.UpdatedAt); Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
} }
[TestMethod] [TestMethod]
public void UpdateColumnChangeRefreshesTimestamp() public void UpdateColumnChangeRefreshesColumnTimestampAndLastEdited()
{ {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
fixture.Clock = 2000;
ColumnModel updated = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col2", "desc"); ColumnModel updated = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col2", "desc");
Assert.IsTrue(updated.UpdatedAt > 100L); Assert.IsTrue(updated.UpdatedAt > 100L);
Assert.AreEqual(100L, updated.CreatedAt); Assert.AreEqual(2000L, fixture.LastEditedAt);
} }
[TestMethod] [TestMethod]
public void DeleteColumnCascadesToCardsAndTagLinks() public void DeleteColumnCascadesToCardsAndTagLinks()
{ {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
fixture.Clock = 2000;
Assert.IsTrue(fixture.Repository.DeleteColumn(fixture.ColumnId)); Assert.IsTrue(fixture.Repository.DeleteColumn(fixture.ColumnId));
@@ -110,6 +102,7 @@ public class WorkspaceRepositoryTests
Assert.AreEqual(2, fixture.Repository.GetTags().Count); Assert.AreEqual(2, fixture.Repository.GetTags().Count);
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(fixture.Directory.FullPath); using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(fixture.Directory.FullPath);
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM card_tags;")); Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM card_tags;"));
Assert.AreEqual(2000L, fixture.LastEditedAt);
} }
[TestMethod] [TestMethod]
@@ -142,40 +135,45 @@ public class WorkspaceRepositoryTests
public void UpdateCardWithoutEffectiveChangeWritesNothing() public void UpdateCardWithoutEffectiveChangeWritesNothing()
{ {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
fixture.Clock = 2000;
CardModel before = fixture.Repository.GetCard(fixture.CardId)!;
CardModel result = fixture.Repository.UpdateCard( CardModel result = fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.BugTagId, fixture.UiTagId]);
fixture.CardId, "T", "C", [fixture.BugTagId, fixture.UiTagId]);
Assert.AreEqual(100L, result.UpdatedAt); Assert.AreEqual(before.UpdatedAt, result.UpdatedAt);
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
} }
[TestMethod] [TestMethod]
public void UpdateCardTitleChangeRefreshesTimestamp() public void UpdateCardTitleChangeRefreshesTimestampsAndLastEdited()
{ {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
fixture.Clock = 2000;
CardModel updated = fixture.Repository.UpdateCard( CardModel updated = fixture.Repository.UpdateCard(fixture.CardId, "T2", "C", [fixture.BugTagId, fixture.UiTagId]);
fixture.CardId, "T2", "C", [fixture.BugTagId, fixture.UiTagId]);
Assert.IsTrue(updated.UpdatedAt > 100L); Assert.IsTrue(updated.UpdatedAt > 100L);
Assert.AreEqual(100L, updated.CreatedAt); Assert.AreEqual(2000L, fixture.LastEditedAt);
} }
[TestMethod] [TestMethod]
public void UpdateCardTagSetOnlyChangeStillRefreshesTimestamp() public void UpdateCardTagSetOnlyChangeStillRefreshesCardTimestamp()
{ {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
fixture.Clock = 2000;
CardModel updated = fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.BugTagId]); CardModel updated = fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.BugTagId]);
Assert.IsTrue(updated.UpdatedAt > 100L); Assert.IsTrue(updated.UpdatedAt > 100L);
Assert.AreEqual(1, updated.Tags.Count); Assert.AreEqual(1, updated.Tags.Count);
Assert.AreEqual(2000L, fixture.LastEditedAt);
} }
[TestMethod] [TestMethod]
public void UpdateCardWithUnknownTagRollsBackAtomically() public void UpdateCardWithUnknownTagRollsBackAtomically()
{ {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
fixture.Clock = 2000;
// Tag 999 does not exist: the FK fires mid-transaction and the whole edit must roll back. // Tag 999 does not exist: the FK fires mid-transaction and the whole edit must roll back.
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
@@ -186,13 +184,15 @@ public class WorkspaceRepositoryTests
Assert.AreEqual("C", after.Content); Assert.AreEqual("C", after.Content);
Assert.AreEqual(100L, after.UpdatedAt); Assert.AreEqual(100L, after.UpdatedAt);
Assert.AreEqual(2, after.Tags.Count); Assert.AreEqual(2, after.Tags.Count);
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
} }
[TestMethod] [TestMethod]
public void MoveCardUpdatesColumnWithoutRefreshingTimestamp() public void MoveCardRefreshesLastEditedButNotCardTimestamp()
{ {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
long target = fixture.Repository.AddColumn("Target", "").Id; long target = fixture.Repository.AddColumn("Target", "").Id;
fixture.Clock = 2000;
Assert.IsTrue(fixture.Repository.MoveCard(fixture.CardId, target)); Assert.IsTrue(fixture.Repository.MoveCard(fixture.CardId, target));
@@ -200,22 +200,25 @@ public class WorkspaceRepositoryTests
Assert.AreEqual(target, moved.ColumnId); Assert.AreEqual(target, moved.ColumnId);
// The move is a write but deliberately leaves the card's updated_at alone. // The move is a write but deliberately leaves the card's updated_at alone.
Assert.AreEqual(100L, moved.UpdatedAt); Assert.AreEqual(100L, moved.UpdatedAt);
Assert.AreEqual(2000L, fixture.LastEditedAt);
} }
[TestMethod] [TestMethod]
public void MoveCardToCurrentColumnIsNoOp() public void MoveCardToCurrentColumnWritesNothing()
{ {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
fixture.Clock = 2000;
Assert.IsFalse(fixture.Repository.MoveCard(fixture.CardId, fixture.ColumnId)); Assert.IsFalse(fixture.Repository.MoveCard(fixture.CardId, fixture.ColumnId));
Assert.AreEqual(100L, fixture.Repository.GetCard(fixture.CardId)!.UpdatedAt); Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
} }
[TestMethod] [TestMethod]
public void AddCardCreatesWithEqualTimestampsAndLinkedTags() public void AddCardCreatesWithEqualTimestampsAndLinkedTags()
{ {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
fixture.Clock = 2000;
CardModel card = fixture.Repository.AddCard(fixture.ColumnId, "N", "body", [fixture.UiTagId]); CardModel card = fixture.Repository.AddCard(fixture.ColumnId, "N", "body", [fixture.UiTagId]);
@@ -223,119 +226,33 @@ public class WorkspaceRepositoryTests
Assert.AreEqual(card.CreatedAt, card.UpdatedAt); Assert.AreEqual(card.CreatedAt, card.UpdatedAt);
Assert.AreEqual(1, card.Tags.Count); Assert.AreEqual(1, card.Tags.Count);
Assert.AreEqual("ui", card.Tags[0].Name); Assert.AreEqual("ui", card.Tags[0].Name);
Assert.AreEqual(2000L, fixture.LastEditedAt);
} }
[TestMethod] [TestMethod]
public void UpdateTagWithoutChangeWritesNothing() public void UpdateTagWithoutChangeWritesNothing()
{ {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
fixture.Clock = 2000;
TagModel result = fixture.Repository.UpdateTag( TagModel result = fixture.Repository.UpdateTag(fixture.BugTagId, "bug", RgbColor.Parse("#ff0000"), "");
fixture.BugTagId, "bug", RgbColor.Parse("#ff0000"), "");
Assert.AreEqual("bug", result.Name); Assert.AreEqual("bug", result.Name);
Assert.AreEqual(new RgbColor(0xFF, 0x00, 0x00), result.Color); Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
} }
[TestMethod] [TestMethod]
public void UpdateTagChangeWrites() public void UpdateTagChangeWritesAndTouchesLastEdited()
{ {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
fixture.Clock = 3000;
TagModel updated = fixture.Repository.UpdateTag( TagModel updated = fixture.Repository.UpdateTag(fixture.BugTagId, "defect", RgbColor.Parse("#ee0a0a"), "desc");
fixture.BugTagId, "defect", RgbColor.Parse("#ee0a0a"), "desc");
Assert.AreEqual("defect", updated.Name); Assert.AreEqual("defect", updated.Name);
Assert.AreEqual(new RgbColor(0xEE, 0x0A, 0x0A), updated.Color); Assert.AreEqual(new RgbColor(0xEE, 0x0A, 0x0A), updated.Color);
Assert.AreEqual("desc", updated.Description); Assert.AreEqual("desc", updated.Description);
Assert.AreEqual("defect", fixture.Repository.GetTags().Single(tag => tag.Id == fixture.BugTagId).Name); Assert.AreEqual(3000L, fixture.LastEditedAt);
}
[TestMethod]
public void AddTagWithDuplicateNameIsRejected()
{
using var fixture = new RepositoryFixture();
DuplicateNameException exception = Assert.ThrowsExactly<DuplicateNameException>(() =>
fixture.Repository.AddTag("BUG", RgbColor.Parse("#123456"), ""));
Assert.AreEqual(NamedEntity.Tag, exception.Entity);
Assert.AreEqual("BUG", exception.Name);
Assert.AreEqual(2, fixture.Repository.GetTags().Count);
}
[TestMethod]
public void AddTagWithEmptyNameIsRejected()
{
using var fixture = new RepositoryFixture();
NameRequiredException exception = Assert.ThrowsExactly<NameRequiredException>(() =>
fixture.Repository.AddTag("", RgbColor.Parse("#123456"), ""));
Assert.AreEqual(NamedEntity.Tag, exception.Entity);
}
[TestMethod]
public void UpdateTagToExistingNameIsRejectedAndKeepsTheRow()
{
using var fixture = new RepositoryFixture();
Assert.ThrowsExactly<DuplicateNameException>(() =>
fixture.Repository.UpdateTag(fixture.UiTagId, "Bug", RgbColor.Parse("#00ff00"), ""));
Assert.AreEqual("ui", fixture.Repository.GetTags().Single(tag => tag.Id == fixture.UiTagId).Name);
}
[TestMethod]
public void AddColumnWithDuplicateTitleIsRejectedCaseInsensitively()
{
using var fixture = new RepositoryFixture();
DuplicateNameException exception = Assert.ThrowsExactly<DuplicateNameException>(() =>
fixture.Repository.AddColumn("COL", ""));
Assert.AreEqual(NamedEntity.Column, exception.Entity);
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
}
[TestMethod]
public void AddColumnWithEmptyTitleIsRejected()
{
using var fixture = new RepositoryFixture();
NameRequiredException exception = Assert.ThrowsExactly<NameRequiredException>(() =>
fixture.Repository.AddColumn("", "description"));
Assert.AreEqual(NamedEntity.Column, exception.Entity);
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
}
[TestMethod]
public void UpdateColumnConstraintViolationsAreTyped()
{
using var fixture = new RepositoryFixture();
ColumnModel other = fixture.Repository.AddColumn("Other", "");
Assert.ThrowsExactly<DuplicateNameException>(() => fixture.Repository.UpdateColumn(other.Id, "col", ""));
Assert.ThrowsExactly<NameRequiredException>(() => fixture.Repository.UpdateColumn(other.Id, "", ""));
Assert.AreEqual("Other", fixture.Repository.GetColumn(other.Id)!.Title);
}
[TestMethod]
public void GetCardsWithFilterReturnsMatchesWithAllOfTheirTags()
{
using var fixture = new RepositoryFixture();
fixture.Repository.AddCard(fixture.ColumnId, "Other", "", []);
// Filtering by one tag must still load both tags of the matching card.
CompiledSearch filter = SearchSqlCompiler.Compile(SearchQueryParser.Parse("tag:ui")!);
IReadOnlyList<CardModel> cards = fixture.Repository.GetCards(filter);
Assert.AreEqual(1, cards.Count);
Assert.AreEqual(fixture.CardId, cards[0].Id);
CollectionAssert.AreEqual(new[] { "bug", "ui" }, cards[0].Tags.Select(tag => tag.Name).ToArray());
Assert.AreEqual(2, fixture.Repository.GetCards(null).Count);
}
[TestMethod]
public void CountCardsCountsPerColumn()
{
using var fixture = new RepositoryFixture();
ColumnModel empty = fixture.Repository.AddColumn("Empty", "");
fixture.Repository.AddCard(fixture.ColumnId, "", "", []);
Assert.AreEqual(2L, fixture.Repository.CountCards(fixture.ColumnId));
Assert.AreEqual(0L, fixture.Repository.CountCards(empty.Id));
} }
[TestMethod] [TestMethod]
@@ -348,6 +265,7 @@ public class WorkspaceRepositoryTests
Assert.AreEqual(1L, before.Single(entry => entry.Tag.Name == "ui").UsageCount); Assert.AreEqual(1L, before.Single(entry => entry.Tag.Name == "ui").UsageCount);
// Detaching one tag via an edit confirmation drops its usage to zero but keeps the tag. // Detaching one tag via an edit confirmation drops its usage to zero but keeps the tag.
fixture.Clock = 2000;
fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.UiTagId]); fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.UiTagId]);
IReadOnlyList<(TagModel Tag, long UsageCount)> after = fixture.Repository.GetTagsWithUsage(); IReadOnlyList<(TagModel Tag, long UsageCount)> after = fixture.Repository.GetTagsWithUsage();
@@ -5,16 +5,11 @@ using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.Workspace; namespace YKanBan.Tests.Storage.Workspace;
/// <summary> /// <summary>Verifies that the DDL constraints reject invalid data at the door.</summary>
/// Verifies that the workspace DDL constraints reject invalid data at the door
/// and that the cascading delete chains work as specified.
/// </summary>
[TestClass] [TestClass]
public class WorkspaceSchemaTests public class WorkspaceSchemaTests
{ {
/// <summary> /// <summary>Owns a temp directory plus a fresh workspace-schema database for one test.</summary>
/// Owns a temp directory plus a fresh workspace-schema database for a single test.
/// </summary>
private sealed class FreshDatabase : IDisposable private sealed class FreshDatabase : IDisposable
{ {
public TempDirectory Directory { get; } = new(); public TempDirectory Directory { get; } = new();
@@ -27,9 +22,6 @@ public class WorkspaceSchemaTests
Path.Combine(Directory.FullPath, "ws.db"), WorkspaceSchema.Migrations); Path.Combine(Directory.FullPath, "ws.db"), WorkspaceSchema.Migrations);
} }
/// <summary>
/// Closes the connection before removing the temporary directory.
/// </summary>
public void Dispose() public void Dispose()
{ {
Connection.Dispose(); Connection.Dispose();
@@ -41,113 +33,62 @@ public class WorkspaceSchemaTests
public void EmptyColumnTitleIsRejected() public void EmptyColumnTitleIsRejected()
{ {
using var db = new FreshDatabase(); using var db = new FreshDatabase();
using var connection = db.Connection;
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('', 1, 1);")); SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('', 1, 1);"));
}
[TestMethod]
public void WhitespaceColumnTitleIsAccepted()
{
using var db = new FreshDatabase();
// No trimming: a single space is a non-empty title as far as the DDL is concerned.
int affected = SqliteTestHelper.Exec(
db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES (' ', 1, 1);");
Assert.AreEqual(1, affected);
} }
[TestMethod] [TestMethod]
public void DuplicateColumnTitleIsRejected() public void DuplicateColumnTitleIsRejected()
{ {
using var db = new FreshDatabase(); using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);"); using var connection = db.Connection;
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);")); SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);"));
} }
[TestMethod] [TestMethod]
public void ColumnTitlesDifferingOnlyInAsciiCaseAreRejected() public void ColumnTitlesCompareCaseSensitively()
{ {
using var db = new FreshDatabase(); using var db = new FreshDatabase();
// NOCASE uniqueness: 'Foo' and 'foo' cannot coexist. using var connection = db.Connection;
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);"); // BINARY collation: 'Foo' and 'foo' are distinct titles.
Assert.ThrowsExactly<SqliteException>(() => SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('foo', 1, 1);")); SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('foo', 1, 1);");
} Assert.AreEqual(2L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM columns;"));
[TestMethod]
public void ColumnTitlesDifferingOnlyInNonAsciiCaseAreAccepted()
{
using var db = new FreshDatabase();
// NOCASE folds ASCII only: 'Ä' and 'ä' remain distinct titles.
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Ä', 1, 1);");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('ä', 1, 1);");
Assert.AreEqual(2L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM columns;"));
}
[TestMethod]
public void ColumnTitleCaseOnlyRenameOfSameRowIsAccepted()
{
using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
int affected = SqliteTestHelper.Exec(db.Connection, "UPDATE columns SET title = 'foo' WHERE id = 1;");
Assert.AreEqual(1, affected);
}
[TestMethod]
public void ColumnTitlesStillOrderByCodePoint()
{
using var db = new FreshDatabase();
// Uniqueness is NOCASE, but the column collation stays BINARY: 'B' (0x42) sorts before 'a' (0x61).
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('a', 1, 1);");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('B', 1, 1);");
Assert.AreEqual("B", SqliteTestHelper.ScalarString(db.Connection, "SELECT title FROM columns ORDER BY title LIMIT 1;"));
} }
[TestMethod] [TestMethod]
public void EmptyTagNameIsRejected() public void EmptyTagNameIsRejected()
{ {
using var db = new FreshDatabase(); using var db = new FreshDatabase();
using var connection = db.Connection;
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('', '#112233');")); SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('', '#112233');"));
} }
[TestMethod] [TestMethod]
public void TagNamesAcceptSpacesEmojiAndReservedWords() public void TagNamesAcceptSpacesEmojiAndReservedWords()
{ {
using var db = new FreshDatabase(); using var db = new FreshDatabase();
using var connection = db.Connection;
// Tag names are fully open: no charset or length rules, no trimming. // Tag names are fully open: no charset or length rules, no trimming.
foreach (string name in new[] { " ", "a b", "🏷️", "AND", "tag:with:colons" }) foreach (string name in new[] { " ", "a b", "🏷️", "AND", "tag:with:colons" })
{ {
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ($n, '#112233');", ("$n", name)); SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ($n, '#112233');", ("$n", name));
} }
Assert.AreEqual(5L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;")); Assert.AreEqual(5L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM tags;"));
} }
[TestMethod] [TestMethod]
public void DuplicateTagNameIsRejected() public void DuplicateTagNameIsRejected()
{ {
using var db = new FreshDatabase(); using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');"); using var connection = db.Connection;
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#445566');")); SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#445566');"));
}
[TestMethod]
public void TagNamesDifferingOnlyInAsciiCaseAreRejected()
{
using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('BUG', '#445566');"));
}
[TestMethod]
public void TagNamesDifferingOnlyInNonAsciiCaseAreAccepted()
{
using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('Ä', '#112233');");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('ä', '#445566');");
Assert.AreEqual(2L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;"));
} }
[TestMethod] [TestMethod]
@@ -157,8 +98,8 @@ public class WorkspaceSchemaTests
public void ValidTagColorsAreAccepted(string color) public void ValidTagColorsAreAccepted(string color)
{ {
using var db = new FreshDatabase(); using var db = new FreshDatabase();
int affected = SqliteTestHelper.Exec( using var connection = db.Connection;
db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color)); int affected = SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color));
Assert.AreEqual(1, affected); Assert.AreEqual(1, affected);
} }
@@ -174,98 +115,46 @@ public class WorkspaceSchemaTests
public void InvalidTagColorsAreRejected(string color) public void InvalidTagColorsAreRejected(string color)
{ {
using var db = new FreshDatabase(); using var db = new FreshDatabase();
using var connection = db.Connection;
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color))); SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color)));
} }
[TestMethod] [TestMethod]
public void CardRequiresExistingColumn() public void CardRequiresExistingColumn()
{ {
using var db = new FreshDatabase(); using var db = new FreshDatabase();
using var connection = db.Connection;
// foreign_keys=ON makes the FK enforceable; this is the DDL contract behind the cascades. // foreign_keys=ON makes the FK enforceable; this is the DDL contract behind the cascades.
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (999, 1, 1);")); SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (999, 1, 1);"));
} }
[TestMethod] [TestMethod]
public void CardDefaultsToEmptyTitleAndContent() public void CardDefaultsToEmptyTitleAndContent()
{ {
using var db = new FreshDatabase(); using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);"); using var connection = db.Connection;
SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);"); SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);");
SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
// No title is represented by the empty string. // No title is represented by the empty string.
Assert.AreEqual(string.Empty, SqliteTestHelper.ScalarString(db.Connection, "SELECT title FROM cards WHERE id = 1;")); Assert.AreEqual(string.Empty, SqliteTestHelper.ScalarString(connection, "SELECT title FROM cards WHERE id = 1;"));
Assert.AreEqual(string.Empty, SqliteTestHelper.ScalarString(db.Connection, "SELECT content FROM cards WHERE id = 1;")); Assert.AreEqual(string.Empty, SqliteTestHelper.ScalarString(connection, "SELECT content FROM cards WHERE id = 1;"));
} }
[TestMethod] [TestMethod]
public void CardTagDuplicateAssignmentIsRejected() public void CardTagDuplicateAssignmentIsRejected()
{ {
using var db = new FreshDatabase(); using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);"); using var connection = db.Connection;
SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 1);");
// Composite primary key: the same (card, tag) pair cannot be inserted twice.
Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 1);"));
}
[TestMethod]
public void DeletingColumnCascadesToCardsAndCardTags()
{
using var db = new FreshDatabase();
InsertBoardRow(db.Connection);
SqliteTestHelper.Exec(db.Connection, "DELETE FROM columns WHERE id = 1;");
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM columns;"));
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM cards;"));
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM card_tags;"));
// Tags are never cleaned up automatically.
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;"));
}
[TestMethod]
public void DeletingCardCascadesToCardTagsOnly()
{
using var db = new FreshDatabase();
InsertBoardRow(db.Connection);
SqliteTestHelper.Exec(db.Connection, "DELETE FROM cards WHERE id = 1;");
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM columns;"));
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM cards;"));
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM card_tags;"));
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;"));
}
[TestMethod]
public void DeletingTagRemovesAssignmentsButKeepsCards()
{
using var db = new FreshDatabase();
InsertBoardRow(db.Connection);
SqliteTestHelper.Exec(db.Connection, "DELETE FROM tags WHERE id = 1;");
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;"));
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM card_tags;"));
// The card merely loses the tag.
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM cards;"));
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM columns;"));
}
/// <summary>
/// Inserts one column, one card, one tag and their assignment, ready for a cascade test.
/// </summary>
/// <param name="connection">An open workspace-schema connection.</param>
private static void InsertBoardRow(SqliteConnection connection)
{
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);"); SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);");
SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);"); SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');"); SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
SqliteTestHelper.Exec(connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 1);"); SqliteTestHelper.Exec(connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 1);");
// Composite primary key: the same (card, tag) pair cannot be inserted twice.
Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 1);"));
} }
} }
@@ -1,107 +0,0 @@
using YKanBan.Models;
using YKanBan.Storage;
using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.Workspace;
/// <summary>
/// Tests for the workspace session lifecycle: the exclusive lock is held for
/// the whole session and the repository is usable through it.
/// </summary>
[TestClass]
public class WorkspaceSessionTests
{
[TestMethod]
public void OpenHoldsLockUntilDisposed()
{
using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
using WorkspaceSession session = WorkspaceSession.Open(directory.FullPath);
// A second open while the session is alive must fail on the lock.
Assert.ThrowsExactly<WorkspaceLockException>(() => WorkspaceSession.Open(directory.FullPath));
}
[TestMethod]
public void DisposeReleasesLockForReopen()
{
using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
WorkspaceSession.Open(directory.FullPath).Dispose();
using WorkspaceSession reopened = WorkspaceSession.Open(directory.FullPath);
Assert.AreEqual(directory.FullPath, reopened.FolderPath);
}
[TestMethod]
public void OpenUninitializedFolderThrowsNotInitialized()
{
using var directory = new TempDirectory();
Assert.ThrowsExactly<WorkspaceNotInitializedException>(
() => WorkspaceSession.Open(directory.FullPath));
}
[TestMethod]
public void RepositoryIsUsableThroughSession()
{
using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
using WorkspaceSession session = WorkspaceSession.Open(directory.FullPath);
TagModel tag = session.Repository.AddTag("bug", RgbColor.Parse("#112233"), "");
Assert.AreEqual("bug", session.Repository.GetTags().Single().Name);
Assert.AreEqual(tag.Id, session.Repository.GetTags().Single().Id);
}
[TestMethod]
public void InitializeAddsPresetColumnsAndHoldsTheLock()
{
using var directory = new TempDirectory();
using WorkspaceSession session = WorkspaceSession.Initialize(directory.FullPath);
Assert.AreEqual(3, session.Repository.GetColumns().Count);
Assert.ThrowsExactly<WorkspaceLockException>(() => WorkspaceSession.Open(directory.FullPath));
}
[TestMethod]
public void InitializeWhileAnotherInstanceHoldsTheLockThrowsLockConflict()
{
using var directory = new TempDirectory();
Directory.CreateDirectory(WorkspacePaths.Root(directory.FullPath));
using WorkspaceLock held = WorkspaceLock.Acquire(directory.FullPath);
Assert.ThrowsExactly<WorkspaceLockException>(() => WorkspaceSession.Initialize(directory.FullPath));
Assert.IsFalse(File.Exists(WorkspacePaths.Database(directory.FullPath)));
}
[TestMethod]
public void FailedInitializeReleasesTheLock()
{
using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
// The database already exists, so initialization fails after taking the lock.
Assert.ThrowsExactly<InvalidOperationException>(() => WorkspaceSession.Initialize(directory.FullPath));
using WorkspaceSession reopened = WorkspaceSession.Open(directory.FullPath);
}
[TestMethod]
public void OpenWithMissingDatabaseThrowsAndCreatesNothing()
{
using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
string databasePath = WorkspacePaths.Database(directory.FullPath);
File.Delete(databasePath);
Assert.ThrowsExactly<WorkspaceDatabaseMissingException>(() => WorkspaceSession.Open(directory.FullPath));
Assert.IsFalse(File.Exists(databasePath));
// The lock was released again: the next attempt fails the same way, not with a lock conflict.
Assert.ThrowsExactly<WorkspaceDatabaseMissingException>(() => WorkspaceSession.Open(directory.FullPath));
}
}
@@ -1,50 +0,0 @@
using YKanBan.ViewModels.Dialogs;
namespace YKanBan.Tests.TestUtilities;
/// <summary>
/// Records every dialog shown and lets a test script answer it. The result
/// is whatever the dialog closed with; a dialog the script leaves open
/// counts as dismissed. The save-file dialog answers with
/// <see cref="SaveFilePath"/>.
/// </summary>
internal sealed class ScriptedDialogService : IDialogService
{
public List<DialogViewModelBase> Shown { get; } = [];
public Func<DialogViewModelBase, Task> Script { get; set; } = _ => Task.CompletedTask;
public string? SaveFilePath { get; set; }
public List<string> SuggestedFileNames { get; } = [];
public async Task<bool> ShowAsync(DialogViewModelBase dialog)
{
Shown.Add(dialog);
bool? result = null;
dialog.CloseRequested += (_, closed) => result ??= closed;
await Script(dialog);
return result ?? false;
}
public Task<string?> PickSaveFilePathAsync(string suggestedFileName)
{
SuggestedFileNames.Add(suggestedFileName);
return Task.FromResult(SaveFilePath);
}
/// <summary>Answers every confirmation dialog with the given choice.</summary>
public static Func<DialogViewModelBase, Task> AnswerConfirmations(bool confirm) => dialog =>
{
if (dialog is ConfirmDialogViewModel confirmation)
{
if (confirm)
{
confirmation.ConfirmCommand.Execute(null);
return Task.CompletedTask;
}
return confirmation.CancelCommand.ExecuteAsync(null);
}
return Task.CompletedTask;
};
}
@@ -4,19 +4,10 @@ using YKanBan.Storage.Workspace;
namespace YKanBan.Tests.TestUtilities; namespace YKanBan.Tests.TestUtilities;
/// <summary> /// <summary>Shared helpers for storage tests.</summary>
/// Shared helpers for the storage tests: small SQL conveniences plus opening a
/// workspace database with the real migration list.
/// </summary>
public static class SqliteTestHelper public static class SqliteTestHelper
{ {
/// <summary> /// <summary>Executes a non-query SQL statement and returns the affected row count.</summary>
/// Executes a non-query SQL statement and returns the affected row count.
/// </summary>
/// <param name="connection">An open database connection.</param>
/// <param name="sql">The statement to execute.</param>
/// <param name="parameters">Name/value pairs bound as SQL parameters.</param>
/// <returns>The number of affected rows.</returns>
public static int Exec(SqliteConnection connection, string sql, params (string Name, object? Value)[] parameters) public static int Exec(SqliteConnection connection, string sql, params (string Name, object? Value)[] parameters)
{ {
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
@@ -28,12 +19,7 @@ public static class SqliteTestHelper
return command.ExecuteNonQuery(); return command.ExecuteNonQuery();
} }
/// <summary> /// <summary>Returns the scalar result of a SQL query as a string.</summary>
/// Returns the scalar result of a SQL query as a string.
/// </summary>
/// <param name="connection">An open database connection.</param>
/// <param name="sql">The query to execute.</param>
/// <returns>The scalar result cast to a string.</returns>
public static string ScalarString(SqliteConnection connection, string sql) public static string ScalarString(SqliteConnection connection, string sql)
{ {
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
@@ -41,12 +27,7 @@ public static class SqliteTestHelper
return (string)command.ExecuteScalar()!; return (string)command.ExecuteScalar()!;
} }
/// <summary> /// <summary>Returns the scalar result of a SQL query as a long.</summary>
/// Returns the scalar result of a SQL query as a long.
/// </summary>
/// <param name="connection">An open database connection.</param>
/// <param name="sql">The query to execute.</param>
/// <returns>The scalar result cast to a long.</returns>
public static long ScalarLong(SqliteConnection connection, string sql) public static long ScalarLong(SqliteConnection connection, string sql)
{ {
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
@@ -54,12 +35,7 @@ public static class SqliteTestHelper
return (long)command.ExecuteScalar()!; return (long)command.ExecuteScalar()!;
} }
/// <summary> /// <summary>Returns true when a table with the given name exists.</summary>
/// Returns whether a table with the given name exists in the database.
/// </summary>
/// <param name="connection">An open database connection.</param>
/// <param name="tableName">The table name to look for.</param>
/// <returns><see langword="true"/> when the table exists.</returns>
public static bool TableExists(SqliteConnection connection, string tableName) public static bool TableExists(SqliteConnection connection, string tableName)
{ {
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
@@ -68,11 +44,7 @@ public static class SqliteTestHelper
return (long)command.ExecuteScalar()! == 1; return (long)command.ExecuteScalar()! == 1;
} }
/// <summary> /// <summary>Returns the titles of all columns, ordered by id.</summary>
/// Returns the titles of all columns, ordered by id ascending.
/// </summary>
/// <param name="connection">An open database connection.</param>
/// <returns>The column titles in id order.</returns>
public static List<string> GetColumnTitles(SqliteConnection connection) public static List<string> GetColumnTitles(SqliteConnection connection)
{ {
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
@@ -87,11 +59,7 @@ public static class SqliteTestHelper
return titles; return titles;
} }
/// <summary> /// <summary>Opens a workspace database with the real migration list.</summary>
/// Opens a workspace database with the real workspace migration list.
/// </summary>
/// <param name="folderPath">The workspace folder path.</param>
/// <returns>An open, migrated connection.</returns>
public static SqliteConnection OpenWorkspace(string folderPath) public static SqliteConnection OpenWorkspace(string folderPath)
{ {
return SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations); return SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
+4 -16
View File
@@ -2,14 +2,12 @@ namespace YKanBan.Tests.TestUtilities;
/// <summary> /// <summary>
/// Creates a unique temporary directory per test instance and removes it on /// Creates a unique temporary directory per test instance and removes it on
/// disposal. The removal is retried once because SQLite WAL sidecar files can /// disposal. Retries the deletion once because SQLite WAL files can linger
/// linger for a moment after the connections close. /// for a moment after connections close.
/// </summary> /// </summary>
public sealed class TempDirectory : IDisposable public sealed class TempDirectory : IDisposable
{ {
/// <summary> /// <summary>Unique directory path managed by this instance.</summary>
/// Gets the unique directory path managed by this instance.
/// </summary>
public string FullPath { get; } public string FullPath { get; }
public TempDirectory() public TempDirectory()
@@ -18,9 +16,6 @@ public sealed class TempDirectory : IDisposable
Directory.CreateDirectory(FullPath); Directory.CreateDirectory(FullPath);
} }
/// <summary>
/// Deletes the directory tree, retrying once after a short delay.
/// </summary>
public void Dispose() public void Dispose()
{ {
try try
@@ -30,14 +25,7 @@ public sealed class TempDirectory : IDisposable
catch (IOException) catch (IOException)
{ {
Thread.Sleep(100); Thread.Sleep(100);
try try { Directory.Delete(FullPath, recursive: true); } catch (IOException) { }
{
Directory.Delete(FullPath, recursive: true);
}
catch (IOException)
{
// Leftovers in the OS temp folder are harmless; never fail a test over cleanup.
}
} }
} }
} }
@@ -1,357 +0,0 @@
using YKanBan.Models;
using YKanBan.Search;
using YKanBan.Storage;
using YKanBan.Storage.AppData;
using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities;
using YKanBan.ViewModels.Board;
using YKanBan.ViewModels.Dialogs;
namespace YKanBan.Tests.ViewModels;
/// <summary>
/// View-model tests of the board and its dialogs against a real temporary
/// workspace, with a scripted dialog service standing in for the modal windows.
/// </summary>
[TestClass]
public class BoardViewModelTests
{
private sealed class Fixture : IDisposable
{
public TempDirectory Directory { get; } = new();
public WorkspaceRepository Repository { get; }
public AppConfig Config { get; } = new();
public ScriptedDialogService Dialogs { get; } = new();
public Fixture()
{
WorkspaceInitializer.Initialize(Directory.FullPath);
Repository = new WorkspaceRepository(Directory.FullPath);
}
public BoardViewModel CreateBoard() => new(Repository, Config, Dialogs);
public void Dispose()
{
Repository.Dispose();
Directory.Dispose();
}
}
[TestMethod]
public void RefreshListsColumnsInIdOrderAndSortsCardsWithinEachColumn()
{
using var fixture = new Fixture();
ColumnModel first = fixture.Repository.AddColumn("A", "");
ColumnModel second = fixture.Repository.AddColumn("B", "");
fixture.Repository.AddCard(first.Id, "zeta", "", []);
fixture.Repository.AddCard(first.Id, "alpha", "", []);
fixture.Repository.AddCard(second.Id, "x", "", []);
fixture.Config.Sort.Card = CardSortOption.Title;
BoardViewModel board = fixture.CreateBoard();
CollectionAssert.AreEqual(new[] { "A", "B" }, board.Columns.Select(column => column.Title).ToArray());
CollectionAssert.AreEqual(new[] { "alpha", "zeta" }, board.Columns[0].Cards.Select(card => card.Title).ToArray());
Assert.AreEqual(1, board.Columns[1].CardCount);
}
[TestMethod]
public void ChangingTheSortPersistsItToTheConfigurationAndResorts()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
fixture.Repository.AddCard(column.Id, "b", "", []);
fixture.Repository.AddCard(column.Id, "a", "", []);
BoardViewModel board = fixture.CreateBoard();
CollectionAssert.AreEqual(new[] { "b", "a" }, board.Columns[0].Cards.Select(card => card.Title).ToArray());
board.SelectedSort = board.SortOptions.Single(option => (CardSortOption)option.Value == CardSortOption.Title);
Assert.AreEqual(CardSortOption.Title, fixture.Config.Sort.Card);
CollectionAssert.AreEqual(new[] { "a", "b" }, board.Columns[0].Cards.Select(card => card.Title).ToArray());
}
[TestMethod]
public async Task WritesRefreshWithTheActiveFilterAndKeepEmptyColumns()
{
using var fixture = new Fixture();
ColumnModel todo = fixture.Repository.AddColumn("Todo", "");
ColumnModel done = fixture.Repository.AddColumn("Done", "");
CardModel match = fixture.Repository.AddCard(todo.Id, "match me", "", []);
fixture.Repository.AddCard(todo.Id, "other", "", []);
BoardViewModel board = fixture.CreateBoard();
board.ActiveFilter = SearchSqlCompiler.Compile(SearchQueryParser.Parse("match")!);
board.Refresh();
Assert.AreEqual(1, board.Columns[0].CardCount);
// A move is a write: the board re-queries with the active filter.
CardViewModel card = board.Columns[0].Cards.Single();
MoveTargetViewModel target = card.MoveTargets.Single(entry => entry.ColumnId == done.Id);
Assert.IsFalse(card.MoveTargets.Single(entry => entry.ColumnId == todo.Id).IsEnabled);
await target.Command.ExecuteAsync(target.ColumnId);
Assert.AreEqual(2, board.Columns.Count, "Columns emptied by the filter stay on the board.");
Assert.AreEqual(0, board.Columns[0].CardCount);
Assert.AreEqual(match.Id, board.Columns[1].Cards.Single().Card.Id);
}
[TestMethod]
public async Task DeclinedColumnDeletionKeepsTheColumnAndShowsItsCardCount()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
fixture.Repository.AddCard(column.Id, "", "", []);
fixture.Repository.AddCard(column.Id, "", "", []);
BoardViewModel board = fixture.CreateBoard();
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(false);
await board.Columns[0].DeleteCommand.ExecuteAsync(null);
var confirmation = (ConfirmDialogViewModel)fixture.Dialogs.Shown.Single();
StringAssert.Contains(confirmation.Message, "2");
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
}
[TestMethod]
public async Task ColumnDeletionWithoutConfirmationDeletesImmediately()
{
using var fixture = new Fixture();
fixture.Repository.AddColumn("A", "");
fixture.Config.Confirmations.DeleteColumn = false;
BoardViewModel board = fixture.CreateBoard();
await board.Columns[0].DeleteCommand.ExecuteAsync(null);
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
Assert.AreEqual(0, board.Columns.Count);
}
[TestMethod]
public async Task ConfirmedCardDeletionDeletesTheCard()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
fixture.Repository.AddCard(column.Id, "gone", "", []);
BoardViewModel board = fixture.CreateBoard();
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(true);
await board.Columns[0].Cards[0].DeleteCommand.ExecuteAsync(null);
Assert.AreEqual(0, board.Columns[0].CardCount);
Assert.AreEqual(0, fixture.Repository.GetCards().Count);
}
[TestMethod]
public async Task DuplicateColumnTitleIsReportedInsideTheDialog()
{
using var fixture = new Fixture();
fixture.Repository.AddColumn("Todo", "");
BoardViewModel board = fixture.CreateBoard();
ColumnEditorDialogViewModel? editor = null;
bool closed = false;
fixture.Dialogs.Script = dialog =>
{
editor = (ColumnEditorDialogViewModel)dialog;
editor.CloseRequested += (_, _) => closed = true;
editor.ColumnTitle = "TODO";
editor.ConfirmCommand.Execute(null);
return Task.CompletedTask;
};
await board.AddColumnCommand.ExecuteAsync(null);
Assert.IsNotNull(editor);
Assert.IsFalse(closed, "The dialog stays open on a constraint violation.");
Assert.IsTrue(editor.HasError);
StringAssert.Contains(editor.ErrorMessage, "TODO");
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
}
[TestMethod]
public async Task NewCardIsWrittenWithItsTagsOnConfirmation()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(255, 0, 0), "");
BoardViewModel board = fixture.CreateBoard();
fixture.Dialogs.Script = async dialog =>
{
switch (dialog)
{
case CardEditorDialogViewModel editor:
editor.CardTitle = "Fix it";
editor.Content = "Details";
await editor.AddTagCommand.ExecuteAsync(null);
editor.ConfirmCommand.Execute(null);
break;
case TagPickerDialogViewModel picker:
picker.PickCommand.Execute(picker.FilteredTags.Single());
break;
}
};
await board.Columns[0].AddCardCommand.ExecuteAsync(null);
CardModel card = fixture.Repository.GetCards().Single();
Assert.AreEqual("Fix it", card.Title);
Assert.AreEqual("Details", card.Content);
Assert.AreEqual(bug.Id, card.Tags.Single().Id);
Assert.AreEqual(card.Id, board.Columns[0].Cards.Single().Card.Id);
}
[TestMethod]
public void UnchangedEditConfirmationWritesNothing()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
CardModel card = fixture.Repository.AddCard(column.Id, "t", "c", []);
using (var connection = SqliteTestHelper.OpenWorkspace(fixture.Directory.FullPath))
{
SqliteTestHelper.Exec(connection, "UPDATE cards SET updated_at = 100;");
}
card = fixture.Repository.GetCard(card.Id)!;
var editor = CardEditorDialogViewModel.ForExistingCard(fixture.Repository, fixture.Dialogs, card, confirmDiscard: true);
editor.CardTitle = "changed";
editor.CardTitle = "t";
Assert.IsFalse(editor.IsDirty);
editor.ConfirmCommand.Execute(null);
Assert.AreEqual(100, fixture.Repository.GetCard(card.Id)!.UpdatedAt);
}
[TestMethod]
public async Task DirtyCancelAsksAndStaysOpenWhenDeclined()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
var editor = CardEditorDialogViewModel.ForNewCard(fixture.Repository, fixture.Dialogs, column.Id, confirmDiscard: true);
bool? closedWith = null;
editor.CloseRequested += (_, result) => closedWith = result;
editor.Content = "draft";
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(false);
await editor.RequestCancelAsync();
Assert.IsNull(closedWith, "Declining the discard keeps the editor open.");
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(true);
await editor.RequestCancelAsync();
Assert.IsFalse(closedWith);
Assert.AreEqual(0, fixture.Repository.GetCards().Count);
}
[TestMethod]
public async Task CleanCancelClosesWithoutAsking()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
var editor = CardEditorDialogViewModel.ForNewCard(fixture.Repository, fixture.Dialogs, column.Id, confirmDiscard: true);
bool? closedWith = null;
editor.CloseRequested += (_, result) => closedWith = result;
await editor.RequestCancelAsync();
Assert.IsFalse(closedWith);
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
}
[TestMethod]
public async Task TagCreatedInThePickerSurvivesACancelledCardEdit()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
var editor = CardEditorDialogViewModel.ForNewCard(fixture.Repository, fixture.Dialogs, column.Id, confirmDiscard: false);
fixture.Dialogs.Script = dialog =>
{
if (dialog is TagPickerDialogViewModel picker)
{
picker.NewName = "fresh";
picker.NewColor = "#123456";
picker.CreateCommand.Execute(null);
}
return Task.CompletedTask;
};
await editor.AddTagCommand.ExecuteAsync(null);
Assert.AreEqual("fresh", editor.Tags.Single().Name);
await editor.RequestCancelAsync();
Assert.AreEqual("fresh", fixture.Repository.GetTags().Single().Name);
Assert.AreEqual(0, fixture.Repository.GetCards().Count);
}
[TestMethod]
public void TagPickerReportsInvalidColorAndDuplicateNameWithoutClosing()
{
using var fixture = new Fixture();
fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
var picker = new TagPickerDialogViewModel(fixture.Repository, []);
bool closed = false;
picker.CloseRequested += (_, _) => closed = true;
picker.NewName = "new";
picker.NewColor = "red";
picker.CreateCommand.Execute(null);
Assert.AreEqual(YKanBan.Resources.Error_Tag_InvalidColor, picker.ErrorMessage);
picker.NewName = "BUG";
picker.NewColor = "#ff0000";
picker.CreateCommand.Execute(null);
StringAssert.Contains(picker.ErrorMessage, "BUG");
Assert.IsFalse(closed);
Assert.AreEqual(1, fixture.Repository.GetTags().Count);
}
[TestMethod]
public void TagPickerHidesAssignedTagsAndFiltersCaseInsensitively()
{
using var fixture = new Fixture();
TagModel bug = fixture.Repository.AddTag("Bug", new RgbColor(1, 2, 3), "");
fixture.Repository.AddTag("UI", new RgbColor(1, 2, 3), "");
fixture.Repository.AddTag("Build", new RgbColor(1, 2, 3), "");
var picker = new TagPickerDialogViewModel(fixture.Repository, [bug.Id]);
picker.FilterText = "bu";
CollectionAssert.AreEqual(new[] { "Build" }, picker.FilteredTags.Select(tag => tag.Name).ToArray());
picker.FilterText = "zzz";
Assert.IsTrue(picker.NoMatches);
}
[TestMethod]
public void ColumnWidthDialogCommitsPresetsAndClampsCustomPixels()
{
var settings = new ColumnWidthSettings();
var dialog = new ColumnWidthDialogViewModel(settings) { IsStandard = false, IsCustom = true, CustomPixels = 5000 };
dialog.ConfirmCommand.Execute(null);
Assert.AreEqual(ColumnWidthPreset.Custom, settings.Preset);
Assert.AreEqual(AppConfig.MaxColumnPixels, settings.CustomPixels);
Assert.AreEqual(AppConfig.MaxColumnPixels, ColumnWidths.Resolve(settings));
dialog = new ColumnWidthDialogViewModel(settings) { IsCustom = false, IsWide = true };
dialog.ConfirmCommand.Execute(null);
Assert.AreEqual(ColumnWidthPreset.Wide, settings.Preset);
Assert.AreEqual(ColumnWidths.Wide, ColumnWidths.Resolve(settings));
}
[TestMethod]
public void CardHeaderAndExcerptFollowTheDisplayRules()
{
var untitled = new CardModel(61, 1, "", "", 0, 0, []);
var titled = untitled with { Title = "Foo bar" };
Assert.AreEqual("#61", CardViewModel.FormatHeader(untitled));
Assert.AreEqual("#61 Foo bar", CardViewModel.FormatHeader(titled));
Assert.AreEqual("short", CardViewModel.MakeExcerpt(" short \n"));
string longContent = string.Concat(Enumerable.Repeat("😀", CardViewModel.ExcerptLength + 5));
string excerpt = CardViewModel.MakeExcerpt(longContent);
Assert.IsTrue(excerpt.EndsWith('…'));
Assert.AreEqual((CardViewModel.ExcerptLength * 2) + 1, excerpt.Length, "Surrogate pairs are kept whole.");
}
}
@@ -1,91 +0,0 @@
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,400 +0,0 @@
using YKanBan.Models;
using YKanBan.Storage.AppData;
using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities;
using YKanBan.ViewModels;
using YKanBan.ViewModels.Board;
using YKanBan.ViewModels.Dialogs;
using YKanBan.ViewModels.Tags;
namespace YKanBan.Tests.ViewModels;
/// <summary>
/// View-model tests of the search bar, the tags tab, the cross-tab refresh and
/// the export wiring, against a real temporary workspace with a scripted
/// dialog service.
/// </summary>
[TestClass]
public class TagsAndSearchViewModelTests
{
private sealed class Fixture : IDisposable
{
public TempDirectory Directory { get; } = new();
public WorkspaceSession Session { get; }
public WorkspaceRepository Repository => Session.Repository;
public AppConfig Config { get; } = new();
public ScriptedDialogService Dialogs { get; } = new();
public Fixture()
{
WorkspaceInitializer.Initialize(Directory.FullPath);
Session = WorkspaceSession.Open(Directory.FullPath);
}
public BoardViewModel CreateBoard() => new(Repository, Config, Dialogs);
public TagsViewModel CreateTags() => new(Repository, Config, Dialogs);
public WorkspaceViewModel CreateWorkspace() =>
new(Session, new Interaction<Unit>(), new Interaction<Unit>(), Config, Dialogs);
public void Dispose()
{
Session.Dispose();
Directory.Dispose();
}
}
private static string[] VisibleTitles(BoardViewModel board) =>
board.Columns.SelectMany(column => column.Cards).Select(card => card.Title).Order(StringComparer.Ordinal).ToArray();
/// <summary>Moves a visible card through its menu command.</summary>
private static Task MoveAsync(BoardViewModel board, long cardId, long columnId) =>
board.Columns.SelectMany(column => column.Cards).Single(card => card.Card.Id == cardId)
.MoveToCommand.ExecuteAsync(columnId);
#region Search
[TestMethod]
public async Task SearchFiltersCardsAndKeepsEmptyColumns()
{
using var fixture = new Fixture();
ColumnModel first = fixture.Repository.AddColumn("A", "");
ColumnModel second = fixture.Repository.AddColumn("B", "");
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
fixture.Repository.AddCard(first.Id, "crash", "", [bug.Id]);
fixture.Repository.AddCard(second.Id, "idea", "", []);
BoardViewModel board = fixture.CreateBoard();
board.SearchText = "tag:BUG";
await board.SearchCommand.ExecuteAsync(null);
CollectionAssert.AreEqual(new[] { "crash" }, VisibleTitles(board));
Assert.AreEqual(2, board.Columns.Count);
Assert.AreEqual(0, board.Columns[1].CardCount);
Assert.IsNotNull(board.ActiveFilter);
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
}
[TestMethod]
public async Task InvalidSearchShowsTheErrorAndKeepsTextAndPreviousResult()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
fixture.Repository.AddCard(column.Id, "alpha", "", []);
fixture.Repository.AddCard(column.Id, "beta", "", []);
BoardViewModel board = fixture.CreateBoard();
board.SearchText = "alpha";
await board.SearchCommand.ExecuteAsync(null);
board.SearchText = "alpha AND";
await board.SearchCommand.ExecuteAsync(null);
var error = (MessageDialogViewModel)fixture.Dialogs.Shown.Single();
Assert.AreEqual(Resources.Search_Error_Title, error.Title);
Assert.AreEqual("alpha AND", board.SearchText);
CollectionAssert.AreEqual(new[] { "alpha" }, VisibleTitles(board));
}
[TestMethod]
public async Task WritesRefreshWithTheLastSuccessfulExpressionNotTheBoxText()
{
using var fixture = new Fixture();
ColumnModel first = fixture.Repository.AddColumn("A", "");
ColumnModel second = fixture.Repository.AddColumn("B", "");
CardModel alpha = fixture.Repository.AddCard(first.Id, "alpha", "", []);
fixture.Repository.AddCard(first.Id, "beta", "", []);
BoardViewModel board = fixture.CreateBoard();
board.SearchText = "alpha";
await board.SearchCommand.ExecuteAsync(null);
board.SearchText = "beta";
await MoveAsync(board, alpha.Id, second.Id);
CollectionAssert.AreEqual(new[] { "alpha" }, VisibleTitles(board));
Assert.AreEqual(1, board.Columns[1].CardCount);
}
[TestMethod]
public async Task BlankSearchAndClearShowEveryCard()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
fixture.Repository.AddCard(column.Id, "alpha", "", []);
fixture.Repository.AddCard(column.Id, "beta", "", []);
BoardViewModel board = fixture.CreateBoard();
board.SearchText = "alpha";
await board.SearchCommand.ExecuteAsync(null);
board.SearchText = " ";
await board.SearchCommand.ExecuteAsync(null);
Assert.IsNull(board.ActiveFilter);
CollectionAssert.AreEqual(new[] { "alpha", "beta" }, VisibleTitles(board));
board.SearchText = "alpha";
await board.SearchCommand.ExecuteAsync(null);
Assert.IsTrue(board.HasSearchText);
board.ClearSearchCommand.Execute(null);
Assert.AreEqual("", board.SearchText);
Assert.IsFalse(board.HasSearchText);
Assert.IsNull(board.ActiveFilter);
CollectionAssert.AreEqual(new[] { "alpha", "beta" }, VisibleTitles(board));
}
[TestMethod]
public async Task DataWrittenIsRaisedForWritesButNotForSearchOrSort()
{
using var fixture = new Fixture();
ColumnModel first = fixture.Repository.AddColumn("A", "");
ColumnModel second = fixture.Repository.AddColumn("B", "");
CardModel card = fixture.Repository.AddCard(first.Id, "x", "", []);
BoardViewModel board = fixture.CreateBoard();
int raised = 0;
board.DataWritten += (_, _) => raised++;
board.SearchText = "x";
await board.SearchCommand.ExecuteAsync(null);
board.SelectedSort = board.SortOptions[1];
Assert.AreEqual(0, raised);
await MoveAsync(board, card.Id, second.Id);
Assert.AreEqual(1, raised);
}
#endregion
#region Tags tab
[TestMethod]
public void TagsListInIdOrderWithUsageCounts()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "Broken");
TagModel unused = fixture.Repository.AddTag("unused", new RgbColor(4, 5, 6), "");
fixture.Repository.AddCard(column.Id, "a", "", [bug.Id]);
fixture.Repository.AddCard(column.Id, "b", "", [bug.Id]);
TagsViewModel tags = fixture.CreateTags();
CollectionAssert.AreEqual(new[] { bug.Id, unused.Id }, tags.Tags.Select(row => row.Tag.Id).ToArray());
CollectionAssert.AreEqual(new long[] { 2, 0 }, tags.Tags.Select(row => row.UsageCount).ToArray());
Assert.IsTrue(tags.Tags[0].HasDescription);
Assert.AreEqual("#010203", tags.Tags[0].ColorText);
Assert.IsFalse(tags.IsEmpty);
}
[TestMethod]
public async Task NewTagIsWrittenAndAnnounced()
{
using var fixture = new Fixture();
TagsViewModel tags = fixture.CreateTags();
int changed = 0;
tags.TagsChanged += (_, _) => changed++;
fixture.Dialogs.Script = dialog =>
{
var editor = (TagEditorDialogViewModel)dialog;
editor.Name = "ui";
editor.PickSwatchCommand.Execute(TagColors.Palette[2].ToString());
editor.Description = "Looks";
editor.ConfirmCommand.Execute(null);
return Task.CompletedTask;
};
await tags.AddTagCommand.ExecuteAsync(null);
TagModel created = fixture.Repository.GetTags().Single();
Assert.AreEqual("ui", created.Name);
Assert.AreEqual(TagColors.Palette[2], created.Color);
Assert.AreEqual("Looks", created.Description);
Assert.AreEqual(1, tags.Tags.Count);
Assert.AreEqual(1, changed);
}
[TestMethod]
public async Task TagEditorKeepsTheDialogOpenOnDuplicateNameOrInvalidColor()
{
using var fixture = new Fixture();
fixture.Repository.AddTag("Bug", new RgbColor(1, 2, 3), "");
TagsViewModel tags = fixture.CreateTags();
TagEditorDialogViewModel? editor = null;
bool closed = false;
fixture.Dialogs.Script = dialog =>
{
editor = (TagEditorDialogViewModel)dialog;
editor.CloseRequested += (_, _) => closed = true;
editor.Name = "bug";
editor.ConfirmCommand.Execute(null);
return Task.CompletedTask;
};
await tags.AddTagCommand.ExecuteAsync(null);
Assert.IsNotNull(editor);
Assert.IsTrue(editor.HasError);
Assert.IsFalse(closed);
Assert.AreEqual("bug", editor.Name);
editor.Name = "other";
editor.Color = "red";
editor.ConfirmCommand.Execute(null);
Assert.AreEqual(Resources.Error_Tag_InvalidColor, editor.ErrorMessage);
Assert.IsFalse(closed);
Assert.AreEqual(1, fixture.Repository.GetTags().Count);
}
[TestMethod]
public async Task EditingATagRenamesRecolorsAndDescribesIt()
{
using var fixture = new Fixture();
TagModel tag = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
TagsViewModel tags = fixture.CreateTags();
fixture.Dialogs.Script = dialog =>
{
var editor = (TagEditorDialogViewModel)dialog;
Assert.AreEqual("bug", editor.Name);
Assert.AreEqual("#010203", editor.Color);
editor.Name = "defect";
editor.Color = "#ABCDEF";
editor.Description = "Broken";
editor.ConfirmCommand.Execute(null);
return Task.CompletedTask;
};
await tags.Tags[0].EditCommand.ExecuteAsync(null);
TagModel updated = fixture.Repository.GetTags().Single();
Assert.AreEqual(tag.Id, updated.Id);
Assert.AreEqual("defect", updated.Name);
Assert.AreEqual(new RgbColor(0xab, 0xcd, 0xef), updated.Color);
Assert.AreEqual("Broken", updated.Description);
Assert.AreEqual("defect", tags.Tags[0].Badge.Name);
}
[TestMethod]
public async Task DeletingATagAsksFirstAndKeepsTheCards()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
CardModel card = fixture.Repository.AddCard(column.Id, "a", "", [bug.Id]);
TagsViewModel tags = fixture.CreateTags();
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(false);
await tags.Tags[0].DeleteCommand.ExecuteAsync(null);
Assert.AreEqual(1, fixture.Repository.GetTags().Count);
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(true);
await tags.Tags[0].DeleteCommand.ExecuteAsync(null);
Assert.AreEqual(0, fixture.Repository.GetTags().Count);
Assert.IsTrue(tags.IsEmpty);
CardModel kept = fixture.Repository.GetCard(card.Id)!;
Assert.AreEqual(0, kept.Tags.Count);
}
[TestMethod]
public async Task DeletingATagWithoutConfirmationShowsNoDialog()
{
using var fixture = new Fixture();
fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
fixture.Config.Confirmations.DeleteTag = false;
TagsViewModel tags = fixture.CreateTags();
await tags.Tags[0].DeleteCommand.ExecuteAsync(null);
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
Assert.AreEqual(0, fixture.Repository.GetTags().Count);
}
#endregion
#region Workspace wiring and export
[TestMethod]
public async Task TagWritesRefreshTheBoardAndBoardWritesRefreshTheTags()
{
using var fixture = new Fixture();
ColumnModel first = fixture.Repository.AddColumn("A", "");
ColumnModel second = fixture.Repository.AddColumn("B", "");
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
CardModel card = fixture.Repository.AddCard(first.Id, "a", "", [bug.Id]);
WorkspaceViewModel workspace = fixture.CreateWorkspace();
// A filtered board drops the card once the tag is gone.
workspace.Board.SearchText = "tag:bug";
await workspace.Board.SearchCommand.ExecuteAsync(null);
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(true);
await workspace.Tags.Tags[0].DeleteCommand.ExecuteAsync(null);
Assert.AreEqual(0, workspace.Board.Columns.Sum(column => column.CardCount));
// Re-tag through the repository, then a board write updates the usage count.
workspace.Board.ClearSearchCommand.Execute(null);
TagModel ui = fixture.Repository.AddTag("ui", new RgbColor(4, 5, 6), "");
fixture.Repository.UpdateCard(card.Id, "a", "", [ui.Id]);
Assert.AreEqual(0, workspace.Tags.Tags.Count);
await MoveAsync(workspace.Board, card.Id, second.Id);
Assert.AreEqual(1, workspace.Tags.Tags.Single().UsageCount);
}
[TestMethod]
public async Task ExportWritesTheWholeWorkspaceIgnoringTheSearch()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
fixture.Repository.AddCard(column.Id, "alpha", "", []);
fixture.Repository.AddCard(column.Id, "beta", "", []);
WorkspaceViewModel workspace = fixture.CreateWorkspace();
workspace.Board.SearchText = "alpha";
await workspace.Board.SearchCommand.ExecuteAsync(null);
string path = Path.Combine(fixture.Directory.FullPath, "out.md");
fixture.Dialogs.SaveFilePath = path;
await workspace.ExportCommand.ExecuteAsync(null);
string suggested = fixture.Dialogs.SuggestedFileNames.Single();
StringAssert.StartsWith(suggested, workspace.WorkspaceName);
StringAssert.EndsWith(suggested, ".md");
string markdown = File.ReadAllText(path);
StringAssert.Contains(markdown, "alpha");
StringAssert.Contains(markdown, "beta");
byte[] bytes = File.ReadAllBytes(path);
Assert.AreNotEqual(0xEF, bytes[0], "The export must not start with a UTF-8 BOM.");
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
}
[TestMethod]
public async Task CancelledExportWritesNothing()
{
using var fixture = new Fixture();
WorkspaceViewModel workspace = fixture.CreateWorkspace();
fixture.Dialogs.SaveFilePath = null;
await workspace.ExportCommand.ExecuteAsync(null);
Assert.AreEqual(1, fixture.Dialogs.SuggestedFileNames.Count);
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
Assert.AreEqual(0, System.IO.Directory.GetFiles(fixture.Directory.FullPath, "*.md").Length);
}
[TestMethod]
public async Task ExportWriteFailureIsReportedInAMessageDialog()
{
using var fixture = new Fixture();
WorkspaceViewModel workspace = fixture.CreateWorkspace();
fixture.Dialogs.SaveFilePath = Path.Combine(fixture.Directory.FullPath, "missing-folder", "out.md");
await workspace.ExportCommand.ExecuteAsync(null);
var message = (MessageDialogViewModel)fixture.Dialogs.Shown.Single();
Assert.AreEqual(Resources.Export_Failed_Title, message.Title);
Assert.IsTrue(message.HasDetails);
}
#endregion
}
+2 -5
View File
@@ -1,11 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -15,5 +13,4 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\YKanBan\YKanBan.csproj" /> <ProjectReference Include="..\YKanBan\YKanBan.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+7 -27
View File
@@ -1,45 +1,25 @@
<Application xmlns="https://github.com/avaloniaui" <Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="YKanBan.App" x:Class="YKanBan.App"
xmlns:local="using:YKanBan"
xmlns:semi="https://irihi.tech/semi" xmlns:semi="https://irihi.tech/semi"
RequestedThemeVariant="Default"> RequestedThemeVariant="Default">
<Application.DataTemplates>
<local:ViewLocator/>
</Application.DataTemplates>
<Application.Styles> <Application.Styles>
<!-- Semi.Avalonia provides the light and dark palettes; icons need their own theme. --> <semi:SemiTheme />
<semi:SemiTheme/>
<StyleInclude Source="avares://IconPacks.Avalonia.Lucide/Lucide.axaml"/>
</Application.Styles> </Application.Styles>
<!-- <!--Custom colors MUST be declared as Light/Dark pairs inside ThemeDictionaries
Custom colors are declared as Light/Dark pairs and consumed through and consumed via DynamicResource so theme switches restyle everything.-->
DynamicResource, so a theme switch restyles every surface. Tag colors are
user data and stay as their literal #RRGGBB value.
-->
<Application.Resources> <Application.Resources>
<ResourceDictionary> <ResourceDictionary>
<ResourceDictionary.ThemeDictionaries> <ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Light"> <ResourceDictionary x:Key="Light">
<SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#F6F7F9"/> <SolidColorBrush x:Key="SidebarBackgroundBrush" Color="#F6F7F9"/>
<SolidColorBrush x:Key="TopBarBorderBrush" Color="#E2E4EA"/> <SolidColorBrush x:Key="SidebarBorderBrush" Color="#E2E4EA"/>
<SolidColorBrush x:Key="PanelBorderBrush" Color="#E2E4EA"/>
<SolidColorBrush x:Key="ColumnBackgroundBrush" Color="#F3F4F7"/>
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="CardForegroundBrush" Color="#1C1F23"/>
<SolidColorBrush x:Key="ErrorTextBrush" Color="#D52515"/>
</ResourceDictionary> </ResourceDictionary>
<ResourceDictionary x:Key="Dark"> <ResourceDictionary x:Key="Dark">
<SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#1C1E24"/> <SolidColorBrush x:Key="SidebarBackgroundBrush" Color="#1C1E24"/>
<SolidColorBrush x:Key="TopBarBorderBrush" Color="#2C2F37"/> <SolidColorBrush x:Key="SidebarBorderBrush" Color="#2C2F37"/>
<SolidColorBrush x:Key="PanelBorderBrush" Color="#33363F"/>
<SolidColorBrush x:Key="ColumnBackgroundBrush" Color="#1A1C21"/>
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#25282F"/>
<SolidColorBrush x:Key="CardForegroundBrush" Color="#E6E8EC"/>
<SolidColorBrush x:Key="ErrorTextBrush" Color="#FC725A"/>
</ResourceDictionary> </ResourceDictionary>
</ResourceDictionary.ThemeDictionaries> </ResourceDictionary.ThemeDictionaries>
</ResourceDictionary> </ResourceDictionary>
+43 -41
View File
@@ -1,10 +1,13 @@
using System.Globalization; using System.Globalization;
using Avalonia; using Avalonia;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core;
using Avalonia.Data.Core.Plugins; using Avalonia.Data.Core.Plugins;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Styling; using Avalonia.Styling;
using Avalonia.Threading;
using YKanBan.Ipc;
using YKanBan.Services; using YKanBan.Services;
using YKanBan.Storage.AppData; using YKanBan.Storage.AppData;
using YKanBan.ViewModels; using YKanBan.ViewModels;
@@ -15,23 +18,12 @@ namespace YKanBan;
public partial class App : Application public partial class App : Application
{ {
/// <summary> /// <summary>Composition root, created before the main window.</summary>
/// Gets the process-wide composition root, created at startup. public static AppServices Services { get; } = new();
/// </summary>
public static AppServices? Services { get; private set; }
/// <summary> /// <summary>The language applied at startup; a live selection differing from it needs a restart.</summary>
/// Gets the language applied at startup; a live selection differing from it
/// needs a restart.
/// </summary>
public static string StartupLanguage { get; private set; } = AppConfig.DefaultLanguage; public 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);
@@ -43,40 +35,34 @@ public partial class App : Application
{ {
DisableAvaloniaDataAnnotationValidation(); DisableAvaloniaDataAnnotationValidation();
// Startup order: apply the configured culture, its RTL flow direction // Startup order: apply the configured culture (and its RTL flow direction)
// and the theme BEFORE creating the main window. // and the theme BEFORE creating the main window.
Services = new AppServices();
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 dialogs = new DialogService(); var mainViewModel = new MainWindowViewModel(Services);
var viewModel = new MainWindowViewModel(Services, dialogs, desktop.Args ?? []); desktop.MainWindow = new MainWindow
var mainWindow = new MainWindow
{ {
DataContext = viewModel, DataContext = mainViewModel,
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,
}; };
dialogs.Attach(mainWindow);
desktop.MainWindow = mainWindow; // Primary instance: serve launch commands forwarded by secondary instances.
Program.SingleInstance?.StartServer(command => HandleLaunchCommand(desktop, mainViewModel, command));
} }
base.OnFrameworkInitializationCompleted(); base.OnFrameworkInitializationCompleted();
} }
/// <summary> /// <summary>Resolves the configured language to a culture, falling back to English.</summary>
/// Resolves a configured language to a culture, falling back to English.
/// </summary>
/// <param name="language">The language code from app.json.</param>
/// <returns>The resolved culture.</returns>
public static CultureInfo ResolveCulture(string language) public static CultureInfo ResolveCulture(string language)
{ {
try try
@@ -89,18 +75,13 @@ public partial class App : Application
} }
} }
/// <summary> /// <summary>Applies a theme selection immediately; Default follows the operating system.</summary>
/// Applies a theme selection immediately; <see cref="ThemeOption.FollowSystem"/>
/// inherits the operating system preference.
/// </summary>
/// <param name="option">The theme selection.</param>
public static void ApplyTheme(ThemeOption option) public static void ApplyTheme(ThemeOption option)
{ {
if (Current is null) if (Current is null)
{ {
return; return;
} }
Current.RequestedThemeVariant = option switch Current.RequestedThemeVariant = option switch
{ {
ThemeOption.Light => ThemeVariant.Light, ThemeOption.Light => ThemeVariant.Light,
@@ -109,6 +90,27 @@ public partial class App : Application
}; };
} }
/// <summary>Activates the window for a forwarded command; OpenWorkspace also switches to it.</summary>
private static void HandleLaunchCommand(
IClassicDesktopStyleApplicationLifetime desktop,
MainWindowViewModel mainViewModel,
LaunchCommand command)
{
// IPC delivery happens on a background thread; hop to the UI thread.
Dispatcher.UIThread.Post(() =>
{
if (desktop.MainWindow is { } window)
{
window.Show();
window.Activate();
}
if (command is LaunchCommand.OpenWorkspace open)
{
mainViewModel.OpenWorkspaceFromLaunch(open.Path);
}
});
}
private static void DisableAvaloniaDataAnnotationValidation() private static void DisableAvaloniaDataAnnotationValidation()
{ {
var dataValidationPluginsToRemove = var dataValidationPluginsToRemove =
+95 -300
View File
@@ -1,9 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!--
English (neutral) resources. Any key missing from a satellite culture falls back to here.
This file is processed by the cross-platform MSBuild strongly-typed resource generator; see YKanBan.csproj.
-->
<resheader name="resmimetype"> <resheader name="resmimetype">
<value>text/microsoft-resx</value> <value>text/microsoft-resx</value>
</resheader> </resheader>
@@ -16,83 +12,92 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<data name="PresetColumn_Todo" xml:space="preserve">
<value>To Do</value>
</data>
<data name="PresetColumn_InProgress" xml:space="preserve">
<value>In Progress</value>
</data>
<data name="PresetColumn_Done" xml:space="preserve">
<value>Done</value>
</data>
<data name="Export_FileNamePattern" xml:space="preserve">
<value>{0}-export-{1:yyyyMMdd-HHmmss}.md</value>
</data>
<data name="Export_TimePattern" xml:space="preserve">
<value>yyyy-MM-dd HH:mm:ss</value>
</data>
<data name="Export_CardTimePattern" xml:space="preserve">
<value>yyyy-MM-dd HH:mm</value>
</data>
<data name="Export_WorkspaceHeading" xml:space="preserve">
<value># {0}</value>
</data>
<data name="Export_ExportedAtLine" xml:space="preserve">
<value>> Exported at: {0}</value>
</data>
<data name="Export_ColumnHeading" xml:space="preserve">
<value>## Column: {0} ({1})</value>
</data>
<data name="Export_TagsLine" xml:space="preserve">
<value>- Tags: {0}</value>
</data>
<data name="Export_CreatedModifiedLine" xml:space="preserve">
<value>- Created: {0} Modified: {1}</value>
</data>
<data name="Export_TagsSummaryHeading" xml:space="preserve">
<value>## Tags</value>
</data>
<data name="Export_TagsTableHeader" xml:space="preserve">
<value>| Name | Color | Description | Usage |</value>
</data>
<data name="App_Name" xml:space="preserve"> <data name="App_Name" xml:space="preserve">
<value>YKanBan</value> <value>YKanBan</value>
</data> </data>
<data name="Common_Ok" xml:space="preserve"> <data name="Common_Yes" xml:space="preserve">
<value>OK</value> <value>Yes</value>
</data> </data>
<data name="Common_Cancel" xml:space="preserve"> <data name="Common_No" xml:space="preserve">
<value>Cancel</value> <value>No</value>
</data> </data>
<data name="Main_Export" xml:space="preserve"> <data name="Common_Close" xml:space="preserve">
<value>Export</value> <value>Close</value>
</data> </data>
<data name="Main_Settings" xml:space="preserve"> <data name="Sidebar_Welcome" xml:space="preserve">
<value>Welcome</value>
</data>
<data name="Sidebar_OpenProject" xml:space="preserve">
<value>Open project…</value>
</data>
<data name="Sidebar_SortLabel" xml:space="preserve">
<value>Sort</value>
</data>
<data name="Sidebar_Sort_NameAsc" xml:space="preserve">
<value>Name A to Z</value>
</data>
<data name="Sidebar_Sort_NameDesc" xml:space="preserve">
<value>Name Z to A</value>
</data>
<data name="Sidebar_Sort_RecentlyUpdated" xml:space="preserve">
<value>Recently updated</value>
</data>
<data name="Sidebar_Settings" xml:space="preserve">
<value>Settings</value> <value>Settings</value>
</data> </data>
<data name="Main_About" xml:space="preserve"> <data name="Sidebar_About" xml:space="preserve">
<value>About</value> <value>About</value>
</data> </data>
<data name="Tab_Tags" xml:space="preserve"> <data name="Sidebar_RemoveFromList" xml:space="preserve">
<value>Tags</value> <value>Remove from list</value>
</data> </data>
<data name="Tab_Board" xml:space="preserve"> <data name="Welcome_Hint" xml:space="preserve">
<value>Board</value> <value>Open or create a workspace from the left.</value>
</data> </data>
<data name="Error_Argument_Title" xml:space="preserve"> <data name="Dialog_InitializeTitle" xml:space="preserve">
<value>Invalid arguments</value> <value>Initialize workspace?</value>
</data> </data>
<data name="Error_Argument_Message" xml:space="preserve"> <data name="Dialog_InitializeMessage" xml:space="preserve">
<value>YKanBan was started with invalid command-line arguments.</value> <value>There is no .ykanban structure in "{0}". Initialize it here?</value>
</data>
<data name="Error_Argument_Usage" xml:space="preserve">
<value>Usage: ykanban &lt;path&gt;</value>
</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">
<value>No workspace here</value>
</data>
<data name="Error_NotInitialized_Message" xml:space="preserve">
<value>The folder does not contain a .ykanban workspace: {0}</value>
</data>
<data name="Error_NotInitialized_Initialize" xml:space="preserve">
<value>Initialize workspace</value>
</data>
<data name="Error_LockConflict_Title" xml:space="preserve">
<value>Workspace locked</value>
</data>
<data name="Error_LockConflict_Message" xml:space="preserve">
<value>The workspace is already open in another instance: {0}</value>
</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> </data>
<data name="Settings_Title" xml:space="preserve"> <data name="Settings_Title" xml:space="preserve">
<value>Settings</value> <value>Settings</value>
@@ -145,250 +150,40 @@
<data name="About_Repository" xml:space="preserve"> <data name="About_Repository" xml:space="preserve">
<value>Repository</value> <value>Repository</value>
</data> </data>
<data name="About_RepositoryUrl" xml:space="preserve">
<value>(to be filled)</value>
</data>
<data name="About_License" xml:space="preserve"> <data name="About_License" xml:space="preserve">
<value>License</value> <value>License</value>
</data> </data>
<data name="About_LicenseValue" xml:space="preserve"> <data name="About_LicenseValue" xml:space="preserve">
<value>MIT</value> <value>(to be filled)</value>
</data> </data>
<data name="PresetColumn_Todo" xml:space="preserve"> <data name="State_LockConflict_Title" xml:space="preserve">
<value>To Do</value> <value>Workspace locked</value>
</data> </data>
<data name="PresetColumn_InProgress" xml:space="preserve"> <data name="State_LockConflict_Detail" xml:space="preserve">
<value>In Progress</value> <value>The workspace is locked by another instance.</value>
</data> </data>
<data name="PresetColumn_Done" xml:space="preserve"> <data name="State_NotInitialized_Title" xml:space="preserve">
<value>Done</value> <value>No workspace here</value>
</data> </data>
<data name="Export_FileNamePattern" xml:space="preserve"> <data name="State_NotInitialized_Detail" xml:space="preserve">
<value>{0}-export-{1:yyyyMMdd-HHmmss}.md</value> <value>The folder has no .ykanban structure.</value>
</data> </data>
<data name="Export_TimePattern" xml:space="preserve"> <data name="State_DirectoryMissing_Title" xml:space="preserve">
<value>yyyy-MM-dd HH:mm:ss</value> <value>Folder missing</value>
</data> </data>
<data name="Export_WorkspaceHeading" xml:space="preserve"> <data name="State_DirectoryMissing_Detail" xml:space="preserve">
<value># {0}</value> <value>The folder does not exist on disk.</value>
</data> </data>
<data name="Export_ExportedAtLine" xml:space="preserve"> <data name="State_SchemaVersion_Title" xml:space="preserve">
<value>&gt; Exported at: {0}</value> <value>Incompatible database</value>
</data> </data>
<data name="Export_ColumnHeading" xml:space="preserve"> <data name="State_SchemaVersion_Detail" xml:space="preserve">
<value>## Column: {0} ({1})</value> <value>The workspace was written by a newer version.</value>
</data> </data>
<data name="Export_TagsLine" xml:space="preserve"> <data name="State_Unknown_Title" xml:space="preserve">
<value>- Tags: {0}</value> <value>Open failed</value>
</data>
<data name="Export_CreatedModifiedLine" xml:space="preserve">
<value>- Created: {0} Modified: {1}</value>
</data>
<data name="Export_TagsSummaryHeading" xml:space="preserve">
<value>## Tags</value>
</data>
<data name="Export_TagsTableHeader" xml:space="preserve">
<value>| Name | Color | Description | Usage |</value>
</data>
<data name="Common_Delete" xml:space="preserve">
<value>Delete</value>
</data>
<data name="Common_Discard" xml:space="preserve">
<value>Discard</value>
</data>
<data name="Common_TimePattern" xml:space="preserve">
<value>yyyy-MM-dd HH:mm</value>
</data>
<data name="Board_AddColumn" xml:space="preserve">
<value>New column</value>
</data>
<data name="Board_ColumnWidth" xml:space="preserve">
<value>Column width</value>
</data>
<data name="Board_Sort" xml:space="preserve">
<value>Card order</value>
</data>
<data name="Board_AddCard" xml:space="preserve">
<value>New card</value>
</data>
<data name="Sort_Id" xml:space="preserve">
<value>By id</value>
</data>
<data name="Sort_UpdatedAt" xml:space="preserve">
<value>Recently modified</value>
</data>
<data name="Sort_Title" xml:space="preserve">
<value>By title</value>
</data>
<data name="Menu_More" xml:space="preserve">
<value>More</value>
</data>
<data name="Menu_Edit" xml:space="preserve">
<value>Edit</value>
</data>
<data name="Menu_Delete" xml:space="preserve">
<value>Delete</value>
</data>
<data name="Menu_MoveTo" xml:space="preserve">
<value>Move to column</value>
</data>
<data name="Field_Title" xml:space="preserve">
<value>Title</value>
</data>
<data name="Field_Description" xml:space="preserve">
<value>Description</value>
</data>
<data name="Field_Content" xml:space="preserve">
<value>Content</value>
</data>
<data name="Field_Tags" xml:space="preserve">
<value>Tags</value>
</data>
<data name="Field_Name" xml:space="preserve">
<value>Name</value>
</data>
<data name="Field_Color" xml:space="preserve">
<value>#RRGGBB</value>
</data>
<data name="ColumnEditor_TitleNew" xml:space="preserve">
<value>New column</value>
</data>
<data name="ColumnEditor_TitleEdit" xml:space="preserve">
<value>Edit column</value>
</data>
<data name="ColumnWidth_Title" xml:space="preserve">
<value>Column width</value>
</data>
<data name="ColumnWidth_Narrow" xml:space="preserve">
<value>Narrow ({0} px)</value>
</data>
<data name="ColumnWidth_Standard" xml:space="preserve">
<value>Standard ({0} px)</value>
</data>
<data name="ColumnWidth_Wide" xml:space="preserve">
<value>Wide ({0} px)</value>
</data>
<data name="ColumnWidth_Custom" xml:space="preserve">
<value>Custom</value>
</data>
<data name="ColumnWidth_Range" xml:space="preserve">
<value>{0}–{1} px</value>
</data>
<data name="CardEditor_TitleNew" xml:space="preserve">
<value>New card</value>
</data>
<data name="CardEditor_TitleEdit" xml:space="preserve">
<value>Edit card</value>
</data>
<data name="CardEditor_TitleWatermark" xml:space="preserve">
<value>No title</value>
</data>
<data name="CardEditor_Created" xml:space="preserve">
<value>Created {0}</value>
</data>
<data name="CardEditor_Modified" xml:space="preserve">
<value>Modified {0}</value>
</data>
<data name="CardEditor_AddTag" xml:space="preserve">
<value>Add tag</value>
</data>
<data name="CardEditor_RemoveTag" xml:space="preserve">
<value>Remove tag</value>
</data>
<data name="TagPicker_Title" xml:space="preserve">
<value>Add tag</value>
</data>
<data name="TagPicker_FilterWatermark" xml:space="preserve">
<value>Filter tags</value>
</data>
<data name="TagPicker_NoMatches" xml:space="preserve">
<value>No matching tags</value>
</data>
<data name="TagPicker_NewTag" xml:space="preserve">
<value>New tag</value>
</data>
<data name="TagPicker_Create" xml:space="preserve">
<value>Create and add</value>
</data>
<data name="Confirm_Title" xml:space="preserve">
<value>Confirm</value>
</data>
<data name="Confirm_DeleteCard" xml:space="preserve">
<value>Delete card "{0}"?</value>
</data>
<data name="Confirm_DeleteColumn" xml:space="preserve">
<value>Delete column "{0}" and its {1} card(s)?</value>
</data>
<data name="Confirm_DiscardEdit" xml:space="preserve">
<value>Discard the unsaved changes?</value>
</data>
<data name="Error_Column_TitleRequired" xml:space="preserve">
<value>The column title is required.</value>
</data>
<data name="Error_Column_Duplicate" xml:space="preserve">
<value>A column named "{0}" already exists (names are case-insensitive).</value>
</data>
<data name="Error_Tag_NameRequired" xml:space="preserve">
<value>The tag name is required.</value>
</data>
<data name="Error_Tag_Duplicate" xml:space="preserve">
<value>A tag named "{0}" already exists (names are case-insensitive).</value>
</data>
<data name="Error_Tag_InvalidColor" xml:space="preserve">
<value>The color must be written as #RRGGBB.</value>
</data>
<data name="Error_SaveFailed" xml:space="preserve">
<value>Saving failed: {0}</value>
</data>
<data name="Error_Operation_Title" xml:space="preserve">
<value>Operation failed</value>
</data>
<data name="Error_Operation_Message" xml:space="preserve">
<value>The change could not be written to the workspace. The board shows the stored state.</value>
</data>
<data name="TagEditor_TitleNew" xml:space="preserve">
<value>New tag</value>
</data>
<data name="TagEditor_TitleEdit" xml:space="preserve">
<value>Edit tag</value>
</data>
<data name="TagEditor_ColorLabel" xml:space="preserve">
<value>Color</value>
</data>
<data name="Tags_AddTag" xml:space="preserve">
<value>New tag</value>
</data>
<data name="Tags_Summary" xml:space="preserve">
<value>{0} tag(s)</value>
</data>
<data name="Tags_UsageCount" xml:space="preserve">
<value>{0} card(s)</value>
</data>
<data name="Tags_Empty" xml:space="preserve">
<value>No tags yet.</value>
</data>
<data name="Confirm_DeleteTag" xml:space="preserve">
<value>Delete tag "{0}"? It will be removed from {1} card(s).</value>
</data>
<data name="Board_SearchWatermark" xml:space="preserve">
<value>Search, e.g. tag:bug OR title:login</value>
</data>
<data name="Board_Search" xml:space="preserve">
<value>Search</value>
</data>
<data name="Board_ClearSearch" xml:space="preserve">
<value>Clear</value>
</data>
<data name="Search_Error_Title" xml:space="preserve">
<value>Invalid search</value>
</data>
<data name="Search_Error_Message" xml:space="preserve">
<value>The query expression is invalid. Details: {0}</value>
</data>
<data name="Export_FileTypeMarkdown" xml:space="preserve">
<value>Markdown document</value>
</data>
<data name="Export_Failed_Title" xml:space="preserve">
<value>Export failed</value>
</data>
<data name="Export_Failed_Message" xml:space="preserve">
<value>The export file could not be written.</value>
</data> </data>
</root> </root>
+93 -298
View File
@@ -1,9 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!--
Simplified Chinese (zh-Hans) satellite resources.
This file is embedded beside the neutral resources; see YKanBan.csproj.
-->
<resheader name="resmimetype"> <resheader name="resmimetype">
<value>text/microsoft-resx</value> <value>text/microsoft-resx</value>
</resheader> </resheader>
@@ -16,141 +12,6 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<data name="App_Name" xml:space="preserve">
<value>YKanBan</value>
</data>
<data name="Common_Ok" xml:space="preserve">
<value>确定</value>
</data>
<data name="Common_Cancel" xml:space="preserve">
<value>取消</value>
</data>
<data name="Main_Export" xml:space="preserve">
<value>导出</value>
</data>
<data name="Main_Settings" xml:space="preserve">
<value>设置</value>
</data>
<data name="Main_About" xml:space="preserve">
<value>关于</value>
</data>
<data name="Tab_Tags" xml:space="preserve">
<value>标签</value>
</data>
<data name="Tab_Board" xml:space="preserve">
<value>看板</value>
</data>
<data name="Error_Argument_Title" xml:space="preserve">
<value>参数错误</value>
</data>
<data name="Error_Argument_Message" xml:space="preserve">
<value>YKanBan 启动参数有误。</value>
</data>
<data name="Error_Argument_Usage" xml:space="preserve">
<value>用法:ykanban &lt;路径&gt;</value>
</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">
<value>尚未初始化</value>
</data>
<data name="Error_NotInitialized_Message" xml:space="preserve">
<value>该目录下没有 .ykanban 工作区:{0}</value>
</data>
<data name="Error_NotInitialized_Initialize" xml:space="preserve">
<value>初始化工作区</value>
</data>
<data name="Error_LockConflict_Title" xml:space="preserve">
<value>工作区已被占用</value>
</data>
<data name="Error_LockConflict_Message" xml:space="preserve">
<value>该工作区已在另一个实例中打开:{0}</value>
</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>
<data name="Settings_Title" xml:space="preserve">
<value>设置</value>
</data>
<data name="Settings_Language" xml:space="preserve">
<value>语言</value>
</data>
<data name="Settings_Language_RestartNotice" xml:space="preserve">
<value>重启后生效</value>
</data>
<data name="Settings_LanguageEnglish" xml:space="preserve">
<value>English</value>
</data>
<data name="Settings_LanguageChinese" xml:space="preserve">
<value>简体中文</value>
</data>
<data name="Settings_Theme" xml:space="preserve">
<value>主题</value>
</data>
<data name="Settings_ThemeLight" xml:space="preserve">
<value>亮色</value>
</data>
<data name="Settings_ThemeDark" xml:space="preserve">
<value>暗色</value>
</data>
<data name="Settings_ThemeFollowSystem" xml:space="preserve">
<value>跟随系统</value>
</data>
<data name="Settings_Confirmations" xml:space="preserve">
<value>确认对话框</value>
</data>
<data name="Settings_ConfirmDeleteCard" xml:space="preserve">
<value>删除卡片前询问</value>
</data>
<data name="Settings_ConfirmDeleteColumn" xml:space="preserve">
<value>删除列前询问</value>
</data>
<data name="Settings_ConfirmDeleteTag" xml:space="preserve">
<value>删除标签前询问</value>
</data>
<data name="Settings_ConfirmDiscardEdit" xml:space="preserve">
<value>放弃卡片编辑前询问</value>
</data>
<data name="About_Title" xml:space="preserve">
<value>关于</value>
</data>
<data name="About_Version" xml:space="preserve">
<value>版本 {0}</value>
</data>
<data name="About_Repository" xml:space="preserve">
<value>仓库</value>
</data>
<data name="About_License" xml:space="preserve">
<value>许可证</value>
</data>
<data name="About_LicenseValue" xml:space="preserve">
<value>MIT</value>
</data>
<data name="PresetColumn_Todo" xml:space="preserve"> <data name="PresetColumn_Todo" xml:space="preserve">
<value>待办</value> <value>待办</value>
</data> </data>
@@ -166,6 +27,9 @@
<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>
@@ -187,208 +51,139 @@
<data name="Export_TagsTableHeader" xml:space="preserve"> <data name="Export_TagsTableHeader" xml:space="preserve">
<value>| 名称 | 颜色 | 描述 | 使用数 |</value> <value>| 名称 | 颜色 | 描述 | 使用数 |</value>
</data> </data>
<data name="Common_Delete" xml:space="preserve"> <data name="App_Name" xml:space="preserve">
<value>删除</value> <value>YKanBan</value>
</data> </data>
<data name="Common_Discard" xml:space="preserve"> <data name="Common_Yes" xml:space="preserve">
<value>丢弃</value> <value>是</value>
</data> </data>
<data name="Common_TimePattern" xml:space="preserve"> <data name="Common_No" xml:space="preserve">
<value>yyyy年M月d日 HH:mm</value> <value>否</value>
</data> </data>
<data name="Board_AddColumn" xml:space="preserve"> <data name="Common_Close" xml:space="preserve">
<value>新建列</value> <value>关闭</value>
</data> </data>
<data name="Board_ColumnWidth" xml:space="preserve"> <data name="Sidebar_Welcome" xml:space="preserve">
<value>列宽</value> <value>欢迎页</value>
</data> </data>
<data name="Board_Sort" xml:space="preserve"> <data name="Sidebar_OpenProject" xml:space="preserve">
<value>卡片排序</value> <value>打开项目…</value>
</data> </data>
<data name="Board_AddCard" xml:space="preserve"> <data name="Sidebar_SortLabel" xml:space="preserve">
<value>新建卡片</value> <value>排序</value>
</data> </data>
<data name="Sort_Id" xml:space="preserve"> <data name="Sidebar_Sort_NameAsc" xml:space="preserve">
<value>按 ID</value> <value>名称 A 到 Z</value>
</data> </data>
<data name="Sort_UpdatedAt" xml:space="preserve"> <data name="Sidebar_Sort_NameDesc" xml:space="preserve">
<value>最近修改</value> <value>名称 Z 到 A</value>
</data> </data>
<data name="Sort_Title" xml:space="preserve"> <data name="Sidebar_Sort_RecentlyUpdated" xml:space="preserve">
<value>按标题</value> <value>最近更新</value>
</data> </data>
<data name="Menu_More" xml:space="preserve"> <data name="Sidebar_Settings" xml:space="preserve">
<value>更多</value> <value>设置</value>
</data> </data>
<data name="Menu_Edit" xml:space="preserve"> <data name="Sidebar_About" xml:space="preserve">
<value>编辑</value> <value>关于</value>
</data> </data>
<data name="Menu_Delete" xml:space="preserve"> <data name="Sidebar_RemoveFromList" xml:space="preserve">
<value>删除</value> <value>从列表移除</value>
</data> </data>
<data name="Menu_MoveTo" xml:space="preserve"> <data name="Welcome_Hint" xml:space="preserve">
<value>移动到列</value> <value>从左侧打开或新建工作区。</value>
</data> </data>
<data name="Field_Title" xml:space="preserve"> <data name="Dialog_InitializeTitle" xml:space="preserve">
<value>标题</value> <value>初始化工作区?</value>
</data> </data>
<data name="Field_Description" xml:space="preserve"> <data name="Dialog_InitializeMessage" xml:space="preserve">
<value>描述</value> <value>“{0}”中不存在 .ykanban 数据。在此初始化?</value>
</data> </data>
<data name="Field_Content" xml:space="preserve"> <data name="Settings_Title" xml:space="preserve">
<value>内容</value> <value>设置</value>
</data> </data>
<data name="Field_Tags" xml:space="preserve"> <data name="Settings_Language" xml:space="preserve">
<value>标签</value> <value>语言</value>
</data> </data>
<data name="Field_Name" xml:space="preserve"> <data name="Settings_Language_RestartNotice" xml:space="preserve">
<value>名称</value> <value>重启后生效</value>
</data> </data>
<data name="Field_Color" xml:space="preserve"> <data name="Settings_LanguageEnglish" xml:space="preserve">
<value>#RRGGBB</value> <value>English</value>
</data> </data>
<data name="ColumnEditor_TitleNew" xml:space="preserve"> <data name="Settings_LanguageChinese" xml:space="preserve">
<value>新建列</value> <value>简体中文</value>
</data> </data>
<data name="ColumnEditor_TitleEdit" xml:space="preserve"> <data name="Settings_Theme" xml:space="preserve">
<value>编辑列</value> <value>主题</value>
</data> </data>
<data name="ColumnWidth_Title" xml:space="preserve"> <data name="Settings_ThemeLight" xml:space="preserve">
<value>列宽</value> <value>浅色</value>
</data> </data>
<data name="ColumnWidth_Narrow" xml:space="preserve"> <data name="Settings_ThemeDark" xml:space="preserve">
<value>窄({0} px)</value> <value>深色</value>
</data> </data>
<data name="ColumnWidth_Standard" xml:space="preserve"> <data name="Settings_ThemeFollowSystem" xml:space="preserve">
<value>标准({0} px)</value> <value>跟随系统</value>
</data> </data>
<data name="ColumnWidth_Wide" xml:space="preserve"> <data name="Settings_Confirmations" xml:space="preserve">
<value>宽({0} px)</value> <value>操作确认</value>
</data> </data>
<data name="ColumnWidth_Custom" xml:space="preserve"> <data name="Settings_ConfirmDeleteCard" xml:space="preserve">
<value>自定义</value> <value>删除卡片前确认</value>
</data> </data>
<data name="ColumnWidth_Range" xml:space="preserve"> <data name="Settings_ConfirmDeleteColumn" xml:space="preserve">
<value>{0}–{1} px</value> <value>删除列前确认</value>
</data> </data>
<data name="CardEditor_TitleNew" xml:space="preserve"> <data name="Settings_ConfirmDeleteTag" xml:space="preserve">
<value>新建卡片</value> <value>删除标签前确认</value>
</data> </data>
<data name="CardEditor_TitleEdit" xml:space="preserve"> <data name="Settings_ConfirmDiscardEdit" xml:space="preserve">
<value>编辑卡片</value> <value>放弃卡片编辑前确认</value>
</data> </data>
<data name="CardEditor_TitleWatermark" xml:space="preserve"> <data name="About_Title" xml:space="preserve">
<value>无标题</value> <value>关于</value>
</data> </data>
<data name="CardEditor_Created" xml:space="preserve"> <data name="About_Version" xml:space="preserve">
<value>创建于 {0}</value> <value>版本 {0}</value>
</data> </data>
<data name="CardEditor_Modified" xml:space="preserve"> <data name="About_Repository" xml:space="preserve">
<value>修改于 {0}</value> <value>仓库</value>
</data> </data>
<data name="CardEditor_AddTag" xml:space="preserve"> <data name="About_RepositoryUrl" xml:space="preserve">
<value>添加标签</value> <value>(待填写)</value>
</data> </data>
<data name="CardEditor_RemoveTag" xml:space="preserve"> <data name="About_License" xml:space="preserve">
<value>移除标签</value> <value>许可证</value>
</data> </data>
<data name="TagPicker_Title" xml:space="preserve"> <data name="About_LicenseValue" xml:space="preserve">
<value>添加标签</value> <value>(待填写)</value>
</data> </data>
<data name="TagPicker_FilterWatermark" xml:space="preserve"> <data name="State_LockConflict_Title" xml:space="preserve">
<value>筛选标签</value> <value>工作区已被占用</value>
</data> </data>
<data name="TagPicker_NoMatches" xml:space="preserve"> <data name="State_LockConflict_Detail" xml:space="preserve">
<value>没有匹配的标签</value> <value>该工作区正被另一实例锁定。</value>
</data> </data>
<data name="TagPicker_NewTag" xml:space="preserve"> <data name="State_NotInitialized_Title" xml:space="preserve">
<value>新建标签</value> <value>此处没有工作区</value>
</data> </data>
<data name="TagPicker_Create" xml:space="preserve"> <data name="State_NotInitialized_Detail" xml:space="preserve">
<value>新建并添加</value> <value>该文件夹没有 .ykanban 数据。</value>
</data> </data>
<data name="Confirm_Title" xml:space="preserve"> <data name="State_DirectoryMissing_Title" xml:space="preserve">
<value>确认</value> <value>文件夹不存在</value>
</data> </data>
<data name="Confirm_DeleteCard" xml:space="preserve"> <data name="State_DirectoryMissing_Detail" xml:space="preserve">
<value>删除卡片“{0}”?</value> <value>该文件夹在磁盘上不存在。</value>
</data> </data>
<data name="Confirm_DeleteColumn" xml:space="preserve"> <data name="State_SchemaVersion_Title" xml:space="preserve">
<value>删除列“{0}”及其中的 {1} 张卡片?</value> <value>数据库版本不兼容</value>
</data> </data>
<data name="Confirm_DiscardEdit" xml:space="preserve"> <data name="State_SchemaVersion_Detail" xml:space="preserve">
<value>放弃未保存的更改?</value> <value>该工作区由更新版本的程序创建。</value>
</data> </data>
<data name="Error_Column_TitleRequired" xml:space="preserve"> <data name="State_Unknown_Title" xml:space="preserve">
<value>列标题不能为空。</value> <value>打开失败</value>
</data>
<data name="Error_Column_Duplicate" xml:space="preserve">
<value>已存在名为“{0}”的列(名称不区分大小写)。</value>
</data>
<data name="Error_Tag_NameRequired" xml:space="preserve">
<value>标签名称不能为空。</value>
</data>
<data name="Error_Tag_Duplicate" xml:space="preserve">
<value>已存在名为“{0}”的标签(名称不区分大小写)。</value>
</data>
<data name="Error_Tag_InvalidColor" xml:space="preserve">
<value>颜色须为 #RRGGBB 格式。</value>
</data>
<data name="Error_SaveFailed" xml:space="preserve">
<value>保存失败:{0}</value>
</data>
<data name="Error_Operation_Title" xml:space="preserve">
<value>操作失败</value>
</data>
<data name="Error_Operation_Message" xml:space="preserve">
<value>更改未能写入工作区,看板显示的是已保存的状态。</value>
</data>
<data name="TagEditor_TitleNew" xml:space="preserve">
<value>新建标签</value>
</data>
<data name="TagEditor_TitleEdit" xml:space="preserve">
<value>编辑标签</value>
</data>
<data name="TagEditor_ColorLabel" xml:space="preserve">
<value>颜色</value>
</data>
<data name="Tags_AddTag" xml:space="preserve">
<value>新建标签</value>
</data>
<data name="Tags_Summary" xml:space="preserve">
<value>共 {0} 个标签</value>
</data>
<data name="Tags_UsageCount" xml:space="preserve">
<value>{0} 张卡片</value>
</data>
<data name="Tags_Empty" xml:space="preserve">
<value>还没有标签。</value>
</data>
<data name="Confirm_DeleteTag" xml:space="preserve">
<value>删除标签“{0}”?将从 {1} 张卡片移除该标签。</value>
</data>
<data name="Board_SearchWatermark" xml:space="preserve">
<value>搜索,例如 tag:bug OR title:登录</value>
</data>
<data name="Board_Search" xml:space="preserve">
<value>搜索</value>
</data>
<data name="Board_ClearSearch" xml:space="preserve">
<value>清空</value>
</data>
<data name="Search_Error_Title" xml:space="preserve">
<value>搜索表达式错误</value>
</data>
<data name="Search_Error_Message" xml:space="preserve">
<value>查询表达式有误,详情:{0}</value>
</data>
<data name="Export_FileTypeMarkdown" xml:space="preserve">
<value>Markdown 文档</value>
</data>
<data name="Export_Failed_Title" xml:space="preserve">
<value>导出失败</value>
</data>
<data name="Export_Failed_Message" xml:space="preserve">
<value>无法写入导出文件。</value>
</data> </data>
</root> </root>
+34 -109
View File
@@ -6,25 +6,19 @@ 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 the time format come from the ResX resources in the current /// template text and time formats come from the ResX resources in the
/// UI language; every timestamp (export time and card created/modified times) /// current UI language; the export timestamp uses the per-language pattern,
/// uses that one per-language pattern. The whole document uses LF line endings /// card timestamps use the shared minute-precision pattern. The output is
/// on every platform. Card bodies and column descriptions are emitted verbatim /// meant for reading only — there is no re-import.
/// apart from line endings; 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 &lt;br&gt;. The
/// output is meant for reading only — there is no re-import.
/// </summary> /// </summary>
public static class MarkdownExporter public static class MarkdownExporter
{ {
/// <summary> /// <summary>Renders the whole board to Markdown.</summary>
/// Renders the whole board to Markdown.
/// </summary>
/// <param name="workspaceName">Workspace display name (the folder name).</param> /// <param name="workspaceName">Workspace display name (the folder name).</param>
/// <param name="columns">All columns; emitted in id order, empty columns kept.</param> /// <param name="columns">All columns, in id order; empty columns are kept.</param>
/// <param name="cards">All cards; grouped by column, id order within a column.</param> /// <param name="cards">All cards; grouped by column, id order within a column.</param>
/// <param name="tags">All tags with usage counts, in id order.</param> /// <param name="tags">All tags with usage counts, in id order.</param>
/// <param name="exportedAt">Export moment in local time.</param> /// <param name="exportedAt">Export moment in local time.</param>
/// <returns>The Markdown document.</returns>
public static string Export( public static string Export(
string workspaceName, string workspaceName,
IReadOnlyList<ColumnModel> columns, IReadOnlyList<ColumnModel> columns,
@@ -37,23 +31,21 @@ 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.
AppendLine(builder, string.Format(culture, Resources.Export_WorkspaceHeading, SingleLine(workspaceName))); builder.AppendLine(string.Format(culture, Resources.Export_WorkspaceHeading, workspaceName));
AppendLine(builder, 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)));
AppendLine(builder); builder.AppendLine();
// Board body: every column in id order, empty ones included; independent of // Board body: every column in id order, empty ones included.
// the board's search filter and card sort option. foreach (ColumnModel column in columns)
foreach (ColumnModel column in columns.OrderBy(column => column.Id))
{ {
IReadOnlyList<CardModel> cardsInColumn = IReadOnlyList<CardModel> cardsInColumn = cards.Where(card => card.ColumnId == column.Id).ToArray();
cards.Where(card => card.ColumnId == column.Id).OrderBy(card => card.Id).ToArray(); builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, column.Title, cardsInColumn.Count));
AppendLine(builder, string.Format(culture, Resources.Export_ColumnHeading, SingleLine(column.Title), cardsInColumn.Count));
if (column.Description.Length > 0) if (column.Description.Length > 0)
{ {
AppendLine(builder, ToLf(column.Description)); builder.AppendLine(SingleLine(column.Description));
} }
AppendLine(builder); builder.AppendLine();
foreach (CardModel card in cardsInColumn) foreach (CardModel card in cardsInColumn)
{ {
@@ -65,128 +57,61 @@ public static class MarkdownExporter
return builder.ToString(); return builder.ToString();
} }
/// <summary> /// <summary>Builds the default export file name in the UI language, e.g. "MyRepo-export-20260930-142537.md".</summary>
/// Builds the default export file name in the UI language, for example
/// "MyRepo-export-20260930-142537.md".
/// </summary>
/// <param name="workspaceName">Workspace display name.</param>
/// <param name="exportedAt">Export moment.</param>
/// <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); return string.Format(culture, Resources.Export_FileNamePattern, workspaceName, exportedAt);
} }
/// <summary> /// <summary>Appends one card block: heading, body, tags line, timestamps line.</summary>
/// Appends one card block: heading, body, tags line and timestamps line.
/// </summary>
/// <param name="builder">The output builder.</param>
/// <param name="card">The card to render.</param>
/// <param name="culture">The UI culture.</param>
private static void AppendCard(StringBuilder builder, CardModel card, CultureInfo culture) private static void AppendCard(StringBuilder builder, CardModel card, CultureInfo culture)
{ {
// Heading: "#id title"; an untitled card shows only the id. // Heading: "#id title"; an untitled card shows only the id.
AppendLine(builder, card.Title.Length == 0 builder.AppendLine(card.Title.Length == 0
? $"### #{card.Id}" ? $"### #{card.Id}"
: $"### #{card.Id} {SingleLine(card.Title)}"); : $"### #{card.Id} {SingleLine(card.Title)}");
if (card.Content.Length > 0) if (card.Content.Length > 0)
{ {
AppendLine(builder, ToLf(card.Content)); builder.AppendLine(card.Content);
} }
if (card.Tags.Count > 0) if (card.Tags.Count > 0)
{ {
string names = string.Join(" ", card.Tags.Select(tag => InlineCode(tag.Name))); string names = string.Join(" ", card.Tags.Select(tag => $"`{tag.Name}`"));
AppendLine(builder, string.Format(culture, Resources.Export_TagsLine, names)); builder.AppendLine(string.Format(culture, Resources.Export_TagsLine, names));
} }
string created = ToLocalTime(card.CreatedAt).ToString(Resources.Export_TimePattern, culture); string created = ToLocalTime(card.CreatedAt).ToString(Resources.Export_CardTimePattern, culture);
string updated = ToLocalTime(card.UpdatedAt).ToString(Resources.Export_TimePattern, culture); string updated = ToLocalTime(card.UpdatedAt).ToString(Resources.Export_CardTimePattern, culture);
AppendLine(builder, string.Format(culture, Resources.Export_CreatedModifiedLine, created, updated)); builder.AppendLine(string.Format(culture, Resources.Export_CreatedModifiedLine, created, updated));
AppendLine(builder); builder.AppendLine();
} }
/// <summary> /// <summary>Appends the tag summary table with usage counts; tags with zero usage are included.</summary>
/// Appends the tag summary table with usage counts; tags with zero usage are included.
/// </summary>
/// <param name="builder">The output builder.</param>
/// <param name="tags">The tags and their usage counts.</param>
/// <param name="culture">The UI culture.</param>
private static void AppendTagTable( private static void AppendTagTable(
StringBuilder builder, StringBuilder builder,
IReadOnlyList<(TagModel Tag, long UsageCount)> tags, IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
CultureInfo culture) CultureInfo culture)
{ {
AppendLine(builder, Resources.Export_TagsSummaryHeading); builder.AppendLine(Resources.Export_TagsSummaryHeading);
AppendLine(builder, Resources.Export_TagsTableHeader); builder.AppendLine(Resources.Export_TagsTableHeader);
AppendLine(builder, "|---|---|---|---|"); builder.AppendLine("|---|---|---|---|");
foreach ((TagModel tag, long usage) in tags) foreach ((TagModel tag, long usage) in tags)
{ {
// '|' and line breaks would break the table row; neutralize them. // '|' and line breaks would break the table row; neutralize them.
AppendLine(builder, $"| {Cell(tag.Name)} | {tag.Color} | {Cell(tag.Description)} | {usage} |"); builder.AppendLine($"| {Cell(tag.Name)} | {tag.Color} | {Cell(tag.Description)} | {usage} |");
} }
} }
/// <summary> /// <summary>Formats a table cell: single line with escaped pipe characters.</summary>
/// Formats a table cell: escaped backslashes and pipe characters, line breaks as &lt;br&gt;. private static string Cell(string text) => SingleLine(text).Replace("|", "\\|");
/// </summary>
/// <param name="text">The raw cell text.</param>
/// <returns>The escaped single-line text.</returns>
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> /// <summary>Collapses line breaks so the text stays on one Markdown line.</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>
/// Appends a line terminated by LF, whatever the platform's newline.
/// </summary>
/// <param name="builder">The output builder.</param>
/// <param name="text">The line text; empty for a blank line.</param>
private static void AppendLine(StringBuilder builder, string text = "") => builder.Append(text).Append('\n');
/// <summary>
/// Converts CRLF and lone CR line breaks to LF.
/// </summary>
/// <param name="text">The raw text.</param>
/// <returns>The text with LF line breaks only.</returns>
private static string ToLf(string text) => text.Replace("\r\n", "\n").Replace('\r', '\n');
/// <summary>
/// Collapses line breaks so the text stays on one Markdown line.
/// </summary>
/// <param name="text">The raw text.</param>
/// <returns>The text without line breaks.</returns>
private static string SingleLine(string text) => text.Replace("\r", string.Empty).Replace("\n", " "); private static string SingleLine(string text) => text.Replace("\r", string.Empty).Replace("\n", " ");
/// <summary> /// <summary>Converts stored Unix seconds to a local-time DateTimeOffset.</summary>
/// Converts stored Unix seconds to a local-time <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="unixSeconds">The stored timestamp.</param>
/// <returns>The local time.</returns>
private static DateTimeOffset ToLocalTime(long unixSeconds) => private static DateTimeOffset ToLocalTime(long unixSeconds) =>
DateTimeOffset.FromUnixTimeSeconds(unixSeconds).ToLocalTime(); DateTimeOffset.FromUnixTimeSeconds(unixSeconds).ToLocalTime();
} }
+25
View File
@@ -0,0 +1,25 @@
namespace YKanBan.Ipc;
/// <summary>
/// Single-instance detection and inter-instance messaging, built on a named
/// mutex (detection) and a named pipe (command forwarding). The primary
/// instance holds the mutex for its lifetime and serves the pipe; secondary
/// instances forward their launch command to the primary and exit.
/// </summary>
public interface ISingleInstanceService : IDisposable
{
/// <summary>Attempts to register this process as the single YKanBan instance.</summary>
/// <returns>True when this process is the primary instance; false when another one exists.</returns>
bool TryAcquireSingleInstance();
/// <summary>Starts serving launch commands on a background task (primary instance only).</summary>
/// <param name="handler">Invoked for each decoded command; runs on a background thread.</param>
/// <exception cref="InvalidOperationException">
/// Not called on a primary instance, or called a second time.
/// </exception>
void StartServer(Action<LaunchCommand> handler);
/// <summary>Delivers a command to the primary instance and waits for its acknowledgement.</summary>
/// <returns>True when the primary instance acknowledged the command.</returns>
bool TrySend(LaunchCommand command);
}
+62
View File
@@ -0,0 +1,62 @@
namespace YKanBan.Ipc;
/// <summary>
/// Text encoding of launch commands on the IPC pipe. A message is one or
/// two newline-terminated lines: "show", or "open" followed by the
/// workspace path taken verbatim (paths may contain spaces; paths
/// containing newlines are not supported). Decoding is strict and throws
/// FormatException on malformed payloads.
/// </summary>
public static class IpcProtocol
{
/// <summary>Encodes a command into its wire text.</summary>
/// <exception cref="InvalidOperationException">The command type is unknown.</exception>
public static string Encode(LaunchCommand command) => command switch
{
LaunchCommand.ShowMain => "show\n",
LaunchCommand.OpenWorkspace open => $"open\n{open.Path}\n",
_ => throw new InvalidOperationException($"Unsupported launch command: {command?.GetType().Name ?? "null"}"),
};
/// <summary>Decodes wire text into a command; trailing newlines are tolerated.</summary>
/// <exception cref="FormatException">The payload is not a valid message.</exception>
public static LaunchCommand Decode(string payload)
{
List<string> lines = payload.Split('\n').ToList();
// Trailing newlines are a framing detail; drop the empty lines they produce.
while (lines.Count > 0 && lines[^1].Length == 0)
{
lines.RemoveAt(lines.Count - 1);
}
if (lines.Count == 0)
{
throw new FormatException("Empty IPC payload.");
}
switch (lines[0])
{
case "show":
if (lines.Count != 1)
{
throw new FormatException($"Unexpected content after 'show': '{lines[1]}'");
}
return new LaunchCommand.ShowMain();
case "open":
if (lines.Count != 2)
{
throw new FormatException("'open' requires exactly one path line.");
}
if (lines[1].Length == 0)
{
throw new FormatException("'open' requires a non-empty path.");
}
return new LaunchCommand.OpenWorkspace(lines[1]);
default:
throw new FormatException($"Unknown IPC command: '{lines[0]}'");
}
}
}
+18
View File
@@ -0,0 +1,18 @@
namespace YKanBan.Ipc;
/// <summary>Parses command-line arguments into a launch command.</summary>
public static class LaunchArguments
{
/// <summary>
/// Parses raw command-line arguments: with no meaningful argument the
/// command is ShowMain; otherwise the first non-blank argument is taken
/// as the workspace path and any further arguments are ignored.
/// </summary>
public static LaunchCommand Parse(IReadOnlyList<string> arguments)
{
string? path = arguments.FirstOrDefault(argument => !string.IsNullOrWhiteSpace(argument));
return path is null
? new LaunchCommand.ShowMain()
: new LaunchCommand.OpenWorkspace(path);
}
}
+15
View File
@@ -0,0 +1,15 @@
namespace YKanBan.Ipc;
/// <summary>
/// A launch command: what a YKanBan invocation asks the application to do.
/// Doubles as the IPC message forwarded from a secondary instance to the
/// primary one.
/// </summary>
public abstract record LaunchCommand
{
/// <summary>No arguments: show the main window and bring it to front.</summary>
public sealed record ShowMain : LaunchCommand;
/// <summary>A workspace path: activate the window and switch to (or open) the workspace.</summary>
public sealed record OpenWorkspace(string Path) : LaunchCommand;
}
+188
View File
@@ -0,0 +1,188 @@
using System.IO.Pipes;
using System.Text;
namespace YKanBan.Ipc;
/// <summary>
/// Mutex + named pipe implementation of <see cref="ISingleInstanceService"/>.
/// The mutex name is per-user-session (Local\ prefix), so separate users on
/// one machine run independently. A crash releases the mutex with the
/// process — no stale state survives.
/// </summary>
public sealed class SingleInstanceService : ISingleInstanceService
{
private const string MutexName = @"Local\YKanBan.SingleInstance";
private const string PipeName = "YKanBan.Ipc";
private const int ConnectTimeoutMilliseconds = 2000;
private const int ConnectAttempts = 3;
private const int RetryDelayMilliseconds = 300;
private readonly object _gate = new();
private Mutex? _mutex;
private CancellationTokenSource? _serverCancellation;
private bool _isPrimary;
/// <summary>Attempts to register this process as the single YKanBan instance.</summary>
/// <exception cref="InvalidOperationException">Acquired a second time.</exception>
public bool TryAcquireSingleInstance()
{
lock (_gate)
{
if (_mutex is not null)
{
throw new InvalidOperationException("Single instance already acquired.");
}
// Ownership is requested up front; createdNew tells primary from secondary.
_mutex = new Mutex(initiallyOwned: true, MutexName, out bool createdNew);
_isPrimary = createdNew;
return createdNew;
}
}
/// <summary>Starts serving launch commands on a background task (primary instance only).</summary>
/// <exception cref="InvalidOperationException">
/// Not called on a primary instance, or called a second time.
/// </exception>
public void StartServer(Action<LaunchCommand> handler)
{
CancellationTokenSource cancellation;
lock (_gate)
{
if (!_isPrimary || _mutex is null)
{
throw new InvalidOperationException("Only the primary instance can serve IPC.");
}
if (_serverCancellation is not null)
{
throw new InvalidOperationException("IPC server already started.");
}
_serverCancellation = new CancellationTokenSource();
cancellation = _serverCancellation;
}
_ = Task.Run(() => ServerLoopAsync(handler, cancellation.Token));
}
/// <summary>Delivers a command to the primary instance and waits for its acknowledgement.</summary>
public bool TrySend(LaunchCommand command)
{
string payload = IpcProtocol.Encode(command);
// The primary may still be starting its server; retry briefly before giving up.
for (int attempt = 0; attempt < ConnectAttempts; attempt++)
{
try
{
using var client = new NamedPipeClientStream(".", PipeName, PipeDirection.InOut);
client.Connect(ConnectTimeoutMilliseconds);
using (var writer = new StreamWriter(client, Encoding.UTF8, bufferSize: 64, leaveOpen: true)
{
AutoFlush = true,
})
{
writer.Write(payload);
}
using var reader = new StreamReader(client, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 64, leaveOpen: true);
string acknowledgement = reader.ReadLine() ?? string.Empty;
return acknowledgement == "ok";
}
catch (TimeoutException)
{
Thread.Sleep(RetryDelayMilliseconds);
}
catch (IOException)
{
Thread.Sleep(RetryDelayMilliseconds);
}
}
return false;
}
/// <summary>Releases the mutex and stops the IPC server.</summary>
public void Dispose()
{
lock (_gate)
{
_serverCancellation?.Cancel();
_serverCancellation?.Dispose();
_serverCancellation = null;
_mutex?.Dispose();
_mutex = null;
_isPrimary = false;
}
}
/// <summary>Accepts one client at a time: read, decode, dispatch, acknowledge, disconnect.</summary>
private static async Task ServerLoopAsync(Action<LaunchCommand> handler, CancellationToken cancellation)
{
while (!cancellation.IsCancellationRequested)
{
try
{
using var server = new NamedPipeServerStream(PipeName, PipeDirection.InOut, maxNumberOfServerInstances: 1);
await server.WaitForConnectionAsync(cancellation);
string payload = await ReadMessageAsync(server, cancellation);
LaunchCommand command = IpcProtocol.Decode(payload);
// Dispatch to the app; handler failures must not kill the server.
try
{
handler(command);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// Swallow handler exceptions: one bad dispatch must not stop serving.
}
WriteAcknowledgement(server);
server.Disconnect();
}
catch (OperationCanceledException)
{
break;
}
catch (IOException)
{
// Client vanished mid-conversation: drop the connection and keep serving.
}
catch (FormatException)
{
// Malformed payload: no acknowledgement is written; keep serving.
}
}
}
/// <summary>Reads the command line plus, for open, the path line.</summary>
private static async Task<string> ReadMessageAsync(PipeStream pipe, CancellationToken cancellation)
{
using var reader = new StreamReader(pipe, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true);
string firstLine = await reader.ReadLineAsync(cancellation)
?? throw new IOException("Connection closed before the command line arrived.");
if (firstLine != "open")
{
return firstLine;
}
string? pathLine = await reader.ReadLineAsync(cancellation);
if (pathLine is null)
{
throw new IOException("Connection closed before the path line arrived.");
}
return $"open\n{pathLine}";
}
/// <summary>Writes the acknowledgement the sender waits for.</summary>
private static void WriteAcknowledgement(PipeStream pipe)
{
using var writer = new StreamWriter(pipe, Encoding.UTF8, bufferSize: 64, leaveOpen: true)
{
AutoFlush = true,
};
writer.Write("ok\n");
}
}
-42
View File
@@ -1,42 +0,0 @@
using System.Diagnostics.CodeAnalysis;
namespace YKanBan.Launching;
/// <summary>
/// Parses raw command-line arguments. The only accepted form is a single,
/// non-blank workspace path (<c>ykanban &lt;path&gt;</c>); zero arguments,
/// more than one argument, a blank argument, an argument starting with
/// <c>-</c> (any option form, <c>--help</c> included) or a malformed path is
/// rejected as an argument error. A relative path is resolved against the
/// process's current directory; the path itself is not checked for existence
/// here.
/// </summary>
public static class LaunchArguments
{
/// <summary>
/// Tries to parse command-line arguments following the
/// <c>ykanban &lt;path&gt;</c> contract.
/// </summary>
/// <param name="arguments">The raw arguments, excluding the executable name.</param>
/// <param name="folderPath">The absolute workspace path on success, otherwise <see langword="null"/>.</param>
/// <returns><see langword="true"/> when exactly one usable path was supplied.</returns>
public static bool TryParse(IReadOnlyList<string> arguments, [NotNullWhen(true)] out string? folderPath)
{
folderPath = null;
if (arguments.Count != 1 || string.IsNullOrWhiteSpace(arguments[0]) || arguments[0].StartsWith('-'))
{
return false;
}
try
{
folderPath = Path.GetFullPath(arguments[0]);
return true;
}
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;
}
}
}
+1 -3
View File
@@ -1,8 +1,6 @@
namespace YKanBan.Models; namespace YKanBan.Models;
/// <summary> /// <summary>A card with its assigned tags loaded.</summary>
/// A card with its assigned tags loaded.
/// </summary>
/// <param name="Id">Row id.</param> /// <param name="Id">Row id.</param>
/// <param name="ColumnId">Owning column.</param> /// <param name="ColumnId">Owning column.</param>
/// <param name="Title">Possibly empty; the empty string is the canonical "no title".</param> /// <param name="Title">Possibly empty; the empty string is the canonical "no title".</param>
-70
View File
@@ -1,70 +0,0 @@
using System.Text;
using YKanBan.Storage.AppData;
namespace YKanBan.Models;
/// <summary>
/// Computes the in-column card display order for a <see cref="CardSortOption"/>.
/// Columns are not affected: they always stay in id order. Every option falls
/// back to id ascending as the final tie-breaker, so the order is total.
/// </summary>
public static class CardOrdering
{
/// <summary>
/// Orders cards for display.
/// </summary>
/// <param name="cards">The cards to order, typically those of one column.</param>
/// <param name="option">The selected sort option.</param>
/// <returns>The cards in display order.</returns>
public static IReadOnlyList<CardModel> Sort(IEnumerable<CardModel> cards, CardSortOption option)
{
IOrderedEnumerable<CardModel> ordered = option switch
{
CardSortOption.Id => cards.OrderBy(card => card.Id),
// Most recently modified first.
CardSortOption.UpdatedAt => cards.OrderByDescending(card => card.UpdatedAt).ThenBy(card => card.Id),
// Code point order, matching SQLite's BINARY collation; the empty title sorts first.
CardSortOption.Title => cards.OrderBy(card => card.Title, CodePointComparer.Instance).ThenBy(card => card.Id),
_ => throw new ArgumentOutOfRangeException(nameof(option), option, "Unknown card sort option."),
};
return ordered.ToList();
}
/// <summary>
/// Compares strings by Unicode code points. Unlike ordinal UTF-16 comparison
/// it orders supplementary characters after U+E000–U+FFFF, as BINARY does on UTF-8.
/// </summary>
private sealed class CodePointComparer : IComparer<string>
{
public static readonly CodePointComparer Instance = new();
public int Compare(string? x, string? y)
{
if (x is null || y is null)
{
return x is null ? (y is null ? 0 : -1) : 1;
}
StringRuneEnumerator left = x.EnumerateRunes();
StringRuneEnumerator right = y.EnumerateRunes();
while (true)
{
bool hasLeft = left.MoveNext();
bool hasRight = right.MoveNext();
if (!hasLeft || !hasRight)
{
return hasLeft.CompareTo(hasRight);
}
int result = left.Current.Value.CompareTo(right.Current.Value);
if (result != 0)
{
return result;
}
}
}
}
}
+2 -4
View File
@@ -1,10 +1,8 @@
namespace YKanBan.Models; namespace YKanBan.Models;
/// <summary> /// <summary>A board column as stored in the workspace database.</summary>
/// A board column as stored in the workspace database.
/// </summary>
/// <param name="Id">Row id.</param> /// <param name="Id">Row id.</param>
/// <param name="Title">Non-empty, table-unique title.</param> /// <param name="Title">Non-empty unique title.</param>
/// <param name="Description">Free-form description, possibly empty.</param> /// <param name="Description">Free-form description, possibly empty.</param>
/// <param name="CreatedAt">Unix seconds of creation.</param> /// <param name="CreatedAt">Unix seconds of creation.</param>
/// <param name="UpdatedAt">Unix seconds of the last title/description change.</param> /// <param name="UpdatedAt">Unix seconds of the last title/description change.</param>
+11 -35
View File
@@ -1,34 +1,23 @@
namespace YKanBan.Models; namespace YKanBan.Models;
/// <summary> /// <summary>
/// An RGB color without an alpha channel, stored as one byte per component — /// An RGB color without an alpha channel, stored as one byte per component
/// mirroring the color structures of WinForms, WPF and Avalonia minus the /// — mirroring the color structures of WinForms, WPF and Avalonia minus
/// alpha byte. The type is total: every combination of components is valid, /// the alpha byte. The type is total: every combination of components is
/// and all validation happens at the text boundary. /// valid, and all validation happens at the text boundary. Converts to and
/// /// from the persisted "#RRGGBB" text form; ToString always produces the
/// It converts to and from the persisted "#RRGGBB" text form; <see cref="ToString"/> /// canonical lowercase form (e.g. "#ff0a00").
/// always produces the canonical lowercase form (for example "#ff0a00"). It is
/// not specific to tags and may be reused anywhere a color value is needed.
/// </summary> /// </summary>
public readonly record struct RgbColor(byte R, byte G, byte B) public readonly record struct RgbColor(byte R, byte G, byte B)
{ {
/// <summary> /// <summary>Parses a "#RRGGBB" text with case-insensitive hex digits.</summary>
/// Parses a "#RRGGBB" text with case-insensitive hex digits.
/// </summary>
/// <param name="text">The text to parse.</param>
/// <returns>The parsed color.</returns>
/// <exception cref="FormatException">The text is not in #RRGGBB form.</exception> /// <exception cref="FormatException">The text is not in #RRGGBB form.</exception>
public static RgbColor Parse(string text) => public static RgbColor Parse(string text) =>
TryParse(text, out RgbColor color) TryParse(text, out RgbColor color)
? color ? color
: throw new FormatException($"Not a valid #RRGGBB color: '{text}'."); : throw new FormatException($"Not a valid #RRGGBB color: '{text}'.");
/// <summary> /// <summary>Attempts to parse a "#RRGGBB" text; no whitespace tolerance.</summary>
/// Attempts to parse a "#RRGGBB" text. There is no whitespace tolerance.
/// </summary>
/// <param name="text">The text to parse.</param>
/// <param name="color">The parsed color on success, otherwise the default value.</param>
/// <returns><see langword="true"/> when the text is exactly #RRGGBB.</returns>
public static bool TryParse(string? text, out RgbColor color) public static bool TryParse(string? text, out RgbColor color)
{ {
color = default; color = default;
@@ -46,19 +35,10 @@ public readonly record struct RgbColor(byte R, byte G, byte B)
return false; return false;
} }
/// <summary> /// <summary>Returns the canonical lowercase "#RRGGBB" form used by the database and exports.</summary>
/// Returns the canonical lowercase "#RRGGBB" form used by the database and exports.
/// </summary>
/// <returns>The lowercase #RRGGBB text.</returns>
public override string ToString() => $"#{R:x2}{G:x2}{B:x2}"; public override string ToString() => $"#{R:x2}{G:x2}{B:x2}";
/// <summary> /// <summary>Parses exactly two hex digits into a byte value.</summary>
/// Parses exactly two hex digits into a byte value.
/// </summary>
/// <param name="text">The source text.</param>
/// <param name="start">Index of the first of the two digits.</param>
/// <param name="value">The parsed byte value.</param>
/// <returns><see langword="true"/> when both characters are hex digits.</returns>
private static bool TryHexPair(string text, int start, out byte value) private static bool TryHexPair(string text, int start, out byte value)
{ {
value = 0; value = 0;
@@ -72,11 +52,7 @@ public readonly record struct RgbColor(byte R, byte G, byte B)
return true; return true;
} }
/// <summary> /// <summary>Converts one hex digit to its value; -1 for any other character.</summary>
/// Converts one hex digit to its value.
/// </summary>
/// <param name="character">The character to convert.</param>
/// <returns>The digit value, or -1 for any other character.</returns>
private static int HexDigit(char character) => character switch private static int HexDigit(char character) => character switch
{ {
>= '0' and <= '9' => character - '0', >= '0' and <= '9' => character - '0',
+1 -4
View File
@@ -1,9 +1,6 @@
namespace YKanBan.Models; namespace YKanBan.Models;
/// <summary> /// <summary>A tag assignable to cards. Tags are never garbage-collected: unreferenced tags stay until deleted explicitly.</summary>
/// A tag assignable to cards. Tags are never garbage-collected: unreferenced
/// tags stay until they are deleted explicitly.
/// </summary>
/// <param name="Id">Row id.</param> /// <param name="Id">Row id.</param>
/// <param name="Name">Arbitrary non-empty text; no charset or length rules.</param> /// <param name="Name">Arbitrary non-empty text; no charset or length rules.</param>
/// <param name="Color">The tag color; persisted as #RRGGBB text.</param> /// <param name="Color">The tag color; persisted as #RRGGBB text.</param>
+64
View File
@@ -0,0 +1,64 @@
namespace YKanBan.Platform;
/// <summary>
/// Compares and normalizes workspace folder paths. Normalization produces
/// the canonical absolute form: separators unified by the operating system,
/// "." and ".." collapsed, trailing separator trimmed except on roots.
/// Symbolic links are deliberately NOT resolved. Case handling is an
/// injected platform rule — ignored on Windows, significant on Unix and
/// macOS — so the Unix behavior is testable on any host.
/// </summary>
public sealed class PathComparer : IEqualityComparer<string>
{
private readonly StringComparison _comparison;
/// <summary>Creates a comparer with an explicit case-sensitivity rule.</summary>
/// <param name="ignoreCase">True for Windows-style path semantics.</param>
public PathComparer(bool ignoreCase)
{
_comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
}
/// <summary>The comparer matching the current operating system's path semantics.</summary>
public static PathComparer ForCurrentPlatform() => new(OperatingSystem.IsWindows());
/// <summary>Returns the canonical absolute form used for storage and display.</summary>
public string Normalize(string path)
{
// GetFullPath makes the path absolute, collapses relative segments and
// unifies separators; it preserves a trailing separator, so trim it to
// keep the canonical form unique ("D:\repo" and "D:\repo\" are one path).
string full = Path.GetFullPath(path);
return TrimTrailingSeparator(full);
}
/// <summary>Determines whether two paths denote the same location under the configured platform rules.</summary>
public bool Equals(string? x, string? y)
{
if (x is null || y is null)
{
return ReferenceEquals(x, y);
}
return string.Equals(Normalize(x), Normalize(y), _comparison);
}
/// <summary>Returns a hash code consistent with <see cref="Equals(string?, string?)"/>.</summary>
public int GetHashCode(string path) => Normalize(path).GetHashCode(_comparison);
/// <summary>Removes trailing separators while keeping root forms intact ("C:\", "/").</summary>
private static string TrimTrailingSeparator(string fullPath)
{
bool isDriveRoot = fullPath.Length == 3
&& char.IsAsciiLetter(fullPath[0])
&& fullPath[1] == ':'
&& IsSeparator(fullPath[2]);
if (isDriveRoot || fullPath == "/")
{
return fullPath;
}
return fullPath.TrimEnd('/', '\\');
}
/// <summary>Returns true for both supported separator characters.</summary>
private static bool IsSeparator(char character) => character is '/' or '\\';
}
+21 -9
View File
@@ -1,23 +1,35 @@
using Avalonia; using System;
using Avalonia;
using YKanBan.Ipc;
namespace YKanBan; namespace YKanBan;
sealed class Program sealed class Program
{ {
// Initialization code. Don't use any Avalonia, third-party APIs or any /// <summary>The single-instance service held by this process while the app runs.</summary>
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized internal static ISingleInstanceService? SingleInstance { get; private set; }
// yet and stuff might break.
[STAThread] [STAThread]
public static void Main(string[] args) public static void Main(string[] args)
{ {
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); LaunchCommand command = LaunchArguments.Parse(args);
using ISingleInstanceService singleInstance = new SingleInstanceService();
// The lifetime has ended: persist the configuration once, then release services. // Secondary instance: forward the command to the primary, then exit immediately.
App.Services?.SaveConfiguration(); if (!singleInstance.TryAcquireSingleInstance())
App.Services?.Dispose(); {
singleInstance.TrySend(command);
return;
}
SingleInstance = singleInstance;
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
// Lifetime ended: persist the configuration once, then release the services.
App.Services.SaveConfiguration();
App.Services.Dispose();
} }
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp() public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>() => AppBuilder.Configure<App>()
.UsePlatformDetect() .UsePlatformDetect()
+26 -126
View File
@@ -2,56 +2,35 @@ using Pidgin;
namespace YKanBan.Search; namespace YKanBan.Search;
/// <summary> /// <summary>Lexical tokens of the search syntax.</summary>
/// Lexical tokens of the search syntax.
/// </summary>
public abstract record SearchToken public abstract record SearchToken
{ {
/// <summary> /// <summary>A bare word; qualifier detection happens later from the text.</summary>
/// A bare word; qualifier detection happens later from the text.
/// </summary>
/// <param name="Text">The word text.</param>
public sealed record Word(string Text) : SearchToken; public sealed record Word(string Text) : SearchToken;
/// <summary> /// <summary>A quoted phrase with escapes already resolved.</summary>
/// A quoted phrase with its escapes already resolved.
/// </summary>
/// <param name="Text">The unescaped phrase content.</param>
public sealed record Phrase(string Text) : SearchToken; public sealed record Phrase(string Text) : SearchToken;
/// <summary> /// <summary>An opening parenthesis.</summary>
/// An opening parenthesis.
/// </summary>
public sealed record OpenParen : SearchToken; public sealed record OpenParen : SearchToken;
/// <summary> /// <summary>A closing parenthesis.</summary>
/// A closing parenthesis.
/// </summary>
public sealed record CloseParen : SearchToken; public sealed record CloseParen : SearchToken;
} }
/// <summary> /// <summary>
/// Pidgin-based lexer for the search syntax. Splits the input into words, /// Pidgin-based lexer for the search syntax. Splits the input into words,
/// quoted phrases and parentheses; whitespace only separates tokens. /// quoted phrases (with \" and \\ escapes) and parentheses; whitespace only
/// /// separates tokens. The lexer is total: it never rejects input — anything
/// The lexer is strict: inside a phrase only <c>\"</c> and <c>\\</c> are valid /// the dedicated rules do not cover falls through to the word rule, and an
/// escapes, a bare backslash or an unknown escape is rejected, a backslash in a /// unterminated phrase simply extends to the end of the input.
/// bare word is rejected, and an unterminated phrase is rejected. A phrase
/// 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>A valid phrase escape sequence: <c>\"</c> or <c>\\</c>.</summary>
private static readonly Parser<char, char> PhraseEscape =
Parser.Try(Parser.String("\\\"").Select(_ => '"'))
.Or(Parser.String("\\\\").Select(_ => '\\'));
/// <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 != '\\')); Parser.Try(Parser.String("\\\"").Select(_ => '"'))
.Or(Parser.Try(Parser.String("\\\\").Select(_ => '\\')))
.Or(Parser.AnyCharExcept('"'));
private static readonly Parser<char, SearchToken> PhraseParser = private static readonly Parser<char, SearchToken> PhraseParser =
from openingQuote in Parser.Char('"') from openingQuote in Parser.Char('"')
@@ -65,109 +44,30 @@ 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(c => !char.IsWhiteSpace(c) && c != '(' && c != ')' && c != '"')
!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())));
// Each token with its source span, so adjacency can be checked afterwards. private static readonly Parser<char, SearchToken> AnyCharacterAsWord =
private static readonly Parser<char, PositionedToken> TokenParser = Parser<char>.Any.Select(c => (SearchToken)new SearchToken.Word(c.ToString()));
private static readonly Parser<char, SearchToken> TokenParser =
Parser.SkipWhitespaces.Then( Parser.SkipWhitespaces.Then(
from start in Parser<char>.CurrentOffset PhraseParser
from token in PhraseParser
.Or(OpenParenParser) .Or(OpenParenParser)
.Or(CloseParenParser) .Or(CloseParenParser)
.Or(WordParser) .Or(WordParser)
from end in Parser<char>.CurrentOffset .Or(AnyCharacterAsWord));
select new PositionedToken(token, start, end));
// Try(...) keeps a failed token non-consuming so Many stops gracefully; End private static readonly Parser<char, IReadOnlyList<SearchToken>> Lexer =
// then rejects any leftover input, which turns dangling quotes or invalid // Try(...) keeps a trailing-whitespace failure non-consuming so Many stops
// escapes into hard failures instead of silently dropped text. // gracefully; the trailing Before(...) then swallows the leftover whitespace.
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) .Select(tokens => (IReadOnlyList<SearchToken>)tokens.ToList());
.Select(tokens => (IReadOnlyList<PositionedToken>)tokens.ToList());
/// <summary> /// <summary>Tokenizes the search text; total over any input.</summary>
/// Tokenizes the search text. public static IReadOnlyList<SearchToken> Tokenize(string input) =>
/// </summary> Lexer.ParseOrThrow(input);
/// <param name="input">The raw search text.</param>
/// <returns>The token stream.</returns>
/// <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)
{
IReadOnlyList<PositionedToken> tokens;
try
{
tokens = Lexer.ParseOrThrow(input);
}
catch (ParseException 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);
} }
+9 -33
View File
@@ -1,7 +1,7 @@
// YYC MARK: C# records synthesize equality by running EqualityComparer<T>.Default // YYC MARK: C# records synthesize equality by running EqualityComparer<T>.Default
// on each positional property. For collection properties (IReadOnlyList<>, // on each positional property. For collection properties (IReadOnlyList<>,
// ImmutableArray<>, arrays, ...) that comparer falls back to REFERENCE equality, // ImmutableArray<>, arrays, ...) that comparer falls back to REFERENCE equality,
// so the Or/And nodes below deliberately do NOT compare structurally. The only // so the And/Or nodes below deliberately do NOT compare structurally. The only
// structural comparison lives in the test helper (SearchNodeComparer); production // structural comparison lives in the test helper (SearchNodeComparer); production
// code never compares AST nodes. // code never compares AST nodes.
namespace YKanBan.Search; namespace YKanBan.Search;
@@ -12,53 +12,29 @@ namespace YKanBan.Search;
/// </summary> /// </summary>
public abstract record SearchNode public abstract record SearchNode
{ {
/// <summary> /// <summary>Disjunction: matches when any term matches (OR).</summary>
/// Disjunction: matches when any term matches (OR).
/// </summary>
/// <param name="Terms">The alternative terms.</param>
public sealed record Or(IReadOnlyList<SearchNode> Terms) : SearchNode; public sealed record Or(IReadOnlyList<SearchNode> Terms) : SearchNode;
/// <summary> /// <summary>Conjunction: matches when all terms match (explicit AND or adjacency).</summary>
/// Conjunction: matches when all terms match (explicit AND or adjacency).
/// </summary>
/// <param name="Terms">The required terms.</param>
public sealed record And(IReadOnlyList<SearchNode> Terms) : SearchNode; public sealed record And(IReadOnlyList<SearchNode> Terms) : SearchNode;
/// <summary> /// <summary>A bare word or phrase matched as a substring of the title OR content.</summary>
/// A bare word or phrase matched as a substring of the title OR content.
/// </summary>
/// <param name="Text">The search text.</param>
public sealed record FreeText(string Text) : SearchNode; public sealed record FreeText(string Text) : SearchNode;
/// <summary> /// <summary>A substring match scoped to one card field.</summary>
/// A substring match scoped to one card field.
/// </summary>
/// <param name="Field">The card field to match against.</param>
/// <param name="Text">The search text.</param>
public sealed record FieldText(SearchField Field, string Text) : SearchNode; public sealed record FieldText(SearchField Field, string Text) : SearchNode;
/// <summary> /// <summary>An exact, case-insensitive tag name match.</summary>
/// An exact, case-insensitive tag name match.
/// </summary>
/// <param name="Name">The tag name to match.</param>
public sealed record TagName(string Name) : SearchNode; public sealed record TagName(string Name) : SearchNode;
/// <summary> /// <summary>An exact, case-insensitive column title match.</summary>
/// An exact, case-insensitive column title match.
/// </summary>
/// <param name="Title">The column title to match.</param>
public sealed record ColumnTitle(string Title) : SearchNode; public sealed record ColumnTitle(string Title) : SearchNode;
/// <summary> /// <summary>An exact card id match.</summary>
/// An exact card id match.
/// </summary>
/// <param name="Id">The card id to match.</param>
public sealed record CardId(long Id) : SearchNode; public sealed record CardId(long Id) : SearchNode;
} }
/// <summary> /// <summary>The card fields a <see cref="SearchNode.FieldText"/> atom can scope to.</summary>
/// The card fields a <see cref="SearchNode.FieldText"/> atom can scope to.
/// </summary>
public enum SearchField public enum SearchField
{ {
/// <summary>The card title.</summary> /// <summary>The card title.</summary>
+69 -176
View File
@@ -3,30 +3,43 @@ using Pidgin;
namespace YKanBan.Search; namespace YKanBan.Search;
/// <summary>
/// Thrown when the search text violates the search grammar. Carries the
/// underlying parser's descriptive message (including the error position);
/// the UI surfaces it as a search error instead of coupling to Pidgin types.
/// </summary>
public sealed class SearchSyntaxException : Exception
{
/// <summary>Creates an exception wrapping the original parse failure.</summary>
public SearchSyntaxException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary> /// <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 operators, unterminated phrases,
/// phrases, invalid escapes, a backslash in a bare word, unknown qualifier /// qualifier keys without a value, non-numeric id values) raises
/// keys, qualifiers without a value, unquoted values containing ':' or equal /// <see cref="SearchSyntaxException"/>. Only uppercase AND/OR are operators
/// to AND/OR, id values that are not an unquoted positive integer with an /// (lowercase ones are plain words); AND — explicit or by adjacency — binds
/// optional '#', and parentheses nested deeper than <see cref="MaxNestingDepth"/>) /// tighter than OR; parentheses group. Blank input returns null and means
/// raises <see cref="SearchSyntaxException"/>. /// "show everything".
///
/// Only uppercase AND/OR are operators (lowercase ones are plain words); AND —
/// explicit or by adjacency — binds tighter than OR; parentheses group. Blank
/// input returns null and means "show everything". Search keywords and
/// qualifier keys are fixed English grammar and are never localized.
/// </summary> /// </summary>
public static class SearchQueryParser public static class SearchQueryParser
{ {
/// <summary> /// <summary>Recognized qualifier kinds; extend <see cref="Qualifiers"/> to add new keys.</summary>
/// Deepest accepted parenthesis nesting. The parser recurses once per level, private enum QualifierKind
/// so an unbounded depth would overflow the stack and kill the process. {
/// </summary> Tag,
public const int MaxNestingDepth = 64; Title,
Content,
Id,
Column,
}
/// <summary>The recognized qualifier keys; add new entries here to extend the grammar.</summary> /// <summary>The qualifier key table ("key:" prefixes); reserved for future keys like created:.</summary>
private static readonly (string Key, QualifierKind Kind)[] QualifierTable = private static readonly (string Key, QualifierKind Kind)[] Qualifiers =
[ [
("tag", QualifierKind.Tag), ("tag", QualifierKind.Tag),
("title", QualifierKind.Title), ("title", QualifierKind.Title),
@@ -38,26 +51,26 @@ public static class SearchQueryParser
#region Token primitives #region Token primitives
private static readonly Parser<SearchToken, SearchToken> AndKeyword = private static readonly Parser<SearchToken, SearchToken> AndKeyword =
Parser<SearchToken>.Token(token => token is SearchToken.Word { Text: "AND" }); Parser<SearchToken>.Token(new SearchToken.Word("AND"));
private static readonly Parser<SearchToken, SearchToken> OrKeyword = private static readonly Parser<SearchToken, SearchToken> OrKeyword =
Parser<SearchToken>.Token(token => token is SearchToken.Word { Text: "OR" }); Parser<SearchToken>.Token(new SearchToken.Word("OR"));
private static readonly Parser<SearchToken, SearchToken> OpenParen = private static readonly Parser<SearchToken, SearchToken> OpenParen =
Parser<SearchToken>.Token(token => token is SearchToken.OpenParen); Parser<SearchToken>.Token((SearchToken)new SearchToken.OpenParen());
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((SearchToken)new SearchToken.CloseParen());
/// <summary>The text of a phrase token.</summary> /// <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(t => t is SearchToken.Phrase)
.Select(token => ((SearchToken.Phrase)token).Text); .Select(t => ((SearchToken.Phrase)t).Text);
/// <summary>The text of a word token, operator keywords excluded (they never start an operand).</summary> /// <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(t => t is SearchToken.Word w && w.Text != "AND" && w.Text != "OR")
.Select(token => ((SearchToken.Word)token).Text); .Select(t => ((SearchToken.Word)t).Text);
#endregion #endregion
@@ -100,16 +113,11 @@ public static class SearchQueryParser
OrExpr.Before(Parser<SearchToken>.End); OrExpr.Before(Parser<SearchToken>.End);
/// <summary>Defers the OrExpr field read to parse time (recursion cycle breaker).</summary> /// <summary>Defers the OrExpr field read to parse time (recursion cycle breaker).</summary>
/// <returns>The OR-expression parser.</returns>
private static Parser<SearchToken, SearchNode> OrExprDeferred() => OrExpr; private static Parser<SearchToken, SearchNode> OrExprDeferred() => OrExpr;
#endregion #endregion
/// <summary> /// <summary>Parses a search box text; returns null for blank input (meaning: show everything).</summary>
/// Parses a search box text.
/// </summary>
/// <param name="text">The raw search text.</param>
/// <returns>The parsed query, or <see langword="null"/> for blank input (meaning: show everything).</returns>
/// <exception cref="SearchSyntaxException">The text violates the grammar.</exception> /// <exception cref="SearchSyntaxException">The text violates the grammar.</exception>
public static SearchNode? Parse(string text) public static SearchNode? Parse(string text)
{ {
@@ -121,181 +129,66 @@ public static class SearchQueryParser
try try
{ {
List<SearchToken> tokens = SearchLexer.Tokenize(text).ToList(); List<SearchToken> tokens = SearchLexer.Tokenize(text).ToList();
EnsureNestingWithinLimit(tokens);
return Query.ParseOrThrow(tokens); return Query.ParseOrThrow(tokens);
} }
catch (ParseException exception) catch (ParseException ex)
{ {
throw new SearchSyntaxException(exception.Message, exception); throw new SearchSyntaxException(ex.Message, ex);
} }
} }
/// <summary> /// <summary>Builds the parser for one word operand: qualifier atom or free text.</summary>
/// Rejects parenthesis nesting deeper than <see cref="MaxNestingDepth"/>
/// before the recursive parser sees it. Balance itself is left to the parser.
/// </summary>
/// <param name="tokens">The token stream.</param>
/// <exception cref="SearchSyntaxException">The nesting is too deep.</exception>
private static void EnsureNestingWithinLimit(IEnumerable<SearchToken> tokens)
{
int depth = 0;
foreach (SearchToken token in tokens)
{
if (token is SearchToken.OpenParen && ++depth > MaxNestingDepth)
{
throw new SearchSyntaxException($"Parentheses are nested more than {MaxNestingDepth} levels deep.");
}
if (token is SearchToken.CloseParen && depth > 0)
{
depth--;
}
}
}
#region Atom construction
/// <summary>
/// Builds the parser for one word operand: a qualifier atom, an unknown-key
/// failure, or free text.
/// </summary>
/// <param name="word">The word token text.</param>
/// <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(':'); foreach ((string key, QualifierKind kind) in Qualifiers)
if (colonIndex < 0)
{ {
// Qualifier keys are case-sensitive lowercase grammar tokens.
if (!word.StartsWith(key + ":", StringComparison.Ordinal))
{
continue;
}
string value = word[(key.Length + 1)..];
// "key:" without an inline value takes the value from the following phrase, e.g. tag:"a b".
return value.Length == 0
? PhraseText.Bind(text => AtomParser(kind, text))
: AtomParser(kind, value);
}
// No qualifier prefix: a plain free-text word.
return Parser<SearchToken>.Return<SearchNode>(new SearchNode.FreeText(word)); 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. /// <summary>Builds the atom parser for a qualifier value, failing strictly on a non-numeric id.</summary>
string key = word[..colonIndex]; private static Parser<SearchToken, SearchNode> AtomParser(QualifierKind kind, string value)
string value = word[(colonIndex + 1)..];
if (!TryLookupQualifier(key, out QualifierKind kind))
{ {
return Parser<SearchToken>.Fail<SearchNode>($"Unknown qualifier key '{key}'; quote the text to search for it literally."); return AtomFrom(kind, value) is { } atom
? Parser<SearchToken>.Return(atom)
: Parser<SearchToken>.Fail<SearchNode>($"id: expects an integer, got '{value}'.");
} }
// "key:" without an inline value takes the value from the following phrase, e.g. tag:"a b". /// <summary>Builds the atom for a qualifier value; null when an id value is not an integer.</summary>
if (value.Length == 0) private static SearchNode? AtomFrom(QualifierKind kind, string value) => kind switch
{
return kind == QualifierKind.Id
? Parser<SearchToken>.Fail<SearchNode>("The id qualifier expects an unquoted positive integer.")
: PhraseText.Select(text => TextAtom(kind, text));
}
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>
/// Builds the atom for a textual qualifier value.
/// </summary>
/// <param name="kind">The qualifier kind; never <see cref="QualifierKind.Id"/>.</param>
/// <param name="value">The qualifier value.</param>
/// <returns>The atom node.</returns>
private static SearchNode TextAtom(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),
_ => throw new InvalidOperationException($"Qualifier kind {kind} has no textual value."), QualifierKind.Id when long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out long id) => new SearchNode.CardId(id),
_ => null,
}; };
/// <summary> /// <summary>Collapses an AND chain into a single node.</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>
/// Looks up a qualifier key in the extension table with ordinal (case-sensitive) matching.
/// </summary>
/// <param name="key">The key text before the colon.</param>
/// <param name="kind">The matching qualifier kind.</param>
/// <returns><see langword="true"/> when the key is known.</returns>
private static bool TryLookupQualifier(string key, out QualifierKind kind)
{
foreach ((string candidate, QualifierKind candidateKind) in QualifierTable)
{
if (string.Equals(candidate, key, StringComparison.Ordinal))
{
kind = candidateKind;
return true;
}
}
kind = default;
return false;
}
/// <summary>
/// Collapses an AND chain into a single node.
/// </summary>
/// <param name="first">The first operand.</param>
/// <param name="rest">The remaining operands.</param>
/// <returns>The single operand, or an <see cref="SearchNode.And"/> node.</returns>
private static SearchNode FoldAnd(SearchNode first, IEnumerable<SearchNode> rest) private static SearchNode FoldAnd(SearchNode first, IEnumerable<SearchNode> rest)
{ {
List<SearchNode> terms = [first, .. rest]; List<SearchNode> terms = [first, .. rest];
return terms.Count == 1 ? terms[0] : new SearchNode.And(terms); return terms.Count == 1 ? terms[0] : new SearchNode.And(terms);
} }
/// <summary> /// <summary>Collapses an OR chain into a single node.</summary>
/// Collapses an OR chain into a single node.
/// </summary>
/// <param name="terms">The operands.</param>
/// <returns>The single operand, or a <see cref="SearchNode.Or"/> node.</returns>
private static SearchNode FoldOr(IEnumerable<SearchNode> terms) private static SearchNode FoldOr(IEnumerable<SearchNode> terms)
{ {
List<SearchNode> list = terms.ToList(); List<SearchNode> list = terms.ToList();
return list.Count == 1 ? list[0] : new SearchNode.Or(list); return list.Count == 1 ? list[0] : new SearchNode.Or(list);
} }
#endregion
/// <summary>The recognized qualifier kinds.</summary>
private enum QualifierKind
{
Tag,
Title,
Content,
Id,
Column,
}
} }
+22 -52
View File
@@ -1,30 +1,20 @@
using YKanBan.Storage;
namespace YKanBan.Search; namespace YKanBan.Search;
/// <summary> /// <summary>A compiled search predicate: a SQL fragment over the "c" (cards) alias plus its bound parameters.</summary>
/// A compiled search predicate: a SQL fragment over the "c" (cards) alias plus /// <param name="Predicate">SQL boolean expression; intended for "SELECT ... FROM cards c WHERE {Predicate}".</param>
/// its bound parameters.
/// </summary>
/// <param name="Predicate">SQL boolean expression, for <c>SELECT ... FROM cards c WHERE {Predicate}</c>.</param>
/// <param name="Parameters">Named parameters referenced by the predicate, in order.</param> /// <param name="Parameters">Named parameters referenced by the predicate, in order.</param>
public sealed record CompiledSearch(string Predicate, IReadOnlyList<(string Name, object Value)> Parameters); public sealed record CompiledSearch(string Predicate, IReadOnlyList<(string Name, object Value)> Parameters);
/// <summary> /// <summary>
/// Compiles a parsed search AST into a parameterized SQL predicate. Matching is /// Compiles a parsed search AST into a parameterized SQL predicate.
/// Unicode case-insensitive: both sides are folded with /// Matching is case-insensitive with SQLite's built-in ASCII semantics:
/// <see cref="SqliteDatabase.Fold"/> (the column side through the per-connection /// LIKE's default case folding plus COLLATE NOCASE for exact matches.
/// <see cref="SqliteDatabase.FoldFunctionName"/> function) and then compared /// LIKE wildcards and the escape character in user text are escaped so they
/// ordinally — <c>instr</c> for substrings, <c>=</c> for exact matches. LIKE is /// match literally.
/// 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>Compiles the query into a SQL predicate.</summary>
/// Compiles the query into a SQL predicate.
/// </summary>
/// <param name="query">The parsed search AST.</param>
/// <returns>The compiled predicate and its parameters.</returns>
public static CompiledSearch Compile(SearchNode query) public static CompiledSearch Compile(SearchNode query)
{ {
var parameters = new List<(string Name, object Value)>(); var parameters = new List<(string Name, object Value)>();
@@ -32,12 +22,7 @@ public static class SearchSqlCompiler
return new CompiledSearch(predicate, parameters); return new CompiledSearch(predicate, parameters);
} }
/// <summary> /// <summary>Recursively builds the SQL expression for one node.</summary>
/// Recursively builds the SQL expression for one node.
/// </summary>
/// <param name="node">The AST node to compile.</param>
/// <param name="parameters">The parameter accumulator.</param>
/// <returns>The SQL boolean expression for the node.</returns>
private static string Build(SearchNode node, List<(string Name, object Value)> parameters) private static string Build(SearchNode node, List<(string Name, object Value)> parameters)
{ {
switch (node) switch (node)
@@ -51,28 +36,29 @@ 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 param = AddParameter(parameters, SqliteDatabase.Fold(freeText.Text)); string titleParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
return $"({Contains("c.title", param)} OR {Contains("c.content", param)})"; string contentParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
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, SqliteDatabase.Fold(field.Text)); string param = AddParameter(parameters, "%" + EscapeLike(field.Text) + "%");
return Contains(column, param); return $"{column} LIKE {param} ESCAPE '\\'";
} }
case SearchNode.TagName tag: case SearchNode.TagName tag:
{ {
string param = AddParameter(parameters, SqliteDatabase.Fold(tag.Name)); string param = AddParameter(parameters, 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 {Folded("t.name")} = {param})"; $"WHERE ct.card_id = c.id AND t.name COLLATE NOCASE = {param})";
} }
case SearchNode.ColumnTitle column: case SearchNode.ColumnTitle column:
{ {
string param = AddParameter(parameters, SqliteDatabase.Fold(column.Title)); string param = AddParameter(parameters, column.Title);
return $"c.column_id IN (SELECT id FROM columns WHERE {Folded("title")} = {param})"; return $"c.column_id IN (SELECT id FROM columns WHERE title COLLATE NOCASE = {param})";
} }
case SearchNode.CardId id: case SearchNode.CardId id:
@@ -86,12 +72,7 @@ public static class SearchSqlCompiler
} }
} }
/// <summary> /// <summary>Binds a value under a fresh name and returns the SQL placeholder.</summary>
/// Binds a value under a fresh name and returns the SQL placeholder.
/// </summary>
/// <param name="parameters">The parameter accumulator.</param>
/// <param name="value">The value to bind.</param>
/// <returns>The placeholder text.</returns>
private static string AddParameter(List<(string Name, object Value)> parameters, object value) private static string AddParameter(List<(string Name, object Value)> parameters, object value)
{ {
string name = "$p" + parameters.Count.ToString(System.Globalization.CultureInfo.InvariantCulture); string name = "$p" + parameters.Count.ToString(System.Globalization.CultureInfo.InvariantCulture);
@@ -99,18 +80,7 @@ public static class SearchSqlCompiler
return name; return name;
} }
/// <summary> /// <summary>Escapes LIKE wildcards and the escape character inside user text.</summary>
/// Wraps a column expression in the case-folding SQL function. private static string EscapeLike(string text) =>
/// </summary> text.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_");
/// <param name="column">The column expression.</param>
/// <returns>The folded column expression.</returns>
private static string Folded(string column) => $"{SqliteDatabase.FoldFunctionName}({column})";
/// <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";
} }
-29
View File
@@ -1,29 +0,0 @@
namespace YKanBan.Search;
/// <summary>
/// Thrown when the search text violates the search grammar. Carries the
/// underlying parser's descriptive English message; the UI surfaces it as a
/// search error instead of coupling to Pidgin types. The message is never
/// localized.
/// </summary>
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>
/// Initializes the exception with a descriptive English message.
/// </summary>
/// <param name="message">The English diagnostic message.</param>
/// <param name="innerException">The underlying parse failure.</param>
public SearchSyntaxException(string message, Exception innerException)
: base(message, innerException)
{
}
}
+28 -51
View File
@@ -1,74 +1,51 @@
using YKanBan.Platform;
using YKanBan.Storage.AppData; using YKanBan.Storage.AppData;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
namespace YKanBan.Services; namespace YKanBan.Services;
/// <summary> /// <summary>
/// Composition root for the whole process: owns the loaded configuration and /// Composition root: owns the application-wide configuration, the global
/// the single open workspace session. The configuration is persisted once at /// workspace registry and the workspace connection pool for the whole
/// shutdown, and only when this session changed it; the session (lock plus connection) lives until disposal. /// process lifetime. The configuration is persisted once at shutdown.
/// </summary> /// </summary>
public sealed class AppServices : IDisposable public sealed class AppServices : IDisposable
{ {
/// <summary> /// <summary>Maximum number of simultaneously open workspaces.</summary>
/// Loads the configuration and prepares the service graph. private const int PoolCapacity = 8;
/// </summary>
/// <summary>Loads the configuration and opens the global services.</summary>
public AppServices() public AppServices()
{ {
ConfigStore = new AppConfigStore(AppDataPaths.AppConfigJsonPath); ConfigStore = new AppConfigStore(AppDataPaths.AppConfigJsonPath);
Config = ConfigStore.Load(); Config = ConfigStore.Load();
Database = new AppDatabase(AppDataPaths.AppDatabasePath);
PathComparison = PathComparer.ForCurrentPlatform();
Pool = new WorkspaceConnectionPool(PoolCapacity, Database, PathComparison);
} }
/// <summary> /// <summary>The mutable application configuration; persisted by <see cref="SaveConfiguration"/>.</summary>
/// Gets the mutable application configuration, persisted at shutdown.
/// </summary>
public AppConfig Config { get; } public AppConfig Config { get; }
/// <summary> /// <summary>Store for app.json.</summary>
/// Gets the store backing app.json.
/// </summary>
public AppConfigStore ConfigStore { get; } public AppConfigStore ConfigStore { get; }
/// <summary> /// <summary>Global workspace registry (app.db).</summary>
/// Gets the open workspace session, or <see langword="null"/> while no public AppDatabase Database { get; }
/// workspace is open (for example on an error page).
/// </summary>
public WorkspaceSession? Session { get; private set; }
/// <summary> /// <summary>LRU pool of open workspace sessions.</summary>
/// Opens a workspace, acquiring its exclusive lock and connection. public WorkspaceConnectionPool Pool { get; }
/// </summary>
/// <param name="folderPath">The workspace folder to open.</param> /// <summary>Platform path comparison rules.</summary>
/// <returns>The open session.</returns> public PathComparer PathComparison { get; }
/// <exception cref="YKanBan.Storage.WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
/// <exception cref="YKanBan.Storage.WorkspaceLockException">Another instance already holds the lock.</exception> /// <summary>Persists the configuration; called once at shutdown.</summary>
public WorkspaceSession OpenWorkspace(string folderPath) public void SaveConfiguration() => ConfigStore.Save(Config);
/// <summary>Releases the pool and the registry.</summary>
public void Dispose()
{ {
Session = WorkspaceSession.Open(folderPath); Pool.Dispose();
return Session; Database.Dispose();
} }
/// <summary>
/// Initializes a workspace with its preset columns and opens it, holding
/// the lock from the creation of .ykanban onwards.
/// </summary>
/// <param name="folderPath">The existing 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>
/// Persists the configuration when this session changed a setting; called once at shutdown.
/// </summary>
public void SaveConfiguration() => ConfigStore.SaveIfChanged(Config);
/// <summary>
/// Releases the workspace session, if any.
/// </summary>
public void Dispose() => Session?.Dispose();
} }
+51 -91
View File
@@ -3,17 +3,18 @@ using Newtonsoft.Json;
namespace YKanBan.Storage.AppData; namespace YKanBan.Storage.AppData;
/// <summary> /// <summary>Card ordering options. All orders fall back to id ascending.</summary>
/// Card ordering options. Every order falls back to id ascending as the final
/// tie-breaker.
/// </summary>
public enum CardSortOption public enum CardSortOption
{ {
/// <summary>Primary key ascending (default).</summary> /// <summary>Ascending primary key (default).</summary>
[EnumMember(Value = "id")] [EnumMember(Value = "id")]
Id, Id,
/// <summary>Last modification time, most recently modified first.</summary> /// <summary>Creation time, oldest first.</summary>
[EnumMember(Value = "created-at")]
CreatedAt,
/// <summary>Last modification time, most recent first.</summary>
[EnumMember(Value = "updated-at")] [EnumMember(Value = "updated-at")]
UpdatedAt, UpdatedAt,
@@ -22,9 +23,23 @@ public enum CardSortOption
Title, Title,
} }
/// <summary> /// <summary>Sidebar workspace list ordering.</summary>
/// Column width presets. <see cref="Custom"/> uses a user-defined pixel width. public enum SidebarSortOption
/// </summary> {
/// <summary>Folder name A to Z.</summary>
[EnumMember(Value = "name-asc")]
NameAsc,
/// <summary>Folder name Z to A.</summary>
[EnumMember(Value = "name-desc")]
NameDesc,
/// <summary>By workspace last edit time, most recent first.</summary>
[EnumMember(Value = "recently-updated")]
RecentlyUpdated,
}
/// <summary>Column width presets. Custom uses a user-defined pixel width.</summary>
public enum ColumnWidthPreset public enum ColumnWidthPreset
{ {
/// <summary>Narrow preset.</summary> /// <summary>Narrow preset.</summary>
@@ -44,9 +59,7 @@ public enum ColumnWidthPreset
Custom, Custom,
} }
/// <summary> /// <summary>UI theme selection.</summary>
/// UI theme selection.
/// </summary>
public enum ThemeOption public enum ThemeOption
{ {
/// <summary>Always light.</summary> /// <summary>Always light.</summary>
@@ -62,138 +75,85 @@ public enum ThemeOption
FollowSystem, FollowSystem,
} }
/// <summary> /// <summary>Card and sidebar list ordering settings.</summary>
/// Card ordering settings. The chosen order is global, not per workspace.
/// </summary>
public sealed class SortSettings public sealed class SortSettings
{ {
/// <summary> /// <summary>Card order used by all workspaces (global, not per workspace).</summary>
/// Gets or sets the order used by the board.
/// </summary>
[JsonProperty("card")] [JsonProperty("card")]
public CardSortOption Card { get; set; } = CardSortOption.Id; public CardSortOption Card { get; set; } = CardSortOption.Id;
/// <summary>Sidebar workspace list order.</summary>
[JsonProperty("sidebar")]
public SidebarSortOption Sidebar { get; set; } = SidebarSortOption.NameAsc;
} }
/// <summary> /// <summary>Board column width settings.</summary>
/// Board column width settings, applied globally.
/// </summary>
public sealed class ColumnWidthSettings public sealed class ColumnWidthSettings
{ {
/// <summary> /// <summary>Width preset applied globally.</summary>
/// Gets or sets the active width preset.
/// </summary>
[JsonProperty("preset")] [JsonProperty("preset")]
public ColumnWidthPreset Preset { get; set; } = ColumnWidthPreset.Standard; public ColumnWidthPreset Preset { get; set; } = ColumnWidthPreset.Standard;
/// <summary> /// <summary>Manual width in pixels used when <see cref="Preset"/> is Custom (range 160–720).</summary>
/// Gets or sets the manual width in pixels, used when <see cref="Preset"/>
/// is <see cref="ColumnWidthPreset.Custom"/> (range 160–720).
/// </summary>
[JsonProperty("custom-pixels")] [JsonProperty("custom-pixels")]
public int CustomPixels { get; set; } = 320; public int CustomPixels { get; set; } = 320;
} }
/// <summary> /// <summary>Confirmation-dialog toggles for destructive actions.</summary>
/// Confirmation-dialog toggles for the destructive actions.
/// </summary>
public sealed class ConfirmationSettings public sealed class ConfirmationSettings
{ {
/// <summary> /// <summary>Whether deleting a card asks for confirmation.</summary>
/// Gets or sets whether deleting a card asks for confirmation.
/// </summary>
[JsonProperty("delete-card")] [JsonProperty("delete-card")]
public bool DeleteCard { get; set; } = true; public bool DeleteCard { get; set; } = true;
/// <summary> /// <summary>Whether deleting a column asks for confirmation.</summary>
/// Gets or sets whether deleting a column asks for confirmation.
/// </summary>
[JsonProperty("delete-column")] [JsonProperty("delete-column")]
public bool DeleteColumn { get; set; } = true; public bool DeleteColumn { get; set; } = true;
/// <summary> /// <summary>Whether deleting a tag asks for confirmation.</summary>
/// Gets or sets whether deleting a tag asks for confirmation.
/// </summary>
[JsonProperty("delete-tag")] [JsonProperty("delete-tag")]
public bool DeleteTag { get; set; } = true; public bool DeleteTag { get; set; } = true;
/// <summary> /// <summary>Whether discarding card edits asks for confirmation.</summary>
/// Gets or sets whether discarding card edits asks for confirmation.
/// </summary>
[JsonProperty("discard-edit")] [JsonProperty("discard-edit")]
public bool DiscardEdit { get; set; } = true; public bool DiscardEdit { get; set; } = true;
} }
/// <summary> /// <summary>
/// Root object of app.json, the whole-file key/value configuration store. /// Root object of app.json — the trivial KV configuration store. Serialized
/// Keys and enum values are serialized in kebab-case (declared explicitly via /// as a whole with kebab-case names (declared via [JsonProperty] and
/// <see cref="JsonPropertyAttribute"/> and <see cref="EnumMemberAttribute"/>). /// [EnumMember]); the "version" field is the migration hook for future
/// The <c>version</c> field is the migration hook for future format changes. /// format changes.
/// </summary> /// </summary>
public sealed class AppConfig public sealed class AppConfig
{ {
/// <summary> /// <summary>Current configuration format version.</summary>
/// Current configuration format version.
/// </summary>
public const int CurrentFormatVersion = 1; public const int CurrentFormatVersion = 1;
/// <summary> /// <summary>The default UI language code.</summary>
/// Default UI language code.
/// </summary>
public const string DefaultLanguage = "en"; public const string DefaultLanguage = "en";
/// <summary> /// <summary>Configuration format version of this file.</summary>
/// Simplified Chinese UI language code.
/// </summary>
public const string SimplifiedChineseLanguage = "zh-Hans";
/// <summary>
/// Gets the supported UI language codes; any other stored value falls back to <see cref="DefaultLanguage"/>.
/// </summary>
public static IReadOnlyList<string> SupportedLanguages { get; } = [DefaultLanguage, SimplifiedChineseLanguage];
/// <summary>
/// Smallest accepted custom column width in pixels.
/// </summary>
public const int MinColumnPixels = 160;
/// <summary>
/// Largest accepted custom column width in pixels.
/// </summary>
public const int MaxColumnPixels = 720;
/// <summary>
/// Gets or sets the configuration format version of this file.
/// </summary>
[JsonProperty("version")] [JsonProperty("version")]
public int Version { get; set; } = CurrentFormatVersion; public int Version { get; set; } = CurrentFormatVersion;
/// <summary> /// <summary>UI language code: "en" (default) or "zh-Hans".</summary>
/// Gets or sets the UI language code ("en" default or "zh-Hans").
/// </summary>
[JsonProperty("language")] [JsonProperty("language")]
public string Language { get; set; } = DefaultLanguage; public string Language { get; set; } = DefaultLanguage;
/// <summary> /// <summary>UI theme selection (default: follow the system).</summary>
/// Gets or sets the UI theme selection (default: follow the system).
/// </summary>
[JsonProperty("theme")] [JsonProperty("theme")]
public ThemeOption Theme { get; set; } = ThemeOption.FollowSystem; public ThemeOption Theme { get; set; } = ThemeOption.FollowSystem;
/// <summary> /// <summary>Ordering settings.</summary>
/// Gets or sets the card ordering settings.
/// </summary>
[JsonProperty("sort")] [JsonProperty("sort")]
public SortSettings Sort { get; set; } = new(); public SortSettings Sort { get; set; } = new();
/// <summary> /// <summary>Column width settings.</summary>
/// Gets or sets the board column width settings.
/// </summary>
[JsonProperty("column-width")] [JsonProperty("column-width")]
public ColumnWidthSettings ColumnWidth { get; set; } = new(); public ColumnWidthSettings ColumnWidth { get; set; } = new();
/// <summary> /// <summary>Confirmation-dialog settings.</summary>
/// Gets or sets the confirmation-dialog settings.
/// </summary>
[JsonProperty("confirmations")] [JsonProperty("confirmations")]
public ConfirmationSettings Confirmations { get; set; } = new(); public ConfirmationSettings Confirmations { get; set; } = new();
} }
+20 -152
View File
@@ -1,17 +1,13 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Converters; using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
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 file yields
/// defaults; a file that is not a JSON object is backed up to app.json.bak and /// defaults; a corrupt file is backed up to app.json.bak and then defaults
/// then defaults are used; an individual invalid field (unknown enum value or /// are used. Saving writes the file directly (no atomic replace) — losing
/// language, out-of-range width, wrong type) falls back to its own default while /// the last session's settings to a crash is an accepted trade-off.
/// the other fields are kept. Saving happens only when the configuration differs
/// from what was loaded, and writes the file directly (no atomic replace) —
/// losing the last session's settings to a crash is an accepted trade-off.
/// </summary> /// </summary>
public sealed class AppConfigStore public sealed class AppConfigStore
{ {
@@ -20,87 +16,19 @@ public sealed class AppConfigStore
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].
// numeric enum values are rejected like any other unknown value. Converters = { new StringEnumConverter() },
Converters = { new StringEnumConverter { AllowIntegerValues = false } },
}; };
private static readonly JsonSerializer FieldTolerantSerializer = JsonSerializer.Create(new JsonSerializerSettings /// <summary>Creates a store bound to a specific app.json path.</summary>
{
NullValueHandling = NullValueHandling.Ignore,
Converters = { new StringEnumConverter { AllowIntegerValues = false } },
// The JSON text is already known to be well formed here, so every error is a
// single member that fails to convert: skip it and keep that member's default.
Error = (_, args) => args.ErrorContext.Handled = true,
});
/// <summary>The serialized form of the configuration as last loaded or saved.</summary>
private string _persistedSnapshot = Serialize(new AppConfig());
/// <summary>
/// Initializes a store bound to a specific app.json path.
/// </summary>
/// <param name="filePath">Full path of the app.json file to manage.</param>
public AppConfigStore(string filePath) => FilePath = filePath; public AppConfigStore(string filePath) => FilePath = filePath;
/// <summary> /// <summary>Full path of the managed app.json file.</summary>
/// Gets the full path of the managed app.json file.
/// </summary>
public string FilePath { get; } public string FilePath { get; }
/// <summary> /// <summary>Loads the configuration: missing file → defaults; corrupt file → backup then defaults.</summary>
/// Loads the configuration and records it as the persisted baseline for
/// <see cref="SaveIfChanged"/>. A missing file yields defaults; a file that
/// is not a JSON object is backed up to app.json.bak and then defaults are
/// used; invalid fields fall back to their defaults individually.
/// </summary>
/// <returns>The loaded configuration, or defaults when none could be read.</returns>
/// <exception cref="IOException">The file exists but cannot be read.</exception> /// <exception cref="IOException">The file exists but cannot be read.</exception>
public AppConfig Load() public AppConfig Load()
{
AppConfig config = Read();
// The baseline is the effective configuration, so field fallbacks alone never trigger a write.
_persistedSnapshot = Serialize(config);
return config;
}
/// <summary>
/// Writes the configuration only when it differs from the loaded or last
/// saved one, i.e. when this session changed a setting.
/// </summary>
/// <param name="config">The live configuration.</param>
/// <returns><see langword="true"/> when the file was written.</returns>
public bool SaveIfChanged(AppConfig config)
{
string json = Serialize(config);
if (json == _persistedSnapshot)
{
return false;
}
Write(json);
_persistedSnapshot = json;
return true;
}
/// <summary>
/// Writes the configuration directly to disk (no atomic replace), unconditionally.
/// </summary>
/// <param name="config">The configuration to serialize.</param>
public void Save(AppConfig config)
{
string json = Serialize(config);
Write(json);
_persistedSnapshot = json;
}
/// <summary>
/// Reads and sanitizes the file.
/// </summary>
/// <returns>The effective configuration.</returns>
private AppConfig Read()
{ {
// 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))
@@ -109,98 +37,38 @@ public sealed class AppConfigStore
} }
string json = File.ReadAllText(FilePath); string json = File.ReadAllText(FilePath);
JToken root;
try try
{ {
root = JToken.Parse(json); // A JSON null literal deserializes to null; treat it like defaults.
} AppConfig? config = JsonConvert.DeserializeObject<AppConfig>(json, SerializerSettings);
catch (JsonException) if (config is null)
{
return BackUpAndUseDefaults();
}
// A JSON null literal carries no settings at all; treat it like a missing file.
if (root.Type == JTokenType.Null)
{ {
return new AppConfig(); return new AppConfig();
} }
// Well-formed JSON of the wrong shape has no field to keep: handle it like corrupt text.
if (root is not JObject rootObject)
{
return BackUpAndUseDefaults();
}
AppConfig config = rootObject.ToObject<AppConfig>(FieldTolerantSerializer) ?? new AppConfig();
Sanitize(config);
return config;
}
/// <summary>
/// Keeps a copy of an unusable file for inspection, then continues with defaults.
/// </summary>
/// <returns>The default configuration.</returns>
private AppConfig BackUpAndUseDefaults()
{
File.Copy(FilePath, FilePath + ".bak", overwrite: true);
return new AppConfig();
}
/// <summary>
/// Replaces every value that converted but is outside its domain with the field default.
/// </summary>
/// <param name="config">The freshly deserialized configuration.</param>
private static void Sanitize(AppConfig config)
{
var defaults = new AppConfig();
// Older or hand-edited files may miss whole sections; each falls back to its defaults. // Older or hand-edited files may miss whole sections; each falls back to its defaults.
config.Sort ??= new SortSettings(); config.Sort ??= new SortSettings();
config.ColumnWidth ??= new ColumnWidthSettings(); config.ColumnWidth ??= new ColumnWidthSettings();
config.Confirmations ??= new ConfirmationSettings(); config.Confirmations ??= new ConfirmationSettings();
return config;
if (config.Language is null || !AppConfig.SupportedLanguages.Contains(config.Language, StringComparer.Ordinal))
{
config.Language = defaults.Language;
} }
if (!Enum.IsDefined(config.Theme)) catch (JsonException)
{ {
config.Theme = defaults.Theme; // Corrupt: keep a copy for inspection, then continue with defaults.
} File.Copy(FilePath, FilePath + ".bak", overwrite: true);
if (!Enum.IsDefined(config.Sort.Card)) return new AppConfig();
{
config.Sort.Card = defaults.Sort.Card;
}
if (!Enum.IsDefined(config.ColumnWidth.Preset))
{
config.ColumnWidth.Preset = defaults.ColumnWidth.Preset;
}
if (config.ColumnWidth.CustomPixels is < AppConfig.MinColumnPixels or > AppConfig.MaxColumnPixels)
{
config.ColumnWidth.CustomPixels = defaults.ColumnWidth.CustomPixels;
} }
} }
/// <summary> /// <summary>Writes the configuration directly to disk (no atomic replace).</summary>
/// Writes the serialized configuration, creating the parent folder on demand. public void Save(AppConfig config)
/// </summary>
/// <param name="json">The serialized configuration.</param>
private void Write(string json)
{ {
// Normally the folder already exists. // Create the parent folder on demand; normally it exists already.
string? directory = Path.GetDirectoryName(FilePath); string? directory = Path.GetDirectoryName(FilePath);
if (!string.IsNullOrEmpty(directory)) if (!string.IsNullOrEmpty(directory))
{ {
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
} }
File.WriteAllText(FilePath, JsonConvert.SerializeObject(config, SerializerSettings));
File.WriteAllText(FilePath, json);
} }
/// <summary>
/// Serializes a configuration in the on-disk format.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The JSON text.</returns>
private static string Serialize(AppConfig config) => JsonConvert.SerializeObject(config, SerializerSettings);
} }
+6 -11
View File
@@ -1,20 +1,15 @@
namespace YKanBan.Storage.AppData; namespace YKanBan.Storage.AppData;
/// <summary> /// <summary>Well-known locations under the per-user application data folder.</summary>
/// Well-known locations under the per-user application data folder
/// (%APPDATA%/YKanBan on Windows and the equivalent directory on other
/// platforms).
/// </summary>
public static class AppDataPaths public static class AppDataPaths
{ {
/// <summary> /// <summary>The per-user YKanBan application data folder.</summary>
/// Gets the per-user YKanBan application data folder.
/// </summary>
public static string Directory => public static string Directory =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "YKanBan"); Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "YKanBan");
/// <summary> /// <summary>Full path of app.json.</summary>
/// Gets the full path of app.json.
/// </summary>
public static string AppConfigJsonPath => Path.Combine(Directory, "app.json"); public static string AppConfigJsonPath => Path.Combine(Directory, "app.json");
/// <summary>Full path of app.db.</summary>
public static string AppDatabasePath => Path.Combine(Directory, "app.db");
} }
+122
View File
@@ -0,0 +1,122 @@
using Microsoft.Data.Sqlite;
namespace YKanBan.Storage.AppData;
/// <summary>A known workspace row of the global app.db.</summary>
/// <param name="Path">Workspace folder path as registered.</param>
/// <param name="LastEditedAt">Unix seconds of the last successful data write to the workspace database.</param>
/// <param name="AddedAt">Unix seconds when the workspace was registered.</param>
public sealed record WorkspaceRecord(string Path, long LastEditedAt, long AddedAt);
/// <summary>
/// Global application database (app.db): stores the persistent workspace
/// list. Any successful data write into a workspace database must be
/// mirrored here by refreshing last_edited_at (the write-through is wired
/// by the repository layer). Uses the same PRAGMA configuration as the
/// workspace databases.
/// </summary>
public sealed class AppDatabase : IDisposable
{
/// <summary>Latest app.db schema version this build understands.</summary>
public const int CurrentSchemaVersion = 1;
private static readonly IReadOnlyList<SchemaMigration> Migrations = new SchemaMigration[]
{
new SchemaMigration(CurrentSchemaVersion, "initial schema", """
CREATE TABLE workspaces (
path TEXT PRIMARY KEY,
last_edited_at INTEGER NOT NULL,
added_at INTEGER NOT NULL
);
"""),
};
private readonly SqliteConnection _connection;
private readonly Func<long> _unixNow;
private readonly object _gate = new();
/// <summary>Opens (creating if needed) the app.db file and applies pending migrations.</summary>
/// <param name="databasePath">Path of the app.db file.</param>
/// <param name="unixNow">Clock override for tests; defaults to real Unix time.</param>
public AppDatabase(string databasePath, Func<long>? unixNow = null)
{
// Ensure the application data folder exists before creating the database file.
string? directory = Path.GetDirectoryName(databasePath);
if (!string.IsNullOrEmpty(directory))
{
Directory.CreateDirectory(directory);
}
_unixNow = unixNow ?? (() => UnixTime.Now);
_connection = SqliteDatabase.Open(databasePath, Migrations);
}
/// <summary>Returns all known workspaces ordered by added_at ascending.</summary>
public IReadOnlyList<WorkspaceRecord> GetWorkspaces()
{
lock (_gate)
{
using var command = _connection.CreateCommand();
command.CommandText = "SELECT path, last_edited_at, added_at FROM workspaces ORDER BY added_at ASC, path ASC;";
using var reader = command.ExecuteReader();
var records = new List<WorkspaceRecord>();
while (reader.Read())
{
records.Add(new WorkspaceRecord(reader.GetString(0), reader.GetInt64(1), reader.GetInt64(2)));
}
return records;
}
}
/// <summary>Registers a workspace, or refreshes last_edited_at if it is already known.</summary>
public void UpsertWorkspace(string path)
{
lock (_gate)
{
long now = _unixNow();
using var command = _connection.CreateCommand();
// On conflict only last_edited_at moves; the original added_at is preserved.
command.CommandText = """
INSERT INTO workspaces (path, last_edited_at, added_at)
VALUES ($path, $now, $now)
ON CONFLICT(path) DO UPDATE SET last_edited_at = $now;
""";
command.Parameters.AddWithValue("$path", path);
command.Parameters.AddWithValue("$now", now);
command.ExecuteNonQuery();
}
}
/// <summary>Refreshes last_edited_at for a known workspace; registers it if the row is absent.</summary>
public void TouchLastEdited(string path)
{
lock (_gate)
{
using var command = _connection.CreateCommand();
command.CommandText = "UPDATE workspaces SET last_edited_at = $now WHERE path = $path;";
command.Parameters.AddWithValue("$path", path);
command.Parameters.AddWithValue("$now", _unixNow());
if (command.ExecuteNonQuery() == 0)
{
// Self-healing path: a workspace opened before registration still gets a row.
UpsertWorkspace(path);
}
}
}
/// <summary>Forgets a workspace entry; the .ykanban folder itself is untouched.</summary>
public void RemoveWorkspace(string path)
{
lock (_gate)
{
using var command = _connection.CreateCommand();
command.CommandText = "DELETE FROM workspaces WHERE path = $path;";
command.Parameters.AddWithValue("$path", path);
command.ExecuteNonQuery();
}
}
/// <summary>Closes the underlying connection.</summary>
public void Dispose() => _connection.Dispose();
}
+3 -7
View File
@@ -1,11 +1,7 @@
namespace YKanBan.Storage; namespace YKanBan.Storage;
/// <summary> /// <summary>A single incremental schema step applied when the stored user_version is one below <see cref="Version"/>.</summary>
/// A single incremental schema step. Migrations form a contiguous list /// <param name="Version">Target user_version after applying this migration (contiguous, starting at 1).</param>
/// starting at version 1; each step is applied when the stored
/// <c>user_version</c> is exactly one below <see cref="Version"/>.
/// </summary>
/// <param name="Version">Target <c>user_version</c> after this migration is applied.</param>
/// <param name="Name">Short human-readable identifier used for diagnostics.</param> /// <param name="Name">Short human-readable identifier used for diagnostics.</param>
/// <param name="Sql">SQL script executed atomically together with the version bump.</param> /// <param name="Sql">SQL script executed inside one transaction together with the user_version bump.</param>
public sealed record SchemaMigration(int Version, string Name, string Sql); public sealed record SchemaMigration(int Version, string Name, string Sql);
+28 -168
View File
@@ -3,41 +3,29 @@ using Microsoft.Data.Sqlite;
namespace YKanBan.Storage; namespace YKanBan.Storage;
/// <summary> /// <summary>
/// Shared SQLite plumbing for workspace databases: opens a connection with /// Shared SQLite plumbing for both the per-workspace databases and the
/// the mandated PRAGMA configuration (WAL journal, NORMAL synchronous mode, /// global app.db: opens connections with the mandated PRAGMA configuration
/// foreign keys on), registers the custom SQL functions and applies /// (WAL journal, NORMAL synchronous mode, foreign keys on) and applies
/// incremental <c>user_version</c> migrations. /// incremental user_version migrations.
/// </summary> /// </summary>
public static class SqliteDatabase public static class SqliteDatabase
{ {
/// <summary> /// <summary>Opens (creating if needed) a database file, applies PRAGMAs and pending migrations.</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>
/// Opens (creating if needed) a database file, applies the mandatory
/// PRAGMAs and runs any pending migrations.
/// </summary>
/// <param name="databasePath">Path of the SQLite database file.</param> /// <param name="databasePath">Path of the SQLite database file.</param>
/// <param name="migrations">Contiguous migration list ordered by version, starting at 1.</param> /// <param name="migrations">Contiguous migration list, ordered by version starting at 1.</param>
/// <returns>An open connection with all PRAGMAs applied and the schema migrated.</returns> /// <returns>An open connection with all PRAGMAs applied and the schema migrated.</returns>
public static SqliteConnection Open(string databasePath, IReadOnlyList<SchemaMigration> migrations) public static SqliteConnection Open(string databasePath, IReadOnlyList<SchemaMigration> migrations)
{ {
SqliteConnection connection = OpenConnection(databasePath); var connection = new SqliteConnection(new SqliteConnectionStringBuilder
{
DataSource = databasePath,
Mode = SqliteOpenMode.ReadWriteCreate,
Pooling = false,
}.ToString());
connection.Open();
try try
{ {
ApplyPragmas(connection); ApplyPragmas(connection);
RegisterFunctions(connection);
ApplyMigrations(connection, migrations); ApplyMigrations(connection, migrations);
return connection; return connection;
} }
@@ -48,79 +36,7 @@ public static class SqliteDatabase
} }
} }
/// <summary> /// <summary>Reads the stored PRAGMA user_version value.</summary>
/// Creates a new database file with the mandatory PRAGMAs, then applies
/// every migration and the optional seed in one transaction, so the file
/// ends up either fully built and seeded or still at version 0.
/// </summary>
/// <param name="databasePath">Path of the SQLite database file; it must not exist yet.</param>
/// <param name="migrations">Contiguous migration list ordered by version, starting at 1.</param>
/// <param name="seed">Initial content written in the same transaction, when any.</param>
/// <returns>An open connection with all PRAGMAs applied and the schema migrated.</returns>
/// <exception cref="ArgumentException">The migration list is not contiguous from version 1.</exception>
/// <exception cref="InvalidOperationException">The database file already exists.</exception>
public static SqliteConnection Create(
string databasePath,
IReadOnlyList<SchemaMigration> migrations,
Action<SqliteConnection, SqliteTransaction>? seed = null)
{
ValidateMigrations(migrations);
if (File.Exists(databasePath))
{
throw new InvalidOperationException($"The database already exists: {databasePath}");
}
SqliteConnection connection = OpenConnection(databasePath);
try
{
ApplyPragmas(connection);
RegisterFunctions(connection);
using var transaction = connection.BeginTransaction();
foreach (SchemaMigration migration in migrations)
{
Execute(connection, migration.Sql, transaction);
Execute(connection, $"PRAGMA user_version={migration.Version};", transaction);
}
seed?.Invoke(connection, transaction);
transaction.Commit();
return connection;
}
catch
{
connection.Dispose();
// Leave no empty version-0 file behind that a later open would migrate into an empty board.
DeleteDatabaseFilesBestEffort(databasePath);
throw;
}
}
/// <summary>
/// Deletes a database file together with its WAL and shared-memory files,
/// ignoring failures.
/// </summary>
/// <param name="databasePath">Path of the SQLite database file.</param>
private static void DeleteDatabaseFilesBestEffort(string databasePath)
{
foreach (string path in new[] { databasePath, databasePath + "-wal", databasePath + "-shm", databasePath + "-journal" })
{
try
{
File.Delete(path);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// Best effort: the original failure is what gets reported.
}
}
}
/// <summary>
/// Reads the stored <c>PRAGMA user_version</c> value.
/// </summary>
/// <param name="connection">An open database connection.</param>
/// <returns>The stored schema version.</returns>
public static long ReadUserVersion(SqliteConnection connection) public static long ReadUserVersion(SqliteConnection connection)
{ {
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
@@ -128,43 +44,29 @@ public static class SqliteDatabase
return (long)command.ExecuteScalar()!; return (long)command.ExecuteScalar()!;
} }
/// <summary> /// <summary>Applies per-connection PRAGMAs. WAL itself is a persistent database property.</summary>
/// Applies the per-connection PRAGMAs. WAL is a persistent database
/// property, but the statement is harmless to repeat; foreign keys must be
/// enabled on every connection or the DDL cascades never fire.
/// </summary>
/// <param name="connection">An open database connection.</param>
internal static void ApplyPragmas(SqliteConnection connection) internal static void ApplyPragmas(SqliteConnection connection)
{ {
// WAL plus NORMAL synchronous is the chosen durability/performance trade-off. // WAL plus NORMAL synchronous is the chosen durability/performance trade-off;
// foreign_keys must be enabled on every connection or DDL-level cascades never fire.
Execute(connection, "PRAGMA journal_mode=WAL;"); Execute(connection, "PRAGMA journal_mode=WAL;");
Execute(connection, "PRAGMA synchronous=NORMAL;"); Execute(connection, "PRAGMA synchronous=NORMAL;");
Execute(connection, "PRAGMA foreign_keys=ON;"); Execute(connection, "PRAGMA foreign_keys=ON;");
} }
/// <summary> /// <summary>Runs every migration newer than the stored user_version, each in its own transaction.</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>
/// Runs every migration newer than the stored <c>user_version</c>, each in
/// its own transaction together with its version bump.
/// </summary>
/// <param name="connection">An open database connection.</param>
/// <param name="migrations">Contiguous migration list ordered by version, starting at 1.</param>
/// <exception cref="ArgumentException">The migration list is not contiguous from version 1.</exception>
/// <exception cref="SchemaVersionException">The database was written by a newer build.</exception> /// <exception cref="SchemaVersionException">The database was written by a newer build.</exception>
/// <exception cref="ArgumentException">The migration list is not contiguous from version 1.</exception>
internal static void ApplyMigrations(SqliteConnection connection, IReadOnlyList<SchemaMigration> migrations) internal static void ApplyMigrations(SqliteConnection connection, IReadOnlyList<SchemaMigration> migrations)
{ {
ValidateMigrations(migrations); // Contract check: the list must be contiguous and ordered, starting at version 1.
for (int index = 0; index < migrations.Count; index++)
{
if (migrations[index].Version != index + 1)
{
throw new ArgumentException("Migrations must be contiguous and start at version 1.", nameof(migrations));
}
}
long current = ReadUserVersion(connection); long current = ReadUserVersion(connection);
int latest = migrations.Count; int latest = migrations.Count;
@@ -182,7 +84,6 @@ public static class SqliteDatabase
{ {
continue; continue;
} }
using var transaction = connection.BeginTransaction(); using var transaction = connection.BeginTransaction();
Execute(connection, migration.Sql, transaction); Execute(connection, migration.Sql, transaction);
Execute(connection, $"PRAGMA user_version={migration.Version};", transaction); Execute(connection, $"PRAGMA user_version={migration.Version};", transaction);
@@ -190,48 +91,7 @@ public static class SqliteDatabase
} }
} }
/// <summary> /// <summary>Executes a non-query SQL script, optionally inside an explicit transaction.</summary>
/// Opens a connection to the file, creating it if needed, without any configuration.
/// </summary>
/// <param name="databasePath">Path of the SQLite database file.</param>
/// <returns>The open connection.</returns>
private static SqliteConnection OpenConnection(string databasePath)
{
var connection = new SqliteConnection(new SqliteConnectionStringBuilder
{
DataSource = databasePath,
Mode = SqliteOpenMode.ReadWriteCreate,
// Each process holds its own single connection; a pool would only add noise.
Pooling = false,
}.ToString());
connection.Open();
return connection;
}
/// <summary>
/// Checks that the migration list is ordered, contiguous and starts at version 1.
/// </summary>
/// <param name="migrations">The migration list.</param>
/// <exception cref="ArgumentException">The list breaks the contract.</exception>
private static void ValidateMigrations(IReadOnlyList<SchemaMigration> migrations)
{
for (int index = 0; index < migrations.Count; index++)
{
if (migrations[index].Version != index + 1)
{
throw new ArgumentException("Migrations must be contiguous and start at version 1.", nameof(migrations));
}
}
}
/// <summary>
/// Executes a non-query SQL script, optionally inside an explicit transaction.
/// </summary>
/// <param name="connection">An open database connection.</param>
/// <param name="commandText">The SQL script to execute.</param>
/// <param name="transaction">The transaction to enlist in, when any.</param>
private static void Execute(SqliteConnection connection, string commandText, SqliteTransaction? transaction = null) private static void Execute(SqliteConnection connection, string commandText, SqliteTransaction? transaction = null)
{ {
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
+19 -155
View File
@@ -1,37 +1,26 @@
namespace YKanBan.Storage; namespace YKanBan.Storage;
/// <summary> /// <summary>
/// Base class for the typed exceptions raised by the storage layer. /// Typed exceptions thrown by the YKanBan storage and application layers.
/// Exception messages are always English and never localized; the UI maps the /// Exception messages are always English and never localized; the UI maps
/// exception type to a localized resource key instead. /// exception types to localized resource keys instead.
/// </summary> /// </summary>
public abstract class YKanBanException : Exception public abstract class YKanBanException : Exception
{ {
/// <summary> /// <summary>Creates an exception with an English diagnostic message.</summary>
/// Initializes the exception with an English diagnostic message.
/// </summary>
/// <param name="message">The English diagnostic message.</param>
/// <param name="innerException">The underlying cause, when any.</param>
protected YKanBanException(string message, Exception? innerException = null) protected YKanBanException(string message, Exception? innerException = null)
: base(message, innerException) : base(message, innerException)
{ {
} }
} }
/// <summary> /// <summary>Signals that the workspace folder does not exist on disk.</summary>
/// Signals that the folder passed on the command line does not exist on disk.
/// </summary>
public sealed class WorkspaceDirectoryMissingException : YKanBanException public sealed class WorkspaceDirectoryMissingException : YKanBanException
{ {
/// <summary> /// <summary>The folder path that was expected to exist.</summary>
/// Gets the folder path that was expected to exist.
/// </summary>
public string FolderPath { get; } public string FolderPath { get; }
/// <summary> /// <summary>Creates an exception for a folder that is absent on disk.</summary>
/// Initializes the exception for a folder that is absent on disk.
/// </summary>
/// <param name="folderPath">The missing folder path.</param>
public WorkspaceDirectoryMissingException(string folderPath) public WorkspaceDirectoryMissingException(string folderPath)
: base($"The folder does not exist: {folderPath}") : base($"The folder does not exist: {folderPath}")
{ {
@@ -39,21 +28,13 @@ public sealed class WorkspaceDirectoryMissingException : YKanBanException
} }
} }
/// <summary> /// <summary>Signals that the folder has no .ykanban structure yet.</summary>
/// Signals that a folder exists but has no .ykanban structure, so it is not
/// (yet) a workspace.
/// </summary>
public sealed class WorkspaceNotInitializedException : YKanBanException public sealed class WorkspaceNotInitializedException : YKanBanException
{ {
/// <summary> /// <summary>The folder path that lacks the .ykanban structure.</summary>
/// Gets the folder path that lacks the .ykanban structure.
/// </summary>
public string FolderPath { get; } public string FolderPath { get; }
/// <summary> /// <summary>Creates an exception for a folder without .ykanban.</summary>
/// Initializes the exception for a folder without a .ykanban structure.
/// </summary>
/// <param name="folderPath">The uninitialized folder path.</param>
public WorkspaceNotInitializedException(string folderPath) public WorkspaceNotInitializedException(string folderPath)
: base($"The folder is not a YKanBan workspace (missing .ykanban): {folderPath}") : base($"The folder is not a YKanBan workspace (missing .ykanban): {folderPath}")
{ {
@@ -61,51 +42,16 @@ public sealed class WorkspaceNotInitializedException : YKanBanException
} }
} }
/// <summary> /// <summary>Signals that another instance holds the workspace lock.</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>
/// Signals that another instance already holds the workspace lock, so this
/// process must not touch the workspace.
/// </summary>
public sealed class WorkspaceLockException : YKanBanException public sealed class WorkspaceLockException : YKanBanException
{ {
/// <summary> /// <summary>The lock file that could not be acquired.</summary>
/// Gets the lock file that could not be acquired.
/// </summary>
public string LockFilePath { get; } public string LockFilePath { get; }
/// <summary> /// <summary>Best-effort diagnostics (PID/machine/time) read from the lock file, if readable.</summary>
/// Gets the best-effort holder diagnostics read from the lock file, or
/// <see langword="null"/> when they could not be read.
/// </summary>
public string? HolderDiagnostics { get; } public string? HolderDiagnostics { get; }
/// <summary> /// <summary>Creates an exception for a failed lock acquisition.</summary>
/// Initializes the exception for a failed lock acquisition.
/// </summary>
/// <param name="lockFilePath">The lock file that is already held.</param>
/// <param name="holderDiagnostics">Diagnostics of the current holder, when readable.</param>
/// <param name="innerException">The underlying I/O error.</param>
public WorkspaceLockException(string lockFilePath, string? holderDiagnostics, Exception innerException) public WorkspaceLockException(string lockFilePath, string? holderDiagnostics, Exception innerException)
: base(BuildMessage(lockFilePath, holderDiagnostics), innerException) : base(BuildMessage(lockFilePath, holderDiagnostics), innerException)
{ {
@@ -113,12 +59,7 @@ public sealed class WorkspaceLockException : YKanBanException
HolderDiagnostics = holderDiagnostics; HolderDiagnostics = holderDiagnostics;
} }
/// <summary> /// <summary>Composes the message, including holder details when they were readable.</summary>
/// Composes the diagnostic message, appending holder details when they were readable.
/// </summary>
/// <param name="lockFilePath">The lock file that is already held.</param>
/// <param name="holderDiagnostics">Diagnostics of the current holder, when readable.</param>
/// <returns>The English diagnostic message.</returns>
private static string BuildMessage(string lockFilePath, string? holderDiagnostics) private static string BuildMessage(string lockFilePath, string? holderDiagnostics)
{ {
string message = $"The workspace is locked by another instance: {lockFilePath}"; string message = $"The workspace is locked by another instance: {lockFilePath}";
@@ -130,27 +71,16 @@ public sealed class WorkspaceLockException : YKanBanException
} }
} }
/// <summary> /// <summary>Signals that the stored schema version is not manageable by this build.</summary>
/// Signals that the database was written by a newer build than the one
/// currently running, so its schema cannot be safely managed.
/// </summary>
public sealed class SchemaVersionException : YKanBanException public sealed class SchemaVersionException : YKanBanException
{ {
/// <summary> /// <summary>The user_version value found in the database.</summary>
/// Gets the user_version value found in the database.
/// </summary>
public long StoredVersion { get; } public long StoredVersion { get; }
/// <summary> /// <summary>The latest schema version this build understands.</summary>
/// Gets the newest schema version this build understands.
/// </summary>
public int SupportedVersion { get; } public int SupportedVersion { get; }
/// <summary> /// <summary>Creates an exception for an unmanageable schema version.</summary>
/// Initializes the exception for an unmanageable schema version.
/// </summary>
/// <param name="storedVersion">The user_version read from the database.</param>
/// <param name="supportedVersion">The newest schema version this build supports.</param>
public SchemaVersionException(long storedVersion, int supportedVersion) public SchemaVersionException(long storedVersion, int supportedVersion)
: base($"Database schema version {storedVersion} is newer than the latest supported version {supportedVersion}.") : base($"Database schema version {storedVersion} is newer than the latest supported version {supportedVersion}.")
{ {
@@ -158,69 +88,3 @@ public sealed class SchemaVersionException : YKanBanException
SupportedVersion = supportedVersion; SupportedVersion = supportedVersion;
} }
} }
/// <summary>
/// The entities whose name/title is constrained by the schema to be non-empty
/// and table-unique.
/// </summary>
public enum NamedEntity
{
/// <summary>A board column (constraint on columns.title).</summary>
Column,
/// <summary>A tag (constraint on tags.name).</summary>
Tag,
}
/// <summary>
/// Signals that a column title or tag name was empty, violating the schema's
/// CHECK constraint. Nothing was written.
/// </summary>
public sealed class NameRequiredException : YKanBanException
{
/// <summary>
/// Gets the entity whose name was empty.
/// </summary>
public NamedEntity Entity { get; }
/// <summary>
/// Initializes the exception for an empty name.
/// </summary>
/// <param name="entity">The entity whose name was empty.</param>
/// <param name="innerException">The underlying constraint violation.</param>
public NameRequiredException(NamedEntity entity, Exception innerException)
: base($"The {entity.ToString().ToLowerInvariant()} name must not be empty.", innerException)
{
Entity = entity;
}
}
/// <summary>
/// Signals that a column title or tag name already exists (compared with ASCII
/// case folding), violating the schema's UNIQUE constraint. Nothing was written.
/// </summary>
public sealed class DuplicateNameException : YKanBanException
{
/// <summary>
/// Gets the entity whose name collided.
/// </summary>
public NamedEntity Entity { get; }
/// <summary>
/// Gets the rejected name.
/// </summary>
public string Name { get; }
/// <summary>
/// Initializes the exception for a name collision.
/// </summary>
/// <param name="entity">The entity whose name collided.</param>
/// <param name="name">The rejected name.</param>
/// <param name="innerException">The underlying constraint violation.</param>
public DuplicateNameException(NamedEntity entity, string name, Exception innerException)
: base($"A {entity.ToString().ToLowerInvariant()} named '{name}' already exists.", innerException)
{
Entity = entity;
Name = name;
}
}
+2 -7
View File
@@ -1,13 +1,8 @@
namespace YKanBan.Storage; namespace YKanBan.Storage;
/// <summary> /// <summary>Provides the current Unix time; all persisted timestamps are INTEGER Unix seconds.</summary>
/// Supplies the current Unix timestamp. Every timestamp persisted by YKanBan
/// is an INTEGER count of Unix seconds.
/// </summary>
public static class UnixTime public static class UnixTime
{ {
/// <summary> /// <summary>Current UTC time as Unix seconds.</summary>
/// Gets the current UTC time expressed as Unix seconds.
/// </summary>
public static long Now => DateTimeOffset.UtcNow.ToUnixTimeSeconds(); public static long Now => DateTimeOffset.UtcNow.ToUnixTimeSeconds();
} }
@@ -0,0 +1,183 @@
using YKanBan.Platform;
using YKanBan.Storage.AppData;
namespace YKanBan.Storage.Workspace;
/// <summary>
/// Fixed-capacity LRU pool of open workspace sessions (exclusive lock plus
/// repository per workspace). Opening a workspace also registers it in the
/// global app.db sidebar registry. Eviction — by capacity or explicitly —
/// only releases resources: the sidebar entry survives, and the workspace
/// can be reopened at any time (a lock held elsewhere then surfaces as a
/// lock conflict).
/// </summary>
public sealed class WorkspaceConnectionPool : IDisposable
{
private readonly object _gate = new();
private readonly int _capacity;
private readonly AppDatabase _appDatabase;
private readonly PathComparer _pathComparer;
private readonly Dictionary<string, LinkedListNode<WorkspaceSession>> _sessions;
private readonly LinkedList<WorkspaceSession> _recency = new();
/// <summary>Creates a pool.</summary>
/// <param name="capacity">Maximum number of simultaneously open workspaces.</param>
/// <param name="appDatabase">Global registry for sidebar entries and last_edited_at.</param>
/// <param name="pathComparer">Platform path rules used to identify workspaces.</param>
public WorkspaceConnectionPool(int capacity, AppDatabase appDatabase, PathComparer pathComparer)
{
ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1);
_capacity = capacity;
_appDatabase = appDatabase;
_pathComparer = pathComparer;
_sessions = new Dictionary<string, LinkedListNode<WorkspaceSession>>(pathComparer);
}
/// <summary>Number of currently open workspaces.</summary>
public int OpenCount
{
get
{
lock (_gate)
{
return _sessions.Count;
}
}
}
/// <summary>Returns the open session and marks it most recently used, or null when the workspace is not open.</summary>
public WorkspaceSession? Find(string folderPath)
{
lock (_gate)
{
if (_sessions.TryGetValue(_pathComparer.Normalize(folderPath), out LinkedListNode<WorkspaceSession>? node))
{
Promote(node);
return node.Value;
}
return null;
}
}
/// <summary>Records user activity (click/switch) for an open workspace; no-op when it is not open.</summary>
public void Touch(string folderPath) => Find(folderPath);
/// <summary>Opens the workspace session, or returns the existing one; evicts LRU entries beyond capacity.</summary>
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist.</exception>
/// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban.</exception>
/// <exception cref="WorkspaceLockException">Another instance holds the lock.</exception>
public WorkspaceSession Open(string folderPath)
{
string canonical = _pathComparer.Normalize(folderPath);
// Fast path: already open → promote and return.
lock (_gate)
{
if (_sessions.TryGetValue(canonical, out LinkedListNode<WorkspaceSession>? open))
{
Promote(open);
return open.Value;
}
}
// Validate the folder state up front so callers get precise state errors.
if (!Directory.Exists(canonical))
{
throw new WorkspaceDirectoryMissingException(canonical);
}
if (!WorkspaceInitializer.IsWorkspace(canonical))
{
throw new WorkspaceNotInitializedException(canonical);
}
// Acquire the exclusive lock before touching the database.
WorkspaceLock workspaceLock = WorkspaceLock.Acquire(canonical);
WorkspaceSession session;
try
{
var repository = new WorkspaceRepository(canonical, _appDatabase);
session = new WorkspaceSession
{
FolderPath = canonical,
Lock = workspaceLock,
Repository = repository,
};
}
catch
{
workspaceLock.Dispose();
throw;
}
lock (_gate)
{
// Re-check: another open may have won the race; the existing session wins.
if (_sessions.TryGetValue(canonical, out LinkedListNode<WorkspaceSession>? winner))
{
session.Dispose();
Promote(winner);
return winner.Value;
}
_sessions.Add(canonical, _recency.AddFirst(session));
// Evict least recently used entries beyond capacity; releases resources only.
while (_sessions.Count > _capacity)
{
LinkedListNode<WorkspaceSession> lru = _recency.Last!;
_recency.RemoveLast();
_sessions.Remove(lru.Value.FolderPath);
lru.Value.Dispose();
}
// Opening registers the workspace in the persistent sidebar registry.
_appDatabase.UpsertWorkspace(canonical);
return session;
}
}
/// <summary>Releases a workspace's resources; the sidebar entry is kept. Returns true when it was open.</summary>
public bool Close(string folderPath)
{
lock (_gate)
{
if (!_sessions.Remove(_pathComparer.Normalize(folderPath), out LinkedListNode<WorkspaceSession>? node))
{
return false;
}
_recency.Remove(node);
node.Value.Dispose();
return true;
}
}
/// <summary>Releases the workspace's resources and removes its sidebar entry. Returns true when it was open.</summary>
public bool Remove(string folderPath)
{
string canonical = _pathComparer.Normalize(folderPath);
bool wasOpen = Close(canonical);
_appDatabase.RemoveWorkspace(canonical);
return wasOpen;
}
/// <summary>Releases all sessions.</summary>
public void Dispose()
{
lock (_gate)
{
foreach (WorkspaceSession session in _recency)
{
session.Dispose();
}
_recency.Clear();
_sessions.Clear();
}
}
/// <summary>Moves a session node to the most-recently-used position.</summary>
private void Promote(LinkedListNode<WorkspaceSession> node)
{
_recency.Remove(node);
_recency.AddFirst(node);
}
}
@@ -3,66 +3,33 @@ using Microsoft.Data.Sqlite;
namespace YKanBan.Storage.Workspace; namespace YKanBan.Storage.Workspace;
/// <summary> /// <summary>
/// Creates the .ykanban structure for a folder in the mandated order: the /// Creates the .ykanban structure for a folder: the folder itself and an
/// .ykanban folder, then the exclusive lock, then the database. The database /// empty, fully migrated database. Seeding preset content is a separate
/// schema and the optional preset content are written in one transaction, so a /// concern handled by <see cref="WorkspacePreset"/>.
/// failure never leaves a half-built database behind.
/// </summary> /// </summary>
public static class WorkspaceInitializer public static class WorkspaceInitializer
{ {
/// <summary> /// <summary>Returns true when the folder contains a .ykanban structure (no parent lookup).</summary>
/// Returns whether the folder contains a .ykanban structure. Only the
/// passed folder is checked; parent folders are never searched.
/// </summary>
/// <param name="folderPath">The folder to inspect.</param>
/// <returns><see langword="true"/> when .ykanban exists in the folder.</returns>
public static bool IsWorkspace(string folderPath) => Directory.Exists(WorkspacePaths.Root(folderPath)); public static bool IsWorkspace(string folderPath) => Directory.Exists(WorkspacePaths.Root(folderPath));
/// <summary> /// <summary>Initializes a fresh workspace: creates .ykanban and an empty migrated database.</summary>
/// Initializes a fresh workspace without any preset content and releases
/// the lock again.
/// </summary>
/// <param name="folderPath">The existing folder to initialize.</param>
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception> /// <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> /// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
public static void Initialize(string folderPath) public static void Initialize(string folderPath)
{
using WorkspaceLock workspaceLock = InitializeLocked(folderPath, addPresetColumns: false);
}
/// <summary>
/// Initializes a fresh workspace and returns the lock still held, so the
/// caller can open the workspace without ever releasing it.
/// </summary>
/// <param name="folderPath">The existing folder to initialize.</param>
/// <param name="addPresetColumns">Whether to add the preset columns in the schema transaction.</param>
/// <returns>The held workspace lock.</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>
internal static WorkspaceLock InitializeLocked(string folderPath, bool addPresetColumns)
{ {
if (!Directory.Exists(folderPath)) if (!Directory.Exists(folderPath))
{ {
throw new WorkspaceDirectoryMissingException(folderPath); throw new WorkspaceDirectoryMissingException(folderPath);
} }
// .ykanban first: the lock file lives inside it. string databasePath = WorkspacePaths.Database(folderPath);
if (File.Exists(databasePath))
{
throw new InvalidOperationException($"The workspace database already exists: {databasePath}");
}
// Create the .ykanban folder and the migrated, still empty database.
Directory.CreateDirectory(WorkspacePaths.Root(folderPath)); Directory.CreateDirectory(WorkspacePaths.Root(folderPath));
WorkspaceLock workspaceLock = WorkspaceLock.Acquire(folderPath); using SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations);
try
{
using SqliteConnection connection = SqliteDatabase.Create(
WorkspacePaths.Database(folderPath),
WorkspaceSchema.Migrations,
addPresetColumns ? WorkspacePreset.AddPresetColumns : null);
return workspaceLock;
}
catch
{
workspaceLock.Dispose();
throw;
}
} }
} }
+10 -29
View File
@@ -3,44 +3,34 @@ using System.Text;
namespace YKanBan.Storage.Workspace; namespace YKanBan.Storage.Workspace;
/// <summary> /// <summary>
/// Exclusive, OS-enforced lock over a workspace's ykanban.lock. The handle is /// Exclusive, OS-enforced lock over a workspace's ykanban.lock. The handle
/// held until disposal, so crashes and power loss release it automatically. /// is held until disposal; crashes and power loss release it automatically.
/// The lock file also carries PID / machine name / time for human diagnostics. /// The lock file carries PID / machine name / time for human diagnostics
/// only.
/// </summary> /// </summary>
public sealed class WorkspaceLock : IDisposable public sealed class WorkspaceLock : IDisposable
{ {
private readonly FileStream _stream; private readonly FileStream _stream;
/// <summary>
/// Initializes the lock around an already-acquired handle.
/// </summary>
/// <param name="stream">The exclusively opened lock file stream.</param>
/// <param name="lockFilePath">Path of the lock file being held.</param>
private WorkspaceLock(FileStream stream, string lockFilePath) private WorkspaceLock(FileStream stream, string lockFilePath)
{ {
_stream = stream; _stream = stream;
LockFilePath = lockFilePath; LockFilePath = lockFilePath;
} }
/// <summary> /// <summary>Path of the lock file being held.</summary>
/// Gets the path of the lock file being held.
/// </summary>
public string LockFilePath { get; } public string LockFilePath { get; }
/// <summary> /// <summary>Acquires the workspace lock or throws <see cref="WorkspaceLockException"/>.</summary>
/// Acquires the workspace lock, writing this process's diagnostics into it.
/// </summary>
/// <param name="folderPath">The workspace folder to lock.</param>
/// <returns>The held lock; dispose it to release.</returns>
/// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception> /// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
/// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception> /// <exception cref="WorkspaceLockException">Another instance holds the lock.</exception>
public static WorkspaceLock Acquire(string folderPath) public static WorkspaceLock Acquire(string folderPath)
{ {
string lockFilePath = WorkspacePaths.LockFile(folderPath); string lockFilePath = WorkspacePaths.LockFile(folderPath);
FileStream stream; FileStream stream;
try try
{ {
// FileShare.None gives the exclusive semantics; FileMode.Create truncates stale content. // FileShare.None gives the exclusive semantics; FileMode.Create truncates any stale content.
stream = new FileStream(lockFilePath, FileMode.Create, FileAccess.Write, FileShare.None); stream = new FileStream(lockFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
} }
catch (DirectoryNotFoundException) catch (DirectoryNotFoundException)
@@ -60,13 +50,7 @@ public sealed class WorkspaceLock : IDisposable
return new WorkspaceLock(stream, lockFilePath); return new WorkspaceLock(stream, lockFilePath);
} }
/// <summary> /// <summary>Attempts to read holder diagnostics from a lock file we failed to acquire.</summary>
/// Attempts to read holder diagnostics from a lock file we failed to
/// acquire. The read is best-effort: a live FileShare.None holder makes the
/// file unreadable, in which case <see langword="null"/> is returned.
/// </summary>
/// <param name="lockFilePath">The lock file to read.</param>
/// <returns>The diagnostics text, or <see langword="null"/> when unreadable.</returns>
private static string? ReadDiagnosticsBestEffort(string lockFilePath) private static string? ReadDiagnosticsBestEffort(string lockFilePath)
{ {
try try
@@ -83,9 +67,6 @@ public sealed class WorkspaceLock : IDisposable
} }
} }
/// <summary> /// <summary>Releases the exclusive handle. The lock file itself is intentionally left on disk.</summary>
/// Releases the exclusive handle. The lock file itself is intentionally
/// left on disk; the OS releases the handle even on a crash.
/// </summary>
public void Dispose() => _stream.Dispose(); public void Dispose() => _stream.Dispose();
} }
+9 -30
View File
@@ -1,44 +1,23 @@
namespace YKanBan.Storage.Workspace; namespace YKanBan.Storage.Workspace;
/// <summary> /// <summary>Well-known file and folder names inside a workspace's .ykanban structure.</summary>
/// Well-known file and folder names inside a workspace's .ykanban structure,
/// plus helpers that combine them with a workspace folder path.
/// </summary>
public static class WorkspacePaths public static class WorkspacePaths
{ {
/// <summary> /// <summary>Name of the workspace root folder created inside a managed project.</summary>
/// Name of the workspace root folder created inside a managed project.
/// </summary>
public const string RootFolderName = ".ykanban"; public const string RootFolderName = ".ykanban";
/// <summary> /// <summary>Name of the SQLite database inside .ykanban.</summary>
/// Name of the SQLite database inside .ykanban.
/// </summary>
public const string DatabaseFileName = "ykanban.db"; public const string DatabaseFileName = "ykanban.db";
/// <summary> /// <summary>Name of the exclusive lock file inside .ykanban.</summary>
/// Name of the exclusive lock file inside .ykanban.
/// </summary>
public const string LockFileName = "ykanban.lock"; public const string LockFileName = "ykanban.lock";
/// <summary> /// <summary>Returns the .ykanban root path for a workspace folder.</summary>
/// Returns the .ykanban root path for a workspace folder.
/// </summary>
/// <param name="folderPath">The workspace folder path.</param>
/// <returns>The path of the .ykanban folder.</returns>
public static string Root(string folderPath) => Path.Combine(folderPath, RootFolderName); public static string Root(string folderPath) => Path.Combine(folderPath, RootFolderName);
/// <summary> /// <summary>Returns the workspace database path for a workspace folder.</summary>
/// Returns the workspace database path for a workspace folder. public static string Database(string folderPath) => Path.Combine(folderPath, RootFolderName, DatabaseFileName);
/// </summary>
/// <param name="folderPath">The workspace folder path.</param>
/// <returns>The path of ykanban.db.</returns>
public static string Database(string folderPath) => Path.Combine(Root(folderPath), DatabaseFileName);
/// <summary> /// <summary>Returns the workspace lock file path for a workspace folder.</summary>
/// Returns the workspace lock file path for a workspace folder. public static string LockFile(string folderPath) => Path.Combine(folderPath, RootFolderName, LockFileName);
/// </summary>
/// <param name="folderPath">The workspace folder path.</param>
/// <returns>The path of ykanban.lock.</returns>
public static string LockFile(string folderPath) => Path.Combine(Root(folderPath), LockFileName);
} }
+11 -11
View File
@@ -3,23 +3,20 @@ using Microsoft.Data.Sqlite;
namespace YKanBan.Storage.Workspace; namespace YKanBan.Storage.Workspace;
/// <summary> /// <summary>
/// Adds the initial workspace content. The three preset column titles are read /// Seeds initial workspace content. The three preset column titles are read
/// straight from the ResX resources in the UI language active when they are /// straight from the ResX resources in the UI language active at seeding
/// added; they then become ordinary data that no longer follows language /// time, then stored as ordinary data that no longer follows language
/// switches. /// switches.
/// </summary> /// </summary>
public static class WorkspacePreset public static class WorkspacePreset
{ {
/// <summary> /// <summary>Inserts the three preset columns (To Do / In Progress / Done equivalents).</summary>
/// Inserts the three preset columns (the current language's equivalents of
/// To Do / In Progress / Done) inside the caller's transaction, so the
/// presets land together with the schema or not at all.
/// </summary>
/// <param name="connection">The connection to the freshly created database.</param>
/// <param name="transaction">The transaction that also builds the schema.</param>
/// <exception cref="SqliteException">A title collides with an existing column.</exception> /// <exception cref="SqliteException">A title collides with an existing column.</exception>
public static void AddPresetColumns(SqliteConnection connection, SqliteTransaction transaction) public static void SeedColumns(string folderPath)
{ {
using SqliteConnection connection = SqliteDatabase.Open(
WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
long now = UnixTime.Now; long now = UnixTime.Now;
// Preset titles are data at creation time: whatever the current language says gets stored. // Preset titles are data at creation time: whatever the current language says gets stored.
@@ -30,6 +27,8 @@ public static class WorkspacePreset
Resources.PresetColumn_Done, Resources.PresetColumn_Done,
]; ];
// Insert all three in one transaction so a half-seeded workspace can never exist.
using var transaction = connection.BeginTransaction();
foreach (string title in titles) foreach (string title in titles)
{ {
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
@@ -42,5 +41,6 @@ public static class WorkspacePreset
command.Parameters.AddWithValue("$now", now); command.Parameters.AddWithValue("$now", now);
command.ExecuteNonQuery(); command.ExecuteNonQuery();
} }
transaction.Commit();
} }
} }
+94 -251
View File
@@ -1,12 +1,14 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Models; using YKanBan.Models;
using YKanBan.Search; using YKanBan.Storage.AppData;
namespace YKanBan.Storage.Workspace; namespace YKanBan.Storage.Workspace;
/// <summary> /// <summary>
/// Data access for one open workspace database: CRUD for columns, cards and /// Data access for one open workspace database: CRUD for columns, cards and
/// tags, card moves and tag assignment. Cascading deletes are left to the DDL. /// tags, card moves and tag assignment, plus the write-through that
/// refreshes the workspace's last_edited_at in the global app.db after
/// every successful data write.
/// ///
/// Timestamp rules: /// Timestamp rules:
/// - cards.updated_at refreshes only when a card edit is confirmed with /// - cards.updated_at refreshes only when a card edit is confirmed with
@@ -16,28 +18,26 @@ namespace YKanBan.Storage.Workspace;
/// </summary> /// </summary>
public sealed class WorkspaceRepository : IDisposable public sealed class WorkspaceRepository : IDisposable
{ {
private readonly string _folderPath;
private readonly AppDatabase _appDatabase;
private readonly SqliteConnection _connection; private readonly SqliteConnection _connection;
/// <summary> /// <summary>Opens the repository over an initialized workspace database.</summary>
/// Opens the repository over an initialized workspace database. /// <param name="folderPath">Workspace folder; the exact value is used as the app.db registry key.</param>
/// </summary> /// <param name="appDatabase">Global registry refreshed after every successful write.</param>
/// <param name="folderPath">The workspace folder.</param> public WorkspaceRepository(string folderPath, AppDatabase appDatabase)
public WorkspaceRepository(string folderPath)
{ {
_folderPath = folderPath;
_appDatabase = appDatabase;
_connection = SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations); _connection = SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
} }
/// <summary> /// <summary>Closes the underlying connection.</summary>
/// Closes the underlying connection.
/// </summary>
public void Dispose() => _connection.Dispose(); public void Dispose() => _connection.Dispose();
#region Columns #region Columns
/// <summary> /// <summary>Returns all columns ordered by id.</summary>
/// Returns all columns ordered by id ascending.
/// </summary>
/// <returns>All columns in id order.</returns>
public IReadOnlyList<ColumnModel> GetColumns() public IReadOnlyList<ColumnModel> GetColumns()
{ {
using var command = CreateCommand( using var command = CreateCommand(
@@ -52,11 +52,7 @@ public sealed class WorkspaceRepository : IDisposable
return columns; return columns;
} }
/// <summary> /// <summary>Returns the column with the given id, or null.</summary>
/// Returns the column with the given id.
/// </summary>
/// <param name="columnId">The column id.</param>
/// <returns>The column, or <see langword="null"/> when it does not exist.</returns>
public ColumnModel? GetColumn(long columnId) public ColumnModel? GetColumn(long columnId)
{ {
using var command = CreateCommand( using var command = CreateCommand(
@@ -66,43 +62,30 @@ public sealed class WorkspaceRepository : IDisposable
return reader.Read() ? ReadColumn(reader) : null; return reader.Read() ? ReadColumn(reader) : null;
} }
/// <summary> /// <summary>Creates a column with created_at = updated_at.</summary>
/// Creates a column with created_at equal to updated_at. /// <exception cref="SqliteException">The title is empty or not unique.</exception>
/// </summary>
/// <param name="title">The non-empty, table-unique title.</param>
/// <param name="description">The optional description.</param>
/// <returns>The created column.</returns>
/// <exception cref="NameRequiredException">The title is empty.</exception>
/// <exception cref="DuplicateNameException">The title is not unique.</exception>
public ColumnModel AddColumn(string title, string description) public ColumnModel AddColumn(string title, string description)
{ {
long now = UnixTime.Now; long now = UnixTime.Now;
using var transaction = _connection.BeginTransaction(); using var transaction = _connection.BeginTransaction();
long id = MapNameConstraint(NamedEntity.Column, title, () => ExecuteInsert(transaction, long id = ExecuteInsert(transaction,
"INSERT INTO columns (title, description, created_at, updated_at) VALUES ($title, $description, $now, $now);", "INSERT INTO columns (title, description, created_at, updated_at) VALUES ($title, $description, $now, $now);",
("$title", title), ("$description", description), ("$now", now))); ("$title", title), ("$description", description), ("$now", now));
transaction.Commit(); transaction.Commit();
TouchEdited();
return new ColumnModel(id, title, description, now, now); return new ColumnModel(id, title, description, now, now);
} }
/// <summary> /// <summary>Rewrites title and description; a no-change call writes nothing.</summary>
/// Rewrites the title and description. A call with no effective change
/// writes nothing and leaves the timestamp alone.
/// </summary>
/// <param name="columnId">The column to update.</param>
/// <param name="title">The new non-empty, table-unique title.</param>
/// <param name="description">The new description.</param>
/// <returns>The updated column, or the unchanged one for a no-op.</returns>
/// <exception cref="InvalidOperationException">The column does not exist.</exception> /// <exception cref="InvalidOperationException">The column does not exist.</exception>
/// <exception cref="NameRequiredException">The new title is empty.</exception> /// <exception cref="SqliteException">The new title is empty or not unique.</exception>
/// <exception cref="DuplicateNameException">The new title is not unique.</exception>
public ColumnModel UpdateColumn(long columnId, string title, string description) public ColumnModel UpdateColumn(long columnId, string title, string description)
{ {
ColumnModel existing = GetColumn(columnId) ColumnModel existing = GetColumn(columnId)
?? throw new InvalidOperationException($"Column {columnId} does not exist."); ?? throw new InvalidOperationException($"Column {columnId} does not exist.");
// Unchanged title and description: no write, no timestamp refresh. // Unchanged title and description: no write, no timestamps.
if (existing.Title == title && existing.Description == description) if (existing.Title == title && existing.Description == description)
{ {
return existing; return existing;
@@ -115,57 +98,33 @@ public sealed class WorkspaceRepository : IDisposable
command.Parameters.AddWithValue("$description", description); command.Parameters.AddWithValue("$description", description);
command.Parameters.AddWithValue("$now", now); command.Parameters.AddWithValue("$now", now);
command.Parameters.AddWithValue("$id", columnId); command.Parameters.AddWithValue("$id", columnId);
MapNameConstraint(NamedEntity.Column, title, command.ExecuteNonQuery); command.ExecuteNonQuery();
TouchEdited();
return new ColumnModel(columnId, title, description, existing.CreatedAt, now); return new ColumnModel(columnId, title, description, existing.CreatedAt, now);
} }
/// <summary> /// <summary>Deletes a column; the DDL cascade removes its cards and their tag links. Returns true when a row was deleted.</summary>
/// Deletes a column; the DDL cascade removes its cards and their tag links.
/// </summary>
/// <param name="columnId">The column to delete.</param>
/// <returns><see langword="true"/> when a row was deleted.</returns>
public bool DeleteColumn(long columnId) => ExecuteDelete("DELETE FROM columns WHERE id = $id;", columnId); public bool DeleteColumn(long columnId) => ExecuteDelete("DELETE FROM columns WHERE id = $id;", columnId);
#endregion #endregion
#region Cards #region Cards
/// <summary> /// <summary>Returns all cards with their tags loaded, ordered by id.</summary>
/// Returns all cards with their assigned tags loaded, ordered by id ascending. public IReadOnlyList<CardModel> GetCards()
/// </summary>
/// <returns>All cards in id order.</returns>
public IReadOnlyList<CardModel> GetCards() => GetCards(null);
/// <summary>
/// Returns the cards matching a compiled search, with all of their assigned
/// tags loaded (the filter selects cards, it never trims their tag lists),
/// ordered by id ascending.
/// </summary>
/// <param name="filter">The compiled search, or <see langword="null"/> for every card.</param>
/// <returns>The matching cards in id order.</returns>
public IReadOnlyList<CardModel> GetCards(CompiledSearch? filter)
{ {
string where = filter is null ? "" : $"WHERE {filter.Predicate}"; using var command = CreateCommand("""
using var command = CreateCommand($"""
SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at, SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at,
t.id, t.name, t.color, t.description t.id, t.name, t.color, t.description
FROM cards c FROM cards c
LEFT JOIN card_tags ct ON ct.card_id = c.id LEFT JOIN card_tags ct ON ct.card_id = c.id
LEFT JOIN tags t ON t.id = ct.tag_id LEFT JOIN tags t ON t.id = ct.tag_id
{where} ORDER BY c.id ASC;
ORDER BY c.id ASC, t.id ASC;
"""); """);
if (filter is not null)
{
foreach ((string name, object value) in filter.Parameters)
{
command.Parameters.AddWithValue(name, value);
}
}
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
// Single grouped pass: one output card per distinct card id, with its tags accumulated alongside. // Single grouped pass: one output card per distinct card id, its tags accumulated alongside.
var cards = new List<CardModel>(); var cards = new List<CardModel>();
var tagsByCard = new Dictionary<long, List<TagModel>>(); var tagsByCard = new Dictionary<long, List<TagModel>>();
while (reader.Read()) while (reader.Read())
@@ -184,20 +143,15 @@ public sealed class WorkspaceRepository : IDisposable
reader.GetInt64(5), reader.GetInt64(5),
tags)); tags));
} }
if (!reader.IsDBNull(6)) if (!reader.IsDBNull(6))
{ {
tags.Add(ReadTag(reader, 6)); tags.Add(new TagModel(reader.GetInt64(6), reader.GetString(7), RgbColor.Parse(reader.GetString(8)), reader.GetString(9)));
} }
} }
return cards; return cards;
} }
/// <summary> /// <summary>Returns the card with the given id (tags loaded), or null.</summary>
/// Returns the card with the given id, with its tags loaded.
/// </summary>
/// <param name="cardId">The card id.</param>
/// <returns>The card, or <see langword="null"/> when it does not exist.</returns>
public CardModel? GetCard(long cardId) public CardModel? GetCard(long cardId)
{ {
using var command = CreateCommand(""" using var command = CreateCommand("""
@@ -207,17 +161,18 @@ public sealed class WorkspaceRepository : IDisposable
LEFT JOIN card_tags ct ON ct.card_id = c.id LEFT JOIN card_tags ct ON ct.card_id = c.id
LEFT JOIN tags t ON t.id = ct.tag_id LEFT JOIN tags t ON t.id = ct.tag_id
WHERE c.id = $id WHERE c.id = $id
ORDER BY t.id ASC; ORDER BY c.id ASC;
"""); """);
command.Parameters.AddWithValue("$id", cardId); command.Parameters.AddWithValue("$id", cardId);
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
// The LEFT JOIN may repeat the card row once per tag; build it on the first row only.
CardModel? card = null; CardModel? card = null;
var tags = new List<TagModel>(); var tags = new List<TagModel>();
while (reader.Read()) while (reader.Read())
{ {
card ??= new CardModel( if (card is null)
{
card = new CardModel(
reader.GetInt64(0), reader.GetInt64(0),
reader.GetInt64(1), reader.GetInt64(1),
reader.GetString(2), reader.GetString(2),
@@ -225,24 +180,17 @@ public sealed class WorkspaceRepository : IDisposable
reader.GetInt64(4), reader.GetInt64(4),
reader.GetInt64(5), reader.GetInt64(5),
tags); tags);
}
if (!reader.IsDBNull(6)) if (!reader.IsDBNull(6))
{ {
tags.Add(ReadTag(reader, 6)); tags.Add(new TagModel(reader.GetInt64(6), reader.GetString(7), RgbColor.Parse(reader.GetString(8)), reader.GetString(9)));
} }
} }
return card; return card;
} }
/// <summary> /// <summary>Creates a card with its initial tag assignment (created_at = updated_at).</summary>
/// Creates a card with its initial tag assignment and created_at equal to updated_at. /// <exception cref="SqliteException">The column does not exist, or a tag id does not exist.</exception>
/// </summary>
/// <param name="columnId">The owning column.</param>
/// <param name="title">The card title, possibly empty.</param>
/// <param name="content">The card content, possibly empty.</param>
/// <param name="tagIds">The tags to assign initially.</param>
/// <returns>The created card with tags loaded.</returns>
/// <exception cref="SqliteException">The column or a tag id does not exist.</exception>
public CardModel AddCard(long columnId, string title, string content, IReadOnlyCollection<long> tagIds) public CardModel AddCard(long columnId, string title, string content, IReadOnlyCollection<long> tagIds)
{ {
long now = UnixTime.Now; long now = UnixTime.Now;
@@ -258,20 +206,16 @@ public sealed class WorkspaceRepository : IDisposable
} }
transaction.Commit(); transaction.Commit();
TouchEdited();
return new CardModel(id, columnId, title, content, now, now, LoadTags(id)); return new CardModel(id, columnId, title, content, now, now, LoadTags(id));
} }
/// <summary> /// <summary>
/// Applies one card edit confirmation as a single atomic unit: the card row /// Applies one card edit confirmation as a single atomic unit: the card
/// (title, content, refreshed updated_at) plus the complete tag assignment. /// row (title, content, refreshed updated_at) plus the complete tag
/// A confirmation with no effective change writes nothing; a failure /// assignment. A confirmation with no effective change writes nothing;
/// mid-way rolls the whole edit back. /// a failure mid-way rolls the whole edit back.
/// </summary> /// </summary>
/// <param name="cardId">The card to update.</param>
/// <param name="title">The new title.</param>
/// <param name="content">The new content.</param>
/// <param name="tagIds">The complete set of tags to assign.</param>
/// <returns>The updated card with tags loaded, or the unchanged one for a no-op.</returns>
/// <exception cref="InvalidOperationException">The card does not exist.</exception> /// <exception cref="InvalidOperationException">The card does not exist.</exception>
/// <exception cref="SqliteException">A tag id does not exist; nothing is written.</exception> /// <exception cref="SqliteException">A tag id does not exist; nothing is written.</exception>
public CardModel UpdateCard(long cardId, string title, string content, IReadOnlyCollection<long> tagIds) public CardModel UpdateCard(long cardId, string title, string content, IReadOnlyCollection<long> tagIds)
@@ -279,20 +223,19 @@ public sealed class WorkspaceRepository : IDisposable
CardModel existing = GetCard(cardId) CardModel existing = GetCard(cardId)
?? throw new InvalidOperationException($"Card {cardId} does not exist."); ?? throw new InvalidOperationException($"Card {cardId} does not exist.");
// No effective change in title, content or tag set: no write, no timestamp refresh. // No change in title, content or tag set: no write, no timestamps.
bool tagsChanged = !tagIds.Distinct().ToHashSet().SetEquals(existing.Tags.Select(tag => tag.Id)); bool tagsChanged = !tagIds.Distinct().ToHashSet().SetEquals(existing.Tags.Select(tag => tag.Id));
if (existing.Title == title && existing.Content == content && !tagsChanged) if (existing.Title == title && existing.Content == content && !tagsChanged)
{ {
return existing; return existing;
} }
// The confirmed write refreshes updated_at even when only the tag set changed.
long now = UnixTime.Now; long now = UnixTime.Now;
using var transaction = _connection.BeginTransaction(); using var transaction = _connection.BeginTransaction();
// The confirm write refreshes updated_at even when only the tag set changed.
ExecuteNonQuery(transaction, ExecuteNonQuery(transaction,
"UPDATE cards SET title = $title, content = $content, updated_at = $now WHERE id = $id;", "UPDATE cards SET title = $title, content = $content, updated_at = $now WHERE id = $id;",
("$title", title), ("$content", content), ("$now", now), ("$id", cardId)); ("$title", title), ("$content", content), ("$now", now), ("$id", cardId));
// Tag assignment is rewritten wholesale; card_tags carries nothing beyond the pair. // Tag assignment is rewritten wholesale; card_tags carries nothing beyond the pair.
ExecuteNonQuery(transaction, "DELETE FROM card_tags WHERE card_id = $id;", ("$id", cardId)); ExecuteNonQuery(transaction, "DELETE FROM card_tags WHERE card_id = $id;", ("$id", cardId));
foreach (long tagId in tagIds.Distinct()) foreach (long tagId in tagIds.Distinct())
@@ -303,53 +246,38 @@ public sealed class WorkspaceRepository : IDisposable
} }
transaction.Commit(); transaction.Commit();
TouchEdited();
return new CardModel(cardId, existing.ColumnId, title, content, existing.CreatedAt, now, LoadTags(cardId)); return new CardModel(cardId, existing.ColumnId, title, content, existing.CreatedAt, now, LoadTags(cardId));
} }
/// <summary> /// <summary>
/// Moves a card to another column. This writes to the database but /// Moves a card to another column. This is a data write (refreshes the
/// deliberately does NOT refresh the card's updated_at; moving to the /// workspace last_edited_at) but deliberately does NOT refresh the
/// current column is a no-op. /// card's updated_at; moving to the current column is a no-write no-op.
/// Returns true when the card moved.
/// </summary> /// </summary>
/// <param name="cardId">The card to move.</param>
/// <param name="targetColumnId">The destination column.</param>
/// <returns><see langword="true"/> when the card actually moved.</returns>
public bool MoveCard(long cardId, long targetColumnId) public bool MoveCard(long cardId, long targetColumnId)
{ {
using var command = CreateCommand( using var command = CreateCommand(
"UPDATE cards SET column_id = $columnId WHERE id = $id AND column_id <> $columnId;"); "UPDATE cards SET column_id = $columnId WHERE id = $id AND column_id <> $columnId;");
command.Parameters.AddWithValue("$columnId", targetColumnId); command.Parameters.AddWithValue("$columnId", targetColumnId);
command.Parameters.AddWithValue("$id", cardId); command.Parameters.AddWithValue("$id", cardId);
return command.ExecuteNonQuery() > 0; bool moved = command.ExecuteNonQuery() > 0;
} if (moved)
/// <summary>
/// Counts the cards of a column, regardless of any search filter.
/// </summary>
/// <param name="columnId">The column id.</param>
/// <returns>The number of cards in the column.</returns>
public long CountCards(long columnId)
{ {
using var command = CreateCommand("SELECT COUNT(*) FROM cards WHERE column_id = $id;"); TouchEdited();
command.Parameters.AddWithValue("$id", columnId); }
return (long)command.ExecuteScalar()!; return moved;
} }
/// <summary> /// <summary>Deletes a card; the DDL cascade removes its tag links. Returns true when a row was deleted.</summary>
/// Deletes a card; the DDL cascade removes its tag links.
/// </summary>
/// <param name="cardId">The card to delete.</param>
/// <returns><see langword="true"/> when a row was deleted.</returns>
public bool DeleteCard(long cardId) => ExecuteDelete("DELETE FROM cards WHERE id = $id;", cardId); public bool DeleteCard(long cardId) => ExecuteDelete("DELETE FROM cards WHERE id = $id;", cardId);
#endregion #endregion
#region Tags #region Tags
/// <summary> /// <summary>Returns all tags ordered by id; unreferenced tags are included.</summary>
/// Returns all tags ordered by id ascending; unreferenced tags are included.
/// </summary>
/// <returns>All tags in id order.</returns>
public IReadOnlyList<TagModel> GetTags() public IReadOnlyList<TagModel> GetTags()
{ {
using var command = CreateCommand( using var command = CreateCommand(
@@ -359,15 +287,12 @@ public sealed class WorkspaceRepository : IDisposable
var tags = new List<TagModel>(); var tags = new List<TagModel>();
while (reader.Read()) while (reader.Read())
{ {
tags.Add(ReadTag(reader, 0)); tags.Add(ReadTag(reader));
} }
return tags; return tags;
} }
/// <summary> /// <summary>Returns every tag together with the number of cards using it, ordered by id.</summary>
/// Returns every tag together with the number of cards using it, ordered by tag id.
/// </summary>
/// <returns>The tag/usage pairs in tag id order.</returns>
public IReadOnlyList<(TagModel Tag, long UsageCount)> GetTagsWithUsage() public IReadOnlyList<(TagModel Tag, long UsageCount)> GetTagsWithUsage()
{ {
using var command = CreateCommand(""" using var command = CreateCommand("""
@@ -382,42 +307,28 @@ public sealed class WorkspaceRepository : IDisposable
var tags = new List<(TagModel Tag, long UsageCount)>(); var tags = new List<(TagModel Tag, long UsageCount)>();
while (reader.Read()) while (reader.Read())
{ {
tags.Add((ReadTag(reader, 0), reader.GetInt64(4))); tags.Add((ReadTag(reader), reader.GetInt64(4)));
} }
return tags; return tags;
} }
/// <summary> /// <summary>Creates a tag.</summary>
/// Creates a tag. /// <exception cref="SqliteException">The name is empty/not unique.</exception>
/// </summary>
/// <param name="name">The non-empty, table-unique name.</param>
/// <param name="color">The tag color.</param>
/// <param name="description">The optional description.</param>
/// <returns>The created tag.</returns>
/// <exception cref="NameRequiredException">The name is empty.</exception>
/// <exception cref="DuplicateNameException">The name is not unique.</exception>
public TagModel AddTag(string name, RgbColor color, string description) public TagModel AddTag(string name, RgbColor color, string description)
{ {
using var transaction = _connection.BeginTransaction(); using var transaction = _connection.BeginTransaction();
long id = MapNameConstraint(NamedEntity.Tag, name, () => ExecuteInsert(transaction, long id = ExecuteInsert(transaction,
"INSERT INTO tags (name, color, description) VALUES ($name, $color, $description);", "INSERT INTO tags (name, color, description) VALUES ($name, $color, $description);",
("$name", name), ("$color", color.ToString()), ("$description", description))); ("$name", name), ("$color", color.ToString()), ("$description", description));
transaction.Commit(); transaction.Commit();
TouchEdited();
return new TagModel(id, name, color, description); return new TagModel(id, name, color, description);
} }
/// <summary> /// <summary>Rewrites name, color and description; a no-change call writes nothing.</summary>
/// Rewrites name, color and description. A call with no effective change writes nothing.
/// </summary>
/// <param name="tagId">The tag to update.</param>
/// <param name="name">The new non-empty, table-unique name.</param>
/// <param name="color">The new color.</param>
/// <param name="description">The new description.</param>
/// <returns>The updated tag, or the unchanged one for a no-op.</returns>
/// <exception cref="InvalidOperationException">The tag does not exist.</exception> /// <exception cref="InvalidOperationException">The tag does not exist.</exception>
/// <exception cref="NameRequiredException">The new name is empty.</exception> /// <exception cref="SqliteException">The new name is empty/not unique.</exception>
/// <exception cref="DuplicateNameException">The new name is not unique.</exception>
public TagModel UpdateTag(long tagId, string name, RgbColor color, string description) public TagModel UpdateTag(long tagId, string name, RgbColor color, string description)
{ {
TagModel existing = GetTag(tagId) TagModel existing = GetTag(tagId)
@@ -435,75 +346,30 @@ public sealed class WorkspaceRepository : IDisposable
command.Parameters.AddWithValue("$color", color.ToString()); command.Parameters.AddWithValue("$color", color.ToString());
command.Parameters.AddWithValue("$description", description); command.Parameters.AddWithValue("$description", description);
command.Parameters.AddWithValue("$id", tagId); command.Parameters.AddWithValue("$id", tagId);
MapNameConstraint(NamedEntity.Tag, name, command.ExecuteNonQuery); command.ExecuteNonQuery();
TouchEdited();
return new TagModel(tagId, name, color, description); return new TagModel(tagId, name, color, description);
} }
/// <summary> /// <summary>Deletes a tag; the DDL cascade removes its card links while the cards survive. Returns true when a row was deleted.</summary>
/// Deletes a tag; the DDL cascade removes its card links while the cards survive.
/// </summary>
/// <param name="tagId">The tag to delete.</param>
/// <returns><see langword="true"/> when a row was deleted.</returns>
public bool DeleteTag(long tagId) => ExecuteDelete("DELETE FROM tags WHERE id = $id;", tagId); public bool DeleteTag(long tagId) => ExecuteDelete("DELETE FROM tags WHERE id = $id;", tagId);
#endregion #endregion
#region Helpers #region Helpers
/// <summary>SQLite extended result code of a failed CHECK constraint.</summary> /// <summary>Returns the tag with the given id, or null.</summary>
private const int SqliteConstraintCheck = 275;
/// <summary>SQLite extended result code of a failed UNIQUE constraint.</summary>
private const int SqliteConstraintUnique = 2067;
/// <summary>
/// Runs a write against columns.title or tags.name and translates the
/// schema's non-empty (CHECK) and uniqueness (UNIQUE) violations into typed
/// exceptions that the UI maps to localized messages.
/// </summary>
/// <typeparam name="T">The write's result type.</typeparam>
/// <param name="entity">The entity being written.</param>
/// <param name="name">The name or title being written.</param>
/// <param name="write">The write to run.</param>
/// <returns>The write's result.</returns>
/// <exception cref="NameRequiredException">The name is empty.</exception>
/// <exception cref="DuplicateNameException">The name is not unique.</exception>
private static T MapNameConstraint<T>(NamedEntity entity, string name, Func<T> write)
{
try
{
return write();
}
catch (SqliteException exception) when (exception.SqliteExtendedErrorCode == SqliteConstraintCheck)
{
throw new NameRequiredException(entity, exception);
}
catch (SqliteException exception) when (exception.SqliteExtendedErrorCode == SqliteConstraintUnique)
{
throw new DuplicateNameException(entity, name, exception);
}
}
/// <summary>
/// Returns the tag with the given id.
/// </summary>
/// <param name="tagId">The tag id.</param>
/// <returns>The tag, or <see langword="null"/> when it does not exist.</returns>
private TagModel? GetTag(long tagId) private TagModel? GetTag(long tagId)
{ {
using var command = CreateCommand( using var command = CreateCommand(
"SELECT id, name, color, description FROM tags WHERE id = $id;"); "SELECT id, name, color, description FROM tags WHERE id = $id;");
command.Parameters.AddWithValue("$id", tagId); command.Parameters.AddWithValue("$id", tagId);
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
return reader.Read() ? ReadTag(reader, 0) : null; return reader.Read() ? ReadTag(reader) : null;
} }
/// <summary> /// <summary>Returns the tags currently assigned to a card, ordered by id.</summary>
/// Returns the tags currently assigned to a card, ordered by tag id.
/// </summary>
/// <param name="cardId">The card id.</param>
/// <returns>The assigned tags in id order.</returns>
private IReadOnlyList<TagModel> LoadTags(long cardId) private IReadOnlyList<TagModel> LoadTags(long cardId)
{ {
using var command = CreateCommand(""" using var command = CreateCommand("""
@@ -519,35 +385,20 @@ public sealed class WorkspaceRepository : IDisposable
var tags = new List<TagModel>(); var tags = new List<TagModel>();
while (reader.Read()) while (reader.Read())
{ {
tags.Add(ReadTag(reader, 0)); tags.Add(ReadTag(reader));
} }
return tags; return tags;
} }
/// <summary> /// <summary>Reads a columns row from the reader cursor.</summary>
/// Reads a columns row from the reader cursor.
/// </summary>
/// <param name="reader">The reader positioned on a columns row.</param>
/// <returns>The column model.</returns>
private static ColumnModel ReadColumn(SqliteDataReader reader) => private static ColumnModel ReadColumn(SqliteDataReader reader) =>
new(reader.GetInt64(0), reader.GetString(1), reader.GetString(2), reader.GetInt64(3), reader.GetInt64(4)); new(reader.GetInt64(0), reader.GetString(1), reader.GetString(2), reader.GetInt64(3), reader.GetInt64(4));
/// <summary> /// <summary>Reads a tags row from the reader cursor; color text converts to components.</summary>
/// Reads a tags row from the reader cursor, starting at the given column private static TagModel ReadTag(SqliteDataReader reader) =>
/// offset; the color text is converted to its components. new(reader.GetInt64(0), reader.GetString(1), RgbColor.Parse(reader.GetString(2)), reader.GetString(3));
/// </summary>
/// <param name="reader">The reader positioned on a row containing a tag.</param>
/// <param name="offset">Index of the tag's id column.</param>
/// <returns>The tag model.</returns>
private static TagModel ReadTag(SqliteDataReader reader, int offset) =>
new(reader.GetInt64(offset), reader.GetString(offset + 1), RgbColor.Parse(reader.GetString(offset + 2)), reader.GetString(offset + 3));
/// <summary> /// <summary>Creates a command bound to this connection.</summary>
/// Creates a command bound to this connection.
/// </summary>
/// <param name="sql">The command text.</param>
/// <param name="transaction">The transaction to enlist in, when any.</param>
/// <returns>The prepared command.</returns>
private SqliteCommand CreateCommand(string sql, SqliteTransaction? transaction = null) private SqliteCommand CreateCommand(string sql, SqliteTransaction? transaction = null)
{ {
SqliteCommand command = _connection.CreateCommand(); SqliteCommand command = _connection.CreateCommand();
@@ -556,12 +407,7 @@ public sealed class WorkspaceRepository : IDisposable
return command; return command;
} }
/// <summary> /// <summary>Executes a parameterized non-query statement inside a transaction.</summary>
/// Executes a parameterized non-query statement inside a transaction.
/// </summary>
/// <param name="transaction">The transaction to enlist in.</param>
/// <param name="sql">The statement to execute.</param>
/// <param name="parameters">Name/value pairs bound as SQL parameters.</param>
private void ExecuteNonQuery(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters) private void ExecuteNonQuery(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters)
{ {
using SqliteCommand command = CreateCommand(sql, transaction); using SqliteCommand command = CreateCommand(sql, transaction);
@@ -572,13 +418,7 @@ public sealed class WorkspaceRepository : IDisposable
command.ExecuteNonQuery(); command.ExecuteNonQuery();
} }
/// <summary> /// <summary>Inserts a row inside a transaction and returns the generated rowid.</summary>
/// Inserts a row inside a transaction and returns the generated rowid.
/// </summary>
/// <param name="transaction">The transaction to enlist in.</param>
/// <param name="sql">The INSERT statement.</param>
/// <param name="parameters">Name/value pairs bound as SQL parameters.</param>
/// <returns>The rowid assigned to the inserted row.</returns>
private long ExecuteInsert(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters) private long ExecuteInsert(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters)
{ {
ExecuteNonQuery(transaction, sql, parameters); ExecuteNonQuery(transaction, sql, parameters);
@@ -586,18 +426,21 @@ public sealed class WorkspaceRepository : IDisposable
return (long)rowId.ExecuteScalar()!; return (long)rowId.ExecuteScalar()!;
} }
/// <summary> /// <summary>Deletes by id; refreshes last_edited_at only when a row was actually removed.</summary>
/// Deletes a row by id.
/// </summary>
/// <param name="sql">The DELETE statement with an <c>$id</c> parameter.</param>
/// <param name="id">The id to delete.</param>
/// <returns><see langword="true"/> when a row was deleted.</returns>
private bool ExecuteDelete(string sql, long id) private bool ExecuteDelete(string sql, long id)
{ {
using SqliteCommand command = CreateCommand(sql); using SqliteCommand command = CreateCommand(sql);
command.Parameters.AddWithValue("$id", id); command.Parameters.AddWithValue("$id", id);
return command.ExecuteNonQuery() > 0; if (command.ExecuteNonQuery() == 0)
{
return false;
} }
TouchEdited();
return true;
}
/// <summary>Mirrors a successful data write into the global registry.</summary>
private void TouchEdited() => _appDatabase.TouchLastEdited(_folderPath);
#endregion #endregion
} }
+15 -26
View File
@@ -1,37 +1,27 @@
namespace YKanBan.Storage.Workspace; namespace YKanBan.Storage.Workspace;
/// <summary> /// <summary>
/// Schema definitions for the per-workspace database. A workspace holds a /// Schema definitions for the per-workspace database. The board is a single
/// single board with a columns → cards hierarchy plus tags and their /// board with a columns → cards hierarchy. All data validation is expressed
/// assignments. Data validity is expressed in DDL (CHECK / UNIQUE / FOREIGN /// in DDL (CHECK / UNIQUE / FOREIGN KEY) so that any row entering the
/// KEY) so every stored row is valid by construction, and cascading deletes /// database is valid by construction; cascading deletes are covered by the
/// are covered by the same DDL. /// same DDL.
///
/// Title and name uniqueness is NOCASE (ASCII case folding) while the columns
/// themselves keep the default BINARY collation, so ordering by title stays
/// code-point based. Until the first release the v1 script may be edited in
/// place; after it, every schema change must be appended as a new migration.
/// </summary> /// </summary>
public static class WorkspaceSchema public static class WorkspaceSchema
{ {
/// <summary> /// <summary>Latest workspace schema version this build understands.</summary>
/// Newest workspace schema version this build understands.
/// </summary>
public const int CurrentVersion = 1; public const int CurrentVersion = 1;
/// <summary> /// <summary>Ordered, contiguous migration list for the workspace database.</summary>
/// Ordered, contiguous migration list for the workspace database. public static readonly IReadOnlyList<SchemaMigration> Migrations = new SchemaMigration[]
/// </summary> {
public static readonly IReadOnlyList<SchemaMigration> Migrations = new SchemaMigration(1, "initial schema", """
[
new SchemaMigration(CurrentVersion, "initial schema", """
CREATE TABLE columns ( CREATE TABLE columns (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL CHECK (length(title) > 0), title TEXT NOT NULL UNIQUE CHECK (length(title) > 0),
description TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL, created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL, updated_at INTEGER NOT NULL
UNIQUE (title COLLATE NOCASE)
); );
CREATE TABLE cards ( CREATE TABLE cards (
@@ -45,10 +35,9 @@ public static class WorkspaceSchema
CREATE TABLE tags ( CREATE TABLE tags (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL CHECK (length(name) > 0), name TEXT NOT NULL UNIQUE CHECK (length(name) > 0),
color TEXT NOT NULL CHECK (color GLOB '#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]'), color TEXT NOT NULL CHECK (color GLOB '#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]'),
description TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT ''
UNIQUE (name COLLATE NOCASE)
); );
CREATE TABLE card_tags ( CREATE TABLE card_tags (
@@ -57,5 +46,5 @@ public static class WorkspaceSchema
PRIMARY KEY (card_id, tag_id) PRIMARY KEY (card_id, tag_id)
); );
"""), """),
]; };
} }
+9 -89
View File
@@ -1,101 +1,21 @@
namespace YKanBan.Storage.Workspace; namespace YKanBan.Storage.Workspace;
/// <summary> /// <summary>One open workspace: the exclusive lock plus its repository.</summary>
/// One open workspace for the process lifetime: the exclusive lock plus the
/// single repository connection. Opening acquires the lock first, so a folder
/// without .ykanban, or one already locked by another instance, fails before
/// any database work happens. Disposing releases the repository and then the
/// lock.
/// </summary>
public sealed class WorkspaceSession : IDisposable public sealed class WorkspaceSession : IDisposable
{ {
private readonly WorkspaceLock _workspaceLock; /// <summary>Canonical workspace folder path.</summary>
public required string FolderPath { get; init; }
/// <summary> /// <summary>The exclusive lock held while this session is open.</summary>
/// Initializes the session around an acquired lock and an open repository. public required WorkspaceLock Lock { get; init; }
/// </summary>
/// <param name="folderPath">The canonical workspace folder path.</param>
/// <param name="workspaceLock">The exclusive lock held while this session is open.</param>
/// <param name="repository">The data access object for this workspace.</param>
private WorkspaceSession(string folderPath, WorkspaceLock workspaceLock, WorkspaceRepository repository)
{
FolderPath = folderPath;
_workspaceLock = workspaceLock;
Repository = repository;
}
/// <summary> /// <summary>The data access object for this workspace.</summary>
/// Gets the canonical workspace folder path. public required WorkspaceRepository Repository { get; init; }
/// </summary>
public string FolderPath { get; }
/// <summary> /// <summary>Disposes the repository, then releases the lock.</summary>
/// Gets the data access object for this workspace.
/// </summary>
public WorkspaceRepository Repository { get; }
/// <summary>
/// Opens a workspace: acquires its exclusive lock and opens its repository.
/// </summary>
/// <param name="folderPath">The workspace folder to open.</param>
/// <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="WorkspaceLockException">Another instance already holds the lock.</exception>
/// <exception cref="WorkspaceDatabaseMissingException">.ykanban exists but its database file does not.</exception>
public static WorkspaceSession Open(string 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 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) =>
OpenLocked(folderPath, WorkspaceInitializer.InitializeLocked(folderPath, addPresetColumns: true));
/// <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
{
var repository = new WorkspaceRepository(folderPath);
return new WorkspaceSession(folderPath, workspaceLock, repository);
}
catch
{
workspaceLock.Dispose();
throw;
}
}
/// <summary>
/// Releases the repository connection, then the exclusive lock.
/// </summary>
public void Dispose() public void Dispose()
{ {
Repository.Dispose(); Repository.Dispose();
_workspaceLock.Dispose(); Lock.Dispose();
} }
} }
-31
View File
@@ -1,31 +0,0 @@
using System;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using YKanBan.ViewModels;
namespace YKanBan;
public class ViewLocator : IDataTemplate
{
public Control? Build(object? param)
{
if (param is null)
return null;
var name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
var type = Type.GetType(name);
if (type != null)
{
return (Control)Activator.CreateInstance(type)!;
}
return new TextBlock { Text = "Not Found: " + name };
}
public bool Match(object? data)
{
return data is ViewModelBase;
}
}
-338
View File
@@ -1,338 +0,0 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
using YKanBan.Search;
using YKanBan.Storage.AppData;
using YKanBan.Storage.Workspace;
using YKanBan.ViewModels.Dialogs;
namespace YKanBan.ViewModels.Board;
/// <summary>
/// The board tab: the toolbar (search bar, new column, column width, card sort)
/// and the columns laid out left to right, each listing its cards top to bottom.
///
/// The search runs only on an explicit search (button or Enter), never while
/// typing. An invalid expression is reported in a message dialog and changes
/// nothing: the box keeps its text and the board keeps the previous result.
///
/// Every write is followed by <see cref="Refresh"/>, which re-queries with the
/// most recently successful search expression (<see cref="ActiveFilter"/>), not
/// with whatever the search box currently holds: cards that no longer match
/// disappear, new cards that do not match are not shown, and empty columns stay.
/// </summary>
public sealed partial class BoardViewModel : ViewModelBase
{
private readonly WorkspaceRepository _repository;
private readonly AppConfig _config;
private readonly IDialogService _dialogs;
/// <summary>
/// Initializes the board and loads it.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="config">The live application configuration (sort, column width, confirmations).</param>
/// <param name="dialogs">The modal dialog service.</param>
public BoardViewModel(WorkspaceRepository repository, AppConfig config, IDialogService dialogs)
{
_repository = repository;
_config = config;
_dialogs = dialogs;
SortOptions =
[
new OptionItem(CardSortOption.Id, Resources.Sort_Id),
new OptionItem(CardSortOption.UpdatedAt, Resources.Sort_UpdatedAt),
new OptionItem(CardSortOption.Title, Resources.Sort_Title),
];
selectedSort = SortOptions.FirstOrDefault(option => (CardSortOption)option.Value == config.Sort.Card)
?? SortOptions[0];
columnWidth = ColumnWidths.Resolve(config.ColumnWidth);
Refresh();
}
/// <summary>
/// Raised after every board write (the refresh included), so the tags tab
/// can update its usage counts.
/// </summary>
public event EventHandler? DataWritten;
/// <summary>
/// Gets the columns in id order.
/// </summary>
public ObservableCollection<ColumnViewModel> Columns { get; } = [];
/// <summary>
/// Gets the card sort options shown in the combobox.
/// </summary>
public IReadOnlyList<OptionItem> SortOptions { get; }
/// <summary>
/// Gets the column models in id order, as of the last refresh.
/// </summary>
public IReadOnlyList<ColumnModel> ColumnModels { get; private set; } = [];
/// <summary>
/// Gets or sets the most recently successful search; <see langword="null"/> shows every card.
/// </summary>
public CompiledSearch? ActiveFilter { get; set; }
/// <summary>
/// Gets or sets the search box text; it only takes effect on <see cref="SearchCommand"/>.
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasSearchText))]
private string searchText = "";
/// <summary>
/// Gets whether the search box holds text (shows the clear button).
/// </summary>
public bool HasSearchText => SearchText.Length > 0;
/// <summary>
/// Gets or sets the selected card sort option; changing it is persisted and re-sorts the board.
/// </summary>
[ObservableProperty]
private OptionItem selectedSort;
/// <summary>
/// Gets the effective column width in pixels.
/// </summary>
[ObservableProperty]
private int columnWidth;
/// <summary>
/// Reloads the columns and the cards matching <see cref="ActiveFilter"/>.
/// </summary>
public void Refresh()
{
IReadOnlyList<ColumnModel> columns = _repository.GetColumns();
ILookup<long, CardModel> cardsByColumn = _repository.GetCards(ActiveFilter).ToLookup(card => card.ColumnId);
var sort = (CardSortOption)SelectedSort.Value;
ColumnModels = columns;
Columns.Clear();
foreach (ColumnModel column in columns)
{
Columns.Add(new ColumnViewModel(this, column, CardOrdering.Sort(cardsByColumn[column.Id], sort)));
}
}
/// <summary>
/// Parses and runs the search box text; blank text shows every card. An
/// invalid expression only shows the error dialog.
/// </summary>
/// <returns>A task completing after the refresh or the error dialog.</returns>
[RelayCommand]
private async Task SearchAsync()
{
CompiledSearch? filter;
try
{
SearchNode? query = SearchQueryParser.Parse(SearchText);
filter = query is null ? null : SearchSqlCompiler.Compile(query);
}
catch (SearchSyntaxException exception)
{
await _dialogs.ShowMessageAsync(
Resources.Search_Error_Title,
string.Format(Resources.Culture, Resources.Search_Error_Message, exception.Message));
return;
}
ActiveFilter = filter;
Refresh();
}
/// <summary>
/// Empties the search box and shows every card again.
/// </summary>
[RelayCommand]
private void ClearSearch()
{
SearchText = "";
ActiveFilter = null;
Refresh();
}
/// <summary>
/// Opens the new-column dialog.
/// </summary>
/// <returns>A task completing when the dialog closes.</returns>
[RelayCommand]
private async Task AddColumnAsync()
{
var dialog = new ColumnEditorDialogViewModel(null, (title, description) => _repository.AddColumn(title, description));
if (await _dialogs.ShowAsync(dialog))
{
RefreshAfterWrite();
}
}
/// <summary>
/// Opens the column width dialog and applies the choice.
/// </summary>
/// <returns>A task completing when the dialog closes.</returns>
[RelayCommand]
private async Task AdjustColumnWidthAsync()
{
if (await _dialogs.ShowAsync(new ColumnWidthDialogViewModel(_config.ColumnWidth)))
{
ColumnWidth = ColumnWidths.Resolve(_config.ColumnWidth);
}
}
/// <summary>
/// Opens the edit-column dialog.
/// </summary>
/// <param name="column">The column to edit.</param>
/// <returns>A task completing when the dialog closes.</returns>
internal async Task EditColumnAsync(ColumnModel column)
{
var dialog = new ColumnEditorDialogViewModel(
column, (title, description) => _repository.UpdateColumn(column.Id, title, description));
if (await _dialogs.ShowAsync(dialog))
{
RefreshAfterWrite();
}
}
/// <summary>
/// Deletes a column with its cards, asking first when that confirmation is enabled.
/// </summary>
/// <param name="column">The column to delete.</param>
/// <returns>A task completing when the column is deleted or the deletion was declined.</returns>
internal async Task DeleteColumnAsync(ColumnModel column)
{
await RunWriteAsync(async () =>
{
if (_config.Confirmations.DeleteColumn)
{
long count = _repository.CountCards(column.Id);
string message = string.Format(Resources.Culture, Resources.Confirm_DeleteColumn, column.Title, count);
if (!await _dialogs.ConfirmAsync(message, Resources.Common_Delete))
{
return false;
}
}
_repository.DeleteColumn(column.Id);
return true;
});
}
/// <summary>
/// Opens the card editor for a new card in a column.
/// </summary>
/// <param name="columnId">The column receiving the card.</param>
/// <returns>A task completing when the editor closes.</returns>
internal async Task AddCardAsync(long columnId)
{
var editor = CardEditorDialogViewModel.ForNewCard(
_repository, _dialogs, columnId, _config.Confirmations.DiscardEdit);
await _dialogs.ShowAsync(editor);
// Refresh even after a cancel: the nested picker may have created tags.
RefreshAfterWrite();
}
/// <summary>
/// Opens the card editor for an existing card, reloaded from the database.
/// </summary>
/// <param name="cardId">The card to edit.</param>
/// <returns>A task completing when the editor closes.</returns>
internal async Task EditCardAsync(long cardId)
{
CardModel? card = _repository.GetCard(cardId);
if (card is null)
{
Refresh();
return;
}
var editor = CardEditorDialogViewModel.ForExistingCard(
_repository, _dialogs, card, _config.Confirmations.DiscardEdit);
await _dialogs.ShowAsync(editor);
RefreshAfterWrite();
}
/// <summary>
/// Deletes a card, asking first when that confirmation is enabled.
/// </summary>
/// <param name="card">The card to delete.</param>
/// <returns>A task completing when the card is deleted or the deletion was declined.</returns>
internal async Task DeleteCardAsync(CardModel card)
{
await RunWriteAsync(async () =>
{
if (_config.Confirmations.DeleteCard)
{
string message = string.Format(Resources.Culture, Resources.Confirm_DeleteCard, CardViewModel.FormatHeader(card));
if (!await _dialogs.ConfirmAsync(message, Resources.Common_Delete))
{
return false;
}
}
_repository.DeleteCard(card.Id);
return true;
});
}
/// <summary>
/// Moves a card to another column.
/// </summary>
/// <param name="cardId">The card to move.</param>
/// <param name="columnId">The target column.</param>
/// <returns>A task completing when the card is moved.</returns>
internal Task MoveCardAsync(long cardId, long columnId) =>
RunWriteAsync(() =>
{
_repository.MoveCard(cardId, columnId);
return Task.FromResult(true);
});
/// <summary>
/// Runs an immediate write and refreshes after it; an unexpected failure is
/// reported in a message dialog and the board is refreshed to the stored state.
/// </summary>
/// <param name="write">The write; returns <see langword="false"/> when the user declined it.</param>
/// <returns>A task completing after the refresh.</returns>
private async Task RunWriteAsync(Func<Task<bool>> write)
{
try
{
if (!await write())
{
return;
}
}
catch (Exception exception)
{
Debug.WriteLine(exception);
await _dialogs.ShowMessageAsync(
Resources.Error_Operation_Title, Resources.Error_Operation_Message, exception.Message);
}
RefreshAfterWrite();
}
/// <summary>
/// Refreshes after a write and announces it.
/// </summary>
private void RefreshAfterWrite()
{
Refresh();
DataWritten?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Persists the sort option and re-sorts the board.
/// </summary>
/// <param name="value">The new sort option.</param>
partial void OnSelectedSortChanged(OptionItem value)
{
_config.Sort.Card = (CardSortOption)value.Value;
Refresh();
}
}
-141
View File
@@ -1,141 +0,0 @@
using System.Globalization;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
namespace YKanBan.ViewModels.Board;
/// <summary>
/// One card in a column list: "#id" in bold on the same line as the title, the
/// content cut to a fixed length, and the tag badges below. No timestamps.
/// Clicking the card opens the editor; its menu deletes or moves it.
/// </summary>
public sealed partial class CardViewModel : ViewModelBase
{
/// <summary>
/// The number of text elements of content shown on the card.
/// </summary>
public const int ExcerptLength = 200;
private readonly BoardViewModel _board;
/// <summary>
/// Initializes the card.
/// </summary>
/// <param name="board">The owning board.</param>
/// <param name="card">The card shown.</param>
public CardViewModel(BoardViewModel board, CardModel card)
{
_board = board;
Card = card;
IdText = $"#{card.Id.ToString(CultureInfo.InvariantCulture)}";
Excerpt = MakeExcerpt(card.Content);
Tags = card.Tags.Select(tag => new TagBadgeViewModel(tag)).ToList();
}
/// <summary>
/// Gets the card shown.
/// </summary>
public CardModel Card { get; }
/// <summary>
/// Gets the "#id" text.
/// </summary>
public string IdText { get; }
/// <summary>
/// Gets the title; empty when the card has none.
/// </summary>
public string Title => Card.Title;
/// <summary>
/// Gets the title as it follows "#id" on the header line: a space and the
/// title, or nothing when the card has no title.
/// </summary>
public string TitleSuffix => Card.Title.Length == 0 ? "" : " " + Card.Title;
/// <summary>
/// Gets the truncated content.
/// </summary>
public string Excerpt { get; }
/// <summary>
/// Gets whether there is content to show.
/// </summary>
public bool HasExcerpt => Excerpt.Length > 0;
/// <summary>
/// Gets the tag badges.
/// </summary>
public IReadOnlyList<TagBadgeViewModel> Tags { get; }
/// <summary>
/// Gets whether the card has tags.
/// </summary>
public bool HasTags => Tags.Count > 0;
/// <summary>
/// Gets the "move to column" targets; built when the menu asks for them.
/// The card's current column is listed but disabled.
/// </summary>
public IReadOnlyList<MoveTargetViewModel> MoveTargets =>
_board.ColumnModels
.Select(column => new MoveTargetViewModel(column.Title, column.Id != Card.ColumnId, MoveToCommand, column.Id))
.ToList();
/// <summary>
/// Formats the "#id title" header text of a card ("#id" alone without a title).
/// </summary>
/// <param name="card">The card.</param>
/// <returns>The header text.</returns>
public static string FormatHeader(CardModel card) =>
card.Title.Length == 0
? $"#{card.Id.ToString(CultureInfo.InvariantCulture)}"
: $"#{card.Id.ToString(CultureInfo.InvariantCulture)} {card.Title}";
/// <summary>
/// Cuts content to <see cref="ExcerptLength"/> text elements, appending an
/// ellipsis when something was cut. Surrogate pairs and combining sequences
/// are never split.
/// </summary>
/// <param name="content">The card content.</param>
/// <returns>The excerpt.</returns>
public static string MakeExcerpt(string content)
{
string trimmed = content.Trim();
var info = new StringInfo(trimmed);
return info.LengthInTextElements <= ExcerptLength
? trimmed
: info.SubstringByTextElements(0, ExcerptLength).TrimEnd() + "…";
}
/// <summary>
/// Opens the card editor.
/// </summary>
/// <returns>A task completing when the editor closes.</returns>
[RelayCommand]
private Task EditAsync() => _board.EditCardAsync(Card.Id);
/// <summary>
/// Deletes the card.
/// </summary>
/// <returns>A task completing when the card is deleted or the deletion was declined.</returns>
[RelayCommand]
private Task DeleteAsync() => _board.DeleteCardAsync(Card);
/// <summary>
/// Moves the card to another column.
/// </summary>
/// <param name="columnId">The target column.</param>
/// <returns>A task completing when the card is moved.</returns>
[RelayCommand]
private Task MoveToAsync(long columnId) => _board.MoveCardAsync(Card.Id, columnId);
}
/// <summary>
/// An entry of a card's "move to column" submenu.
/// </summary>
/// <param name="Title">The column title.</param>
/// <param name="IsEnabled">Whether the entry can be picked (false for the card's own column).</param>
/// <param name="Command">The move command.</param>
/// <param name="ColumnId">The target column, passed to <paramref name="Command"/>.</param>
public sealed record MoveTargetViewModel(string Title, bool IsEnabled, IAsyncRelayCommand<long> Command, long ColumnId);
@@ -1,77 +0,0 @@
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
namespace YKanBan.ViewModels.Board;
/// <summary>
/// One board column: its header (title, card count, description, the new-card
/// button and the edit/delete menu) and its virtualized card list.
/// </summary>
public sealed partial class ColumnViewModel : ViewModelBase
{
private readonly BoardViewModel _board;
/// <summary>
/// Initializes the column.
/// </summary>
/// <param name="board">The owning board.</param>
/// <param name="column">The column shown.</param>
/// <param name="cards">The column's visible cards, in display order.</param>
public ColumnViewModel(BoardViewModel board, ColumnModel column, IReadOnlyList<CardModel> cards)
{
_board = board;
Column = column;
Cards = cards.Select(card => new CardViewModel(board, card)).ToList();
}
/// <summary>
/// Gets the column shown.
/// </summary>
public ColumnModel Column { get; }
/// <summary>
/// Gets the column title.
/// </summary>
public string Title => Column.Title;
/// <summary>
/// Gets the column description.
/// </summary>
public string Description => Column.Description;
/// <summary>
/// Gets whether the column has a description to show.
/// </summary>
public bool HasDescription => Column.Description.Length > 0;
/// <summary>
/// Gets the number of visible cards.
/// </summary>
public int CardCount => Cards.Count;
/// <summary>
/// Gets the visible cards in display order.
/// </summary>
public IReadOnlyList<CardViewModel> Cards { get; }
/// <summary>
/// Opens the card editor for a new card in this column.
/// </summary>
/// <returns>A task completing when the editor closes.</returns>
[RelayCommand]
private Task AddCardAsync() => _board.AddCardAsync(Column.Id);
/// <summary>
/// Opens the edit-column dialog.
/// </summary>
/// <returns>A task completing when the dialog closes.</returns>
[RelayCommand]
private Task EditAsync() => _board.EditColumnAsync(Column);
/// <summary>
/// Deletes the column with its cards.
/// </summary>
/// <returns>A task completing when the column is deleted or the deletion was declined.</returns>
[RelayCommand]
private Task DeleteAsync() => _board.DeleteColumnAsync(Column);
}
@@ -1,57 +0,0 @@
using Avalonia.Media;
using Avalonia.Media.Immutable;
using YKanBan.Models;
namespace YKanBan.ViewModels.Board;
/// <summary>
/// A colored tag badge (color + name). Tag colors are user data: they are shown
/// as the literal #RRGGBB value in both themes, with a black or white text color
/// chosen for contrast.
/// </summary>
public sealed class TagBadgeViewModel : ViewModelBase
{
/// <summary>
/// Initializes the badge.
/// </summary>
/// <param name="tag">The tag shown.</param>
public TagBadgeViewModel(TagModel tag)
{
Tag = tag;
Background = new ImmutableSolidColorBrush(Color.FromRgb(tag.Color.R, tag.Color.G, tag.Color.B));
Foreground = IsLight(tag.Color) ? Brushes.Black : Brushes.White;
}
/// <summary>
/// Gets the tag shown.
/// </summary>
public TagModel Tag { get; }
/// <summary>
/// Gets the tag name.
/// </summary>
public string Name => Tag.Name;
/// <summary>
/// Gets the tag description.
/// </summary>
public string Description => Tag.Description;
/// <summary>
/// Gets the badge fill: the tag's own color.
/// </summary>
public IBrush Background { get; }
/// <summary>
/// Gets the text color contrasting with <see cref="Background"/>.
/// </summary>
public IBrush Foreground { get; }
/// <summary>
/// Decides whether dark text reads better on a color, by its relative luminance.
/// </summary>
/// <param name="color">The background color.</param>
/// <returns><see langword="true"/> for light colors.</returns>
public static bool IsLight(RgbColor color) =>
(0.299 * color.R) + (0.587 * color.G) + (0.114 * color.B) > 150;
}
@@ -1,39 +1,26 @@
using System.Globalization; using System.Reflection;
namespace YKanBan.ViewModels.Dialogs; namespace YKanBan.ViewModels.Dialogs;
/// <summary> /// <summary>The about dialog data: application identity and version.</summary>
/// The about dialog: application name, version, repository link and license.
/// </summary>
public sealed class AboutDialogViewModel : ViewModelBase public sealed class AboutDialogViewModel : ViewModelBase
{ {
/// <summary> /// <summary>Display name of the application.</summary>
/// Initializes the view model, reading the version from the assembly. public string ApplicationName => Resources.App_Name;
/// </summary>
public AboutDialogViewModel()
{
string version = typeof(AboutDialogViewModel).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
Version = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.About_Version, version);
}
/// <summary> /// <summary>Localized "Version x.y.z" text.</summary>
/// Gets the application name. public string VersionText => string.Format(
/// </summary> System.Globalization.CultureInfo.CurrentCulture,
public string AppName => Resources.App_Name; Resources.About_Version,
AssemblyVersion);
/// <summary> /// <summary>Repository URL (from resources).</summary>
/// Gets the localized version line. public string RepositoryUrl => Resources.About_RepositoryUrl;
/// </summary>
public string Version { get; }
/// <summary> /// <summary>License name (from resources).</summary>
/// Gets the repository URL. public string LicenseValue => Resources.About_LicenseValue;
/// </summary>
public string RepositoryUrl => "https://code.blumia.cn/yyc12345/YKanBan";
/// <summary> /// <summary>The assembly version, formatted as major.minor.patch.</summary>
/// Gets the license name. public static string AssemblyVersion =>
/// </summary> Assembly.GetExecutingAssembly().GetName().Version?.ToString(3) ?? "0.0.0";
public string License => Resources.About_LicenseValue;
} }
@@ -1,228 +0,0 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
using YKanBan.Storage.Workspace;
using YKanBan.ViewModels.Board;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The card editor — one unit of work. Title, content and the tag assignment
/// are edited in memory and written together in a single transaction on
/// confirmation; cancelling writes nothing about the card or its assignment.
/// Confirming an existing card without effective changes writes nothing and
/// keeps its timestamps. The only immediate write is the creation of a new tag
/// in the nested tag picker (see <see cref="TagPickerDialogViewModel"/>).
/// </summary>
public sealed partial class CardEditorDialogViewModel : DialogViewModelBase
{
private readonly WorkspaceRepository _repository;
private readonly IDialogService _dialogs;
private readonly CardModel? _existing;
private readonly long _columnId;
private readonly bool _confirmDiscard;
private readonly string _initialTitle;
private readonly string _initialContent;
private readonly HashSet<long> _initialTagIds;
/// <summary>
/// Initializes the editor for a new card in a column.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="dialogs">The dialog service, for the nested tag picker and the discard confirmation.</param>
/// <param name="columnId">The column receiving the new card.</param>
/// <param name="confirmDiscard">Whether discarding changes asks for confirmation.</param>
/// <returns>The editor.</returns>
public static CardEditorDialogViewModel ForNewCard(
WorkspaceRepository repository, IDialogService dialogs, long columnId, bool confirmDiscard) =>
new(repository, dialogs, null, columnId, confirmDiscard);
/// <summary>
/// Initializes the editor for an existing card.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="dialogs">The dialog service, for the nested tag picker and the discard confirmation.</param>
/// <param name="card">The card to edit.</param>
/// <param name="confirmDiscard">Whether discarding changes asks for confirmation.</param>
/// <returns>The editor.</returns>
public static CardEditorDialogViewModel ForExistingCard(
WorkspaceRepository repository, IDialogService dialogs, CardModel card, bool confirmDiscard) =>
new(repository, dialogs, card, card.ColumnId, confirmDiscard);
private CardEditorDialogViewModel(
WorkspaceRepository repository, IDialogService dialogs, CardModel? existing, long columnId, bool confirmDiscard)
{
_repository = repository;
_dialogs = dialogs;
_existing = existing;
_columnId = columnId;
_confirmDiscard = confirmDiscard;
_initialTitle = existing?.Title ?? "";
_initialContent = existing?.Content ?? "";
_initialTagIds = existing?.Tags.Select(tag => tag.Id).ToHashSet() ?? [];
cardTitle = _initialTitle;
content = _initialContent;
Tags = new ObservableCollection<TagBadgeViewModel>(
existing?.Tags.Select(tag => new TagBadgeViewModel(tag)) ?? []);
if (existing is null)
{
Title = Resources.CardEditor_TitleNew;
}
else
{
CultureInfo? culture = Resources.Culture;
Title = Resources.CardEditor_TitleEdit;
IdText = $"#{existing.Id.ToString(CultureInfo.InvariantCulture)}";
CreatedText = string.Format(culture, Resources.CardEditor_Created, FormatTime(existing.CreatedAt));
ModifiedText = string.Format(culture, Resources.CardEditor_Modified, FormatTime(existing.UpdatedAt));
}
}
/// <summary>
/// Gets the localized window title.
/// </summary>
public string Title { get; }
/// <summary>
/// Gets whether the card already exists (and thus has an id and timestamps to show).
/// </summary>
public bool IsExisting => _existing is not null;
/// <summary>
/// Gets the read-only "#id" text of an existing card.
/// </summary>
public string? IdText { get; }
/// <summary>
/// Gets the read-only creation time line of an existing card.
/// </summary>
public string? CreatedText { get; }
/// <summary>
/// Gets the read-only modification time line of an existing card.
/// </summary>
public string? ModifiedText { get; }
/// <summary>
/// Gets the tags assigned in this edit session, in assignment order.
/// </summary>
public ObservableCollection<TagBadgeViewModel> Tags { get; }
/// <summary>
/// Gets the card written on confirmation; <see langword="null"/> until then.
/// </summary>
public CardModel? SavedCard { get; private set; }
/// <summary>
/// Gets or sets the card title; the empty string means "no title".
/// </summary>
[ObservableProperty]
private string cardTitle;
/// <summary>
/// Gets or sets the multiline card content.
/// </summary>
[ObservableProperty]
private string content;
/// <summary>
/// Gets the localized error of the last confirmation, or <see langword="null"/>.
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasError))]
private string? errorMessage;
/// <summary>
/// Gets whether an error is shown.
/// </summary>
public bool HasError => ErrorMessage is not null;
/// <summary>
/// Gets whether the in-memory state differs from the state the editor opened with.
/// </summary>
public bool IsDirty =>
CardTitle != _initialTitle
|| Content != _initialContent
|| !_initialTagIds.SetEquals(Tags.Select(tag => tag.Tag.Id));
/// <summary>
/// Opens the nested tag picker and assigns the picked (or newly created) tag.
/// </summary>
/// <returns>A task completing when the picker closes.</returns>
[RelayCommand]
private async Task AddTagAsync()
{
var picker = new TagPickerDialogViewModel(_repository, Tags.Select(tag => tag.Tag.Id).ToHashSet());
if (await _dialogs.ShowAsync(picker) && picker.PickedTag is { } picked)
{
Tags.Add(new TagBadgeViewModel(picked));
}
}
/// <summary>
/// Removes a tag from the in-memory assignment.
/// </summary>
/// <param name="tag">The tag to remove.</param>
[RelayCommand]
private void RemoveTag(TagBadgeViewModel tag) => Tags.Remove(tag);
/// <summary>
/// Writes the card in one transaction and closes; an unchanged existing card
/// is not written at all.
/// </summary>
[RelayCommand]
private void Confirm()
{
if (_existing is not null && !IsDirty)
{
SavedCard = _existing;
Close(true);
return;
}
long[] tagIds = Tags.Select(tag => tag.Tag.Id).ToArray();
try
{
SavedCard = _existing is null
? _repository.AddCard(_columnId, CardTitle, Content, tagIds)
: _repository.UpdateCard(_existing.Id, CardTitle, Content, tagIds);
}
catch (Exception exception)
{
ErrorMessage = WriteErrorMessages.Describe(exception);
return;
}
Close(true);
}
/// <summary>
/// Closes without writing the card, asking first when there are unsaved
/// changes and the discard confirmation is enabled.
/// </summary>
[RelayCommand]
private Task CancelAsync() => RequestCancelAsync();
/// <inheritdoc/>
public override async Task RequestCancelAsync()
{
if (_confirmDiscard && IsDirty
&& !await _dialogs.ConfirmAsync(Resources.Confirm_DiscardEdit, Resources.Common_Discard))
{
return;
}
Close(false);
}
/// <summary>
/// Formats a Unix-seconds timestamp in local time with the language's pattern.
/// </summary>
/// <param name="unixSeconds">The timestamp.</param>
/// <returns>The formatted time.</returns>
private static string FormatTime(long unixSeconds) =>
DateTimeOffset.FromUnixTimeSeconds(unixSeconds).ToLocalTime()
.ToString(Resources.Common_TimePattern, Resources.Culture);
}
@@ -1,82 +0,0 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The new-column / edit-column dialog: a required title and an optional
/// description. Confirming writes through the supplied save callback; a
/// schema-constraint violation (empty or duplicate title) is shown inside the
/// dialog, which stays open with the user's input intact.
/// </summary>
public sealed partial class ColumnEditorDialogViewModel : DialogViewModelBase
{
private readonly Action<string, string> _save;
/// <summary>
/// Initializes the dialog.
/// </summary>
/// <param name="existing">The column being edited, or <see langword="null"/> for a new column.</param>
/// <param name="save">Writes the title and description; throws the repository's typed exceptions.</param>
public ColumnEditorDialogViewModel(ColumnModel? existing, Action<string, string> save)
{
_save = save;
Title = existing is null ? Resources.ColumnEditor_TitleNew : Resources.ColumnEditor_TitleEdit;
columnTitle = existing?.Title ?? "";
description = existing?.Description ?? "";
}
/// <summary>
/// Gets the localized window title.
/// </summary>
public string Title { get; }
/// <summary>
/// Gets or sets the column title being edited (not trimmed).
/// </summary>
[ObservableProperty]
private string columnTitle;
/// <summary>
/// Gets or sets the column description being edited.
/// </summary>
[ObservableProperty]
private string description;
/// <summary>
/// Gets the localized constraint error of the last confirmation, or <see langword="null"/>.
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasError))]
private string? errorMessage;
/// <summary>
/// Gets whether an error is shown.
/// </summary>
public bool HasError => ErrorMessage is not null;
/// <summary>
/// Writes the column; closes on success, otherwise shows the constraint error.
/// </summary>
[RelayCommand]
private void Confirm()
{
try
{
_save(ColumnTitle, Description);
}
catch (Exception exception)
{
ErrorMessage = WriteErrorMessages.Describe(exception);
return;
}
Close(true);
}
/// <summary>
/// Closes without writing.
/// </summary>
[RelayCommand]
private Task CancelAsync() => RequestCancelAsync();
}
@@ -1,129 +0,0 @@
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Storage.AppData;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The column width dialog: one of the narrow / standard / wide presets or a
/// manual pixel width (160–720). The choice is global and is committed to the
/// live configuration on confirmation only.
/// </summary>
public sealed partial class ColumnWidthDialogViewModel : DialogViewModelBase
{
private readonly ColumnWidthSettings _settings;
/// <summary>
/// Initializes the dialog from the live settings.
/// </summary>
/// <param name="settings">The live column width settings.</param>
public ColumnWidthDialogViewModel(ColumnWidthSettings settings)
{
_settings = settings;
CultureInfo? culture = Resources.Culture;
NarrowLabel = string.Format(culture, Resources.ColumnWidth_Narrow, ColumnWidths.Narrow);
StandardLabel = string.Format(culture, Resources.ColumnWidth_Standard, ColumnWidths.Standard);
WideLabel = string.Format(culture, Resources.ColumnWidth_Wide, ColumnWidths.Wide);
RangeLabel = string.Format(culture, Resources.ColumnWidth_Range, AppConfig.MinColumnPixels, AppConfig.MaxColumnPixels);
isNarrow = settings.Preset == ColumnWidthPreset.Narrow;
isStandard = settings.Preset == ColumnWidthPreset.Standard;
isWide = settings.Preset == ColumnWidthPreset.Wide;
isCustom = settings.Preset == ColumnWidthPreset.Custom;
customPixels = settings.CustomPixels;
}
/// <summary>Gets the localized narrow preset label.</summary>
public string NarrowLabel { get; }
/// <summary>Gets the localized standard preset label.</summary>
public string StandardLabel { get; }
/// <summary>Gets the localized wide preset label.</summary>
public string WideLabel { get; }
/// <summary>Gets the localized accepted pixel range.</summary>
public string RangeLabel { get; }
/// <summary>Gets the smallest accepted custom width.</summary>
public int MinPixels => AppConfig.MinColumnPixels;
/// <summary>Gets the largest accepted custom width.</summary>
public int MaxPixels => AppConfig.MaxColumnPixels;
/// <summary>Gets or sets whether the narrow preset is selected.</summary>
[ObservableProperty]
private bool isNarrow;
/// <summary>Gets or sets whether the standard preset is selected.</summary>
[ObservableProperty]
private bool isStandard;
/// <summary>Gets or sets whether the wide preset is selected.</summary>
[ObservableProperty]
private bool isWide;
/// <summary>Gets or sets whether the manual width is selected.</summary>
[ObservableProperty]
private bool isCustom;
/// <summary>Gets or sets the manual width in pixels; <see langword="null"/> while the box is empty.</summary>
[ObservableProperty]
private decimal? customPixels;
/// <summary>
/// Commits the selection to the live settings and closes.
/// </summary>
[RelayCommand]
private void Confirm()
{
if (IsCustom)
{
int pixels = (int)Math.Clamp(CustomPixels ?? _settings.CustomPixels, AppConfig.MinColumnPixels, AppConfig.MaxColumnPixels);
_settings.Preset = ColumnWidthPreset.Custom;
_settings.CustomPixels = pixels;
}
else
{
_settings.Preset = IsNarrow ? ColumnWidthPreset.Narrow
: IsWide ? ColumnWidthPreset.Wide
: ColumnWidthPreset.Standard;
}
Close(true);
}
/// <summary>
/// Closes without changing anything.
/// </summary>
[RelayCommand]
private Task CancelAsync() => RequestCancelAsync();
}
/// <summary>
/// Pixel widths of the column width presets.
/// </summary>
public static class ColumnWidths
{
/// <summary>The narrow preset width.</summary>
public const int Narrow = 240;
/// <summary>The standard (default) preset width.</summary>
public const int Standard = 320;
/// <summary>The wide preset width.</summary>
public const int Wide = 480;
/// <summary>
/// Resolves the effective column width of the settings.
/// </summary>
/// <param name="settings">The column width settings.</param>
/// <returns>The width in pixels.</returns>
public static int Resolve(ColumnWidthSettings settings) => settings.Preset switch
{
ColumnWidthPreset.Narrow => Narrow,
ColumnWidthPreset.Wide => Wide,
ColumnWidthPreset.Custom => Math.Clamp(settings.CustomPixels, AppConfig.MinColumnPixels, AppConfig.MaxColumnPixels),
_ => Standard,
};
}
@@ -1,43 +1,25 @@
using CommunityToolkit.Mvvm.Input;
namespace YKanBan.ViewModels.Dialogs; namespace YKanBan.ViewModels.Dialogs;
/// <summary> /// <summary>A generic confirmation dialog: localized title, message and yes/no answers.</summary>
/// A yes/no confirmation: a message, a confirming button with an action public sealed class ConfirmDialogViewModel : ViewModelBase
/// specific label (for example "Delete") and a cancel button.
/// </summary>
public sealed partial class ConfirmDialogViewModel : DialogViewModelBase
{ {
/// <summary> public ConfirmDialogViewModel(string title, string message)
/// Initializes the confirmation.
/// </summary>
/// <param name="message">The localized question.</param>
/// <param name="confirmLabel">The localized label of the confirming button.</param>
public ConfirmDialogViewModel(string message, string confirmLabel)
{ {
Title = title;
Message = message; Message = message;
ConfirmLabel = confirmLabel; ConfirmText = Resources.Common_Yes;
CancelText = Resources.Common_No;
} }
/// <summary> /// <summary>Localized dialog heading.</summary>
/// Gets the localized question. public string Title { get; }
/// </summary>
/// <summary>Localized message body.</summary>
public string Message { get; } public string Message { get; }
/// <summary> /// <summary>Label of the confirming button.</summary>
/// Gets the localized label of the confirming button. public string ConfirmText { get; }
/// </summary>
public string ConfirmLabel { get; }
/// <summary> /// <summary>Label of the cancelling button.</summary>
/// Closes with a positive result. public string CancelText { get; }
/// </summary>
[RelayCommand]
private void Confirm() => Close(true);
/// <summary>
/// Closes with a negative result.
/// </summary>
[RelayCommand]
private Task CancelAsync() => RequestCancelAsync();
} }
@@ -1,33 +0,0 @@
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// Base class for modal dialog view models shown through <see cref="IDialogService"/>.
/// The dialog decides when it closes: it raises <see cref="CloseRequested"/>
/// with its result, and a close attempted by the window itself (title-bar close
/// button, Escape) is routed to <see cref="RequestCancelAsync"/> so that the
/// dialog can veto it, for example to ask before discarding edits.
/// </summary>
public abstract class DialogViewModelBase : ViewModelBase
{
/// <summary>
/// Raised when the dialog wants to close; the argument is the dialog result.
/// </summary>
public event EventHandler<bool>? CloseRequested;
/// <summary>
/// Handles a cancel request coming from the window (or a cancel button).
/// The default closes immediately with a negative result.
/// </summary>
/// <returns>A task completing once the request has been handled.</returns>
public virtual Task RequestCancelAsync()
{
Close(false);
return Task.CompletedTask;
}
/// <summary>
/// Asks the hosting window to close with the given result.
/// </summary>
/// <param name="result">The dialog result.</param>
protected void Close(bool result) => CloseRequested?.Invoke(this, result);
}
@@ -1,50 +0,0 @@
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// Opens modal dialogs on behalf of view models, which never reference views.
/// Every dialog is owned by the top-most open window, so a dialog opened from
/// inside another dialog (nested modal) is centered on and blocks that dialog.
/// </summary>
public interface IDialogService
{
/// <summary>
/// Shows a dialog modally and waits until it closes.
/// </summary>
/// <param name="dialog">The dialog view model; its window is resolved by naming convention.</param>
/// <returns>The dialog result: <see langword="true"/> when it was accepted.</returns>
Task<bool> ShowAsync(DialogViewModelBase dialog);
/// <summary>
/// Shows the system save-file dialog for a Markdown file.
/// </summary>
/// <param name="suggestedFileName">The proposed file name.</param>
/// <returns>The chosen local path, or <see langword="null"/> when the user cancelled.</returns>
Task<string?> PickSaveFilePathAsync(string suggestedFileName);
}
/// <summary>
/// Convenience wrappers for the plain confirmation and message dialogs.
/// </summary>
public static class DialogServiceExtensions
{
/// <summary>
/// Asks a yes/no question.
/// </summary>
/// <param name="dialogs">The dialog service.</param>
/// <param name="message">The localized question.</param>
/// <param name="confirmLabel">The localized label of the confirming button.</param>
/// <returns><see langword="true"/> when the user confirmed.</returns>
public static Task<bool> ConfirmAsync(this IDialogService dialogs, string message, string confirmLabel) =>
dialogs.ShowAsync(new ConfirmDialogViewModel(message, confirmLabel));
/// <summary>
/// Shows an informational message with an optional read-only details block.
/// </summary>
/// <param name="dialogs">The dialog service.</param>
/// <param name="title">The localized window title.</param>
/// <param name="message">The localized message.</param>
/// <param name="details">Untranslated diagnostic details, or <see langword="null"/>.</param>
/// <returns>A task completing when the dialog closes.</returns>
public static Task ShowMessageAsync(this IDialogService dialogs, string title, string message, string? details = null) =>
dialogs.ShowAsync(new MessageDialogViewModel(title, message, details));
}
@@ -1,49 +0,0 @@
using CommunityToolkit.Mvvm.Input;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// A purely informational dialog with a single OK button: a localized message
/// plus optional untranslated, copyable diagnostic details.
/// </summary>
public sealed partial class MessageDialogViewModel : DialogViewModelBase
{
/// <summary>
/// Initializes the message.
/// </summary>
/// <param name="title">The localized window title.</param>
/// <param name="message">The localized message.</param>
/// <param name="details">Untranslated diagnostic details, or <see langword="null"/>.</param>
public MessageDialogViewModel(string title, string message, string? details)
{
Title = title;
Message = message;
Details = details;
}
/// <summary>
/// Gets the localized window title.
/// </summary>
public string Title { get; }
/// <summary>
/// Gets the localized message.
/// </summary>
public string Message { get; }
/// <summary>
/// Gets the diagnostic details, or <see langword="null"/> when there are none.
/// </summary>
public string? Details { get; }
/// <summary>
/// Gets whether a details block is shown.
/// </summary>
public bool HasDetails => !string.IsNullOrEmpty(Details);
/// <summary>
/// Closes the dialog.
/// </summary>
[RelayCommand]
private void Ok() => Close(true);
}
@@ -1,32 +1,28 @@
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using YKanBan.Services;
using YKanBan.Storage.AppData; using YKanBan.Storage.AppData;
namespace YKanBan.ViewModels.Dialogs; namespace YKanBan.ViewModels.Dialogs;
/// <summary> /// <summary>
/// The settings dialog: language (restart to apply), theme and the four /// The settings dialog: language (restart to apply), theme (applies
/// confirmation-dialog toggles. Nothing is applied until the user accepts; /// immediately) and the four confirmation-dialog toggles. All changes write
/// cancelling or closing the window discards the changes. /// straight into the configuration, which persists at shutdown.
/// </summary> /// </summary>
public sealed partial class SettingsDialogViewModel : ViewModelBase public partial class SettingsDialogViewModel : ViewModelBase
{ {
private readonly AppConfig _config; private readonly AppConfig _config;
private readonly string _startupLanguage; private readonly string _startupLanguage;
/// <summary> public SettingsDialogViewModel(AppServices services)
/// Initializes the dialog from the live configuration.
/// </summary>
/// <param name="config">The live application configuration.</param>
/// <param name="startupLanguage">The language applied at startup, for the restart notice.</param>
public SettingsDialogViewModel(AppConfig config, string startupLanguage)
{ {
_config = config; _config = services.Config;
_startupLanguage = startupLanguage; _startupLanguage = App.StartupLanguage;
Languages = Languages =
[ [
new OptionItem(AppConfig.DefaultLanguage, Resources.Settings_LanguageEnglish), new OptionItem(AppConfig.DefaultLanguage, Resources.Settings_LanguageEnglish),
new OptionItem(AppConfig.SimplifiedChineseLanguage, Resources.Settings_LanguageChinese), new OptionItem("zh-Hans", Resources.Settings_LanguageChinese),
]; ];
selectedLanguage = Languages.FirstOrDefault(option => (string)option.Value == _config.Language) selectedLanguage = Languages.FirstOrDefault(option => (string)option.Value == _config.Language)
?? Languages[0]; ?? Languages[0];
@@ -43,91 +39,69 @@ public sealed partial class SettingsDialogViewModel : ViewModelBase
confirmDeleteColumn = _config.Confirmations.DeleteColumn; confirmDeleteColumn = _config.Confirmations.DeleteColumn;
confirmDeleteTag = _config.Confirmations.DeleteTag; confirmDeleteTag = _config.Confirmations.DeleteTag;
confirmDiscardEdit = _config.Confirmations.DiscardEdit; confirmDiscardEdit = _config.Confirmations.DiscardEdit;
RefreshRestartNotice();
} }
/// <summary> /// <summary>Available languages.</summary>
/// Gets the available languages.
/// </summary>
public IReadOnlyList<OptionItem> Languages { get; } public IReadOnlyList<OptionItem> Languages { get; }
/// <summary> /// <summary>Available themes.</summary>
/// Gets the available themes.
/// </summary>
public IReadOnlyList<OptionItem> Themes { get; } public IReadOnlyList<OptionItem> Themes { get; }
/// <summary> /// <summary>The selected language; takes effect after a restart.</summary>
/// Gets or sets the selected language; takes effect after a restart.
/// </summary>
[ObservableProperty] [ObservableProperty]
private OptionItem? selectedLanguage; private OptionItem? selectedLanguage;
/// <summary> /// <summary>The selected theme; applies immediately.</summary>
/// Gets or sets the selected theme; applied when the dialog is accepted.
/// </summary>
[ObservableProperty] [ObservableProperty]
private OptionItem? selectedTheme; private OptionItem? selectedTheme;
/// <summary> /// <summary>Whether deleting a card asks for confirmation.</summary>
/// Gets or sets whether deleting a card asks for confirmation.
/// </summary>
[ObservableProperty] [ObservableProperty]
private bool confirmDeleteCard; private bool confirmDeleteCard;
/// <summary> /// <summary>Whether deleting a column asks for confirmation.</summary>
/// Gets or sets whether deleting a column asks for confirmation.
/// </summary>
[ObservableProperty] [ObservableProperty]
private bool confirmDeleteColumn; private bool confirmDeleteColumn;
/// <summary> /// <summary>Whether deleting a tag asks for confirmation.</summary>
/// Gets or sets whether deleting a tag asks for confirmation.
/// </summary>
[ObservableProperty] [ObservableProperty]
private bool confirmDeleteTag; private bool confirmDeleteTag;
/// <summary> /// <summary>Whether discarding card edits asks for confirmation.</summary>
/// Gets or sets whether discarding card edits asks for confirmation.
/// </summary>
[ObservableProperty] [ObservableProperty]
private bool confirmDiscardEdit; private bool confirmDiscardEdit;
/// <summary> /// <summary>True while the selected language differs from the one applied at startup.</summary>
/// Gets whether the working language differs from the one applied at startup.
/// </summary>
[ObservableProperty] [ObservableProperty]
private bool restartNoticeVisible; private bool restartNoticeVisible;
/// <summary> /// <summary>Stores the language and refreshes the restart notice.</summary>
/// Commits the working values into the live configuration. partial void OnSelectedLanguageChanged(OptionItem? value)
/// </summary>
public void Accept()
{ {
if (SelectedLanguage is not null) if (value is null)
{ {
_config.Language = (string)SelectedLanguage.Value; return;
} }
if (SelectedTheme is not null) _config.Language = (string)value.Value;
RestartNoticeVisible = _config.Language != _startupLanguage;
}
/// <summary>Stores the theme and applies it immediately.</summary>
partial void OnSelectedThemeChanged(OptionItem? value)
{ {
_config.Theme = (ThemeOption)SelectedTheme.Value; if (value is null)
{
return;
}
_config.Theme = (ThemeOption)value.Value;
App.ApplyTheme(_config.Theme); App.ApplyTheme(_config.Theme);
} }
_config.Confirmations.DeleteCard = ConfirmDeleteCard; partial void OnConfirmDeleteCardChanged(bool value) => _config.Confirmations.DeleteCard = value;
_config.Confirmations.DeleteColumn = ConfirmDeleteColumn;
_config.Confirmations.DeleteTag = ConfirmDeleteTag;
_config.Confirmations.DiscardEdit = ConfirmDiscardEdit;
}
/// <summary> partial void OnConfirmDeleteColumnChanged(bool value) => _config.Confirmations.DeleteColumn = value;
/// Refreshes the restart notice after a language selection change.
/// </summary>
/// <param name="value">The new selection.</param>
partial void OnSelectedLanguageChanged(OptionItem? value) => RefreshRestartNotice();
/// <summary> partial void OnConfirmDeleteTagChanged(bool value) => _config.Confirmations.DeleteTag = value;
/// Recomputes whether the restart notice must be shown.
/// </summary> partial void OnConfirmDiscardEditChanged(bool value) => _config.Confirmations.DiscardEdit = value;
private void RefreshRestartNotice() =>
RestartNoticeVisible = SelectedLanguage is not null && (string)SelectedLanguage.Value != _startupLanguage;
} }
-26
View File
@@ -1,26 +0,0 @@
using YKanBan.Models;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The default colors proposed for new tags, shared by the tag picker and the
/// tag editor.
/// </summary>
public static class TagColors
{
/// <summary>
/// Gets the palette, offered as swatches and cycled for new-tag defaults.
/// </summary>
public static IReadOnlyList<RgbColor> Palette { get; } =
[
new(0xd7, 0x3a, 0x4a), new(0x00, 0x75, 0xca), new(0x0e, 0x8a, 0x16), new(0xfb, 0xca, 0x04),
new(0x7c, 0x3a, 0xed), new(0xe9, 0x9b, 0x3c), new(0x00, 0x8b, 0x8b), new(0xcf, 0xd3, 0xd7),
];
/// <summary>
/// Returns the default color of a new tag, cycled by the number of existing tags.
/// </summary>
/// <param name="existingCount">The number of tags already in the workspace.</param>
/// <returns>The proposed color.</returns>
public static RgbColor DefaultFor(int existingCount) => Palette[existingCount % Palette.Count];
}
@@ -1,146 +0,0 @@
using Avalonia.Media;
using Avalonia.Media.Immutable;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The new-tag / edit-tag dialog of the tags tab: name (required, not trimmed),
/// #RRGGBB color with palette swatches and a live preview, and an optional
/// description. Confirming writes through the supplied save callback; an invalid
/// color or a schema-constraint violation (empty or duplicate name) is shown
/// inside the dialog, which stays open with the user's input intact.
/// </summary>
public sealed partial class TagEditorDialogViewModel : DialogViewModelBase
{
private readonly Action<string, RgbColor, string> _save;
/// <summary>
/// Initializes the dialog.
/// </summary>
/// <param name="existing">The tag being edited, or <see langword="null"/> for a new tag.</param>
/// <param name="defaultColor">The color proposed for a new tag.</param>
/// <param name="save">Writes the name, color and description; throws the repository's typed exceptions.</param>
public TagEditorDialogViewModel(TagModel? existing, RgbColor defaultColor, Action<string, RgbColor, string> save)
{
_save = save;
Title = existing is null ? Resources.TagEditor_TitleNew : Resources.TagEditor_TitleEdit;
name = existing?.Name ?? "";
color = (existing?.Color ?? defaultColor).ToString();
description = existing?.Description ?? "";
Swatches = TagColors.Palette.Select(swatch => new ColorSwatch(swatch.ToString(), ToBrush(swatch))).ToList();
UpdateColorPreview();
}
/// <summary>
/// Gets the localized window title.
/// </summary>
public string Title { get; }
/// <summary>
/// Gets the palette swatches; clicking one sets <see cref="Color"/>.
/// </summary>
public IReadOnlyList<ColorSwatch> Swatches { get; }
/// <summary>
/// Gets or sets the tag name being edited (not trimmed).
/// </summary>
[ObservableProperty]
private string name;
/// <summary>
/// Gets or sets the #RRGGBB color text being edited.
/// </summary>
[ObservableProperty]
private string color;
/// <summary>
/// Gets or sets the tag description being edited.
/// </summary>
[ObservableProperty]
private string description;
/// <summary>
/// Gets the preview of <see cref="Color"/>, transparent while it is not valid.
/// </summary>
[ObservableProperty]
private IBrush colorPreview = Brushes.Transparent;
/// <summary>
/// Gets the localized error of the last confirmation, or <see langword="null"/>.
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasError))]
private string? errorMessage;
/// <summary>
/// Gets whether an error is shown.
/// </summary>
public bool HasError => ErrorMessage is not null;
/// <summary>
/// Takes a swatch color.
/// </summary>
/// <param name="hex">The swatch's #RRGGBB text.</param>
[RelayCommand]
private void PickSwatch(string hex) => Color = hex;
/// <summary>
/// Writes the tag; closes on success, otherwise shows the error.
/// </summary>
[RelayCommand]
private void Confirm()
{
if (!RgbColor.TryParse(Color, out RgbColor parsed))
{
ErrorMessage = Resources.Error_Tag_InvalidColor;
return;
}
try
{
_save(Name, parsed, Description);
}
catch (Exception exception)
{
ErrorMessage = WriteErrorMessages.Describe(exception);
return;
}
Close(true);
}
/// <summary>
/// Closes without writing.
/// </summary>
[RelayCommand]
private Task CancelAsync() => RequestCancelAsync();
/// <summary>
/// Refreshes the color preview.
/// </summary>
/// <param name="value">The new color text.</param>
partial void OnColorChanged(string value) => UpdateColorPreview();
/// <summary>
/// Recomputes <see cref="ColorPreview"/> from <see cref="Color"/>.
/// </summary>
private void UpdateColorPreview() =>
ColorPreview = RgbColor.TryParse(Color, out RgbColor parsed) ? ToBrush(parsed) : Brushes.Transparent;
/// <summary>
/// Creates the thread-agnostic brush of a tag color.
/// </summary>
/// <param name="value">The color.</param>
/// <returns>The brush.</returns>
private static IBrush ToBrush(RgbColor value) =>
new ImmutableSolidColorBrush(Avalonia.Media.Color.FromRgb(value.R, value.G, value.B));
}
/// <summary>
/// A palette swatch of the tag editor.
/// </summary>
/// <param name="Hex">The #RRGGBB text.</param>
/// <param name="Brush">The fill.</param>
public sealed record ColorSwatch(string Hex, IBrush Brush);
@@ -1,176 +0,0 @@
using System.Collections.ObjectModel;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
using YKanBan.Storage;
using YKanBan.Storage.Workspace;
using YKanBan.ViewModels.Board;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The nested "add tag" modal of the card editor: a filterable list of the
/// existing tags not yet on the card, plus a new-tag entry. Picking a tag closes
/// the dialog with it as <see cref="PickedTag"/>.
///
/// Exception to the edit-dialog unit of work: a tag created here is written to
/// the tags table immediately (tags are global entities), so it survives even
/// when the outer card edit is cancelled — only the assignment is discarded.
/// </summary>
public sealed partial class TagPickerDialogViewModel : DialogViewModelBase
{
private readonly WorkspaceRepository _repository;
private readonly IReadOnlyList<TagBadgeViewModel> _available;
/// <summary>
/// Initializes the picker.
/// </summary>
/// <param name="repository">The workspace repository; new tags are written through it immediately.</param>
/// <param name="assignedTagIds">The tags already on the card, which are not offered again.</param>
public TagPickerDialogViewModel(WorkspaceRepository repository, IReadOnlyCollection<long> assignedTagIds)
{
_repository = repository;
IReadOnlyList<TagModel> all = repository.GetTags();
_available = all
.Where(tag => !assignedTagIds.Contains(tag.Id))
.Select(tag => new TagBadgeViewModel(tag))
.ToList();
FilteredTags = new ObservableCollection<TagBadgeViewModel>(_available);
newColor = TagColors.DefaultFor(all.Count).ToString();
UpdateColorPreview();
}
/// <summary>
/// Gets the tag the user picked or created, once the dialog closed positively.
/// </summary>
public TagModel? PickedTag { get; private set; }
/// <summary>
/// Gets the available tags matching <see cref="FilterText"/>.
/// </summary>
public ObservableCollection<TagBadgeViewModel> FilteredTags { get; }
/// <summary>
/// Gets whether no available tag matches the filter.
/// </summary>
public bool NoMatches => FilteredTags.Count == 0;
/// <summary>
/// Gets or sets the list filter: a case-insensitive substring of the tag name.
/// </summary>
[ObservableProperty]
private string filterText = "";
/// <summary>
/// Gets or sets the name of the tag to create (not trimmed).
/// </summary>
[ObservableProperty]
private string newName = "";
/// <summary>
/// Gets or sets the #RRGGBB color text of the tag to create.
/// </summary>
[ObservableProperty]
private string newColor;
/// <summary>
/// Gets or sets the description of the tag to create.
/// </summary>
[ObservableProperty]
private string newDescription = "";
/// <summary>
/// Gets the preview of <see cref="NewColor"/>, transparent while it is not valid.
/// </summary>
[ObservableProperty]
private IBrush newColorPreview = Brushes.Transparent;
/// <summary>
/// Gets the localized error of the last create attempt, or <see langword="null"/>.
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasError))]
private string? errorMessage;
/// <summary>
/// Gets whether an error is shown.
/// </summary>
public bool HasError => ErrorMessage is not null;
/// <summary>
/// Picks an existing tag and closes.
/// </summary>
/// <param name="tag">The picked tag.</param>
[RelayCommand]
private void Pick(TagBadgeViewModel tag)
{
PickedTag = tag.Tag;
Close(true);
}
/// <summary>
/// Creates the new tag right away and closes with it picked; constraint
/// violations and an invalid color keep the dialog open with an error.
/// </summary>
[RelayCommand]
private void Create()
{
if (!RgbColor.TryParse(NewColor, out RgbColor color))
{
ErrorMessage = Resources.Error_Tag_InvalidColor;
return;
}
try
{
PickedTag = _repository.AddTag(NewName, color, NewDescription);
}
catch (Exception exception)
{
ErrorMessage = WriteErrorMessages.Describe(exception);
return;
}
Close(true);
}
/// <summary>
/// Closes without picking anything.
/// </summary>
[RelayCommand]
private Task CancelAsync() => RequestCancelAsync();
/// <summary>
/// Re-filters the list.
/// </summary>
/// <param name="value">The new filter text.</param>
partial void OnFilterTextChanged(string value)
{
string folded = SqliteDatabase.Fold(value);
FilteredTags.Clear();
foreach (TagBadgeViewModel tag in _available)
{
if (SqliteDatabase.Fold(tag.Name).Contains(folded, StringComparison.Ordinal))
{
FilteredTags.Add(tag);
}
}
OnPropertyChanged(nameof(NoMatches));
}
/// <summary>
/// Refreshes the color preview.
/// </summary>
/// <param name="value">The new color text.</param>
partial void OnNewColorChanged(string value) => UpdateColorPreview();
/// <summary>
/// Recomputes <see cref="NewColorPreview"/> from <see cref="NewColor"/>.
/// </summary>
private void UpdateColorPreview() =>
NewColorPreview = RgbColor.TryParse(NewColor, out RgbColor color)
? new ImmutableSolidColorBrush(Color.FromRgb(color.R, color.G, color.B))
: Brushes.Transparent;
}
@@ -1,33 +0,0 @@
using System.Globalization;
using YKanBan.Storage;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// Maps a failed dialog write to the localized message shown inside the dialog
/// that attempted it (the dialog stays open and keeps the user's input). The
/// typed schema-constraint exceptions get dedicated messages; anything else
/// gets a generic one carrying the untranslated exception message.
/// </summary>
public static class WriteErrorMessages
{
/// <summary>
/// Returns the localized message for a failed write.
/// </summary>
/// <param name="exception">The exception thrown by the write.</param>
/// <returns>The localized message.</returns>
public static string Describe(Exception exception)
{
CultureInfo? culture = Resources.Culture;
return exception switch
{
NameRequiredException { Entity: NamedEntity.Column } => Resources.Error_Column_TitleRequired,
NameRequiredException { Entity: NamedEntity.Tag } => Resources.Error_Tag_NameRequired,
DuplicateNameException { Entity: NamedEntity.Column } duplicate =>
string.Format(culture, Resources.Error_Column_Duplicate, duplicate.Name),
DuplicateNameException { Entity: NamedEntity.Tag } duplicate =>
string.Format(culture, Resources.Error_Tag_Duplicate, duplicate.Name),
_ => string.Format(culture, Resources.Error_SaveFailed, exception.Message),
};
}
}
@@ -1,9 +0,0 @@
namespace YKanBan.ViewModels.ErrorPages;
/// <summary>
/// The full-window page shown when YKanBan is started without arguments or with
/// invalid arguments. It has no operations.
/// </summary>
public sealed class ArgumentErrorPageViewModel : ViewModelBase
{
}
@@ -1,31 +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; }
}
@@ -1,31 +0,0 @@
using System.Globalization;
namespace YKanBan.ViewModels.ErrorPages;
/// <summary>
/// The full-window page shown when the workspace is already locked by another
/// instance. It has no operations.
/// </summary>
public sealed class LockConflictPageViewModel : ViewModelBase
{
/// <summary>
/// Initializes the page for a locked workspace.
/// </summary>
/// <param name="folderPath">The locked workspace folder.</param>
public LockConflictPageViewModel(string folderPath)
{
FolderPath = folderPath;
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Error_LockConflict_Message, folderPath);
}
/// <summary>
/// Gets the locked workspace folder.
/// </summary>
public string FolderPath { get; }
/// <summary>
/// Gets the localized explanatory message.
/// </summary>
public string Message { get; }
}
@@ -1,43 +0,0 @@
using System.Globalization;
using CommunityToolkit.Mvvm.Input;
namespace YKanBan.ViewModels.ErrorPages;
/// <summary>
/// The full-window page shown when the folder exists but has no .ykanban
/// structure. It is the only error page with an operation: initializing the
/// workspace.
/// </summary>
public sealed partial class NotInitializedPageViewModel : ViewModelBase
{
private readonly Interaction<Unit> _initializeWorkspace;
/// <summary>
/// Initializes the page for a folder without a workspace.
/// </summary>
/// <param name="folderPath">The uninitialized folder path.</param>
/// <param name="initializeWorkspace">The interaction that performs initialization.</param>
public NotInitializedPageViewModel(string folderPath, Interaction<Unit> initializeWorkspace)
{
FolderPath = folderPath;
_initializeWorkspace = initializeWorkspace;
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Error_NotInitialized_Message, folderPath);
}
/// <summary>
/// Gets the uninitialized folder path.
/// </summary>
public string FolderPath { get; }
/// <summary>
/// Gets the localized explanatory message.
/// </summary>
public string Message { get; }
/// <summary>
/// Asks the owning view model to initialize this folder as a workspace.
/// </summary>
[RelayCommand]
private async Task InitializeAsync() => await _initializeWorkspace.Handle(Unit.Value);
}
@@ -1,65 +0,0 @@
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),
};
}
}
+7 -50
View File
@@ -1,48 +1,12 @@
namespace YKanBan.ViewModels; namespace YKanBan.ViewModels;
/// <summary> /// <summary>Input placeholder for interactions that carry no meaningful input.</summary>
/// Input placeholder for interactions that carry no meaningful payload. public readonly record struct Unit;
/// </summary>
public readonly record struct Unit
{
/// <summary>
/// Gets the single unit value.
/// </summary>
public static Unit Value => default;
}
/// <summary> /// <summary>
/// A view-model side request with no result that the owning view fulfils /// A view-model side request that the owning view fulfils through a
/// through a registered handler (opening a dialog, for example) — the classic /// registered handler (dialogs, pickers) — the classic MVVM interaction
/// MVVM interaction pattern, implemented locally without extra dependencies. /// pattern, implemented locally without extra dependencies.
/// The view model never holds a reference to a view.
/// </summary>
/// <typeparam name="TInput">The request payload.</typeparam>
public sealed class Interaction<TInput>
{
private Func<TInput, Task>? _handler;
/// <summary>
/// Registers the single handler; the view calls this once.
/// </summary>
/// <param name="handler">The handler that fulfils the request.</param>
public void RegisterHandler(Func<TInput, Task> handler) => _handler = handler;
/// <summary>
/// Invokes the registered handler.
/// </summary>
/// <param name="input">The request payload.</param>
/// <returns>A task that completes when the handler completes.</returns>
/// <exception cref="InvalidOperationException">No handler has been registered.</exception>
public Task Handle(TInput input) =>
_handler is null
? throw new InvalidOperationException("No handler registered for this interaction.")
: _handler(input);
}
/// <summary>
/// A view-model side request that produces a result, fulfilled through a
/// registered handler.
/// </summary> /// </summary>
/// <typeparam name="TInput">The request payload.</typeparam> /// <typeparam name="TInput">The request payload.</typeparam>
/// <typeparam name="TOutput">The handler's answer.</typeparam> /// <typeparam name="TOutput">The handler's answer.</typeparam>
@@ -50,17 +14,10 @@ public sealed class Interaction<TInput, TOutput>
{ {
private Func<TInput, Task<TOutput>>? _handler; private Func<TInput, Task<TOutput>>? _handler;
/// <summary> /// <summary>Registers the single handler; the view calls this once.</summary>
/// Registers the single handler; the view calls this once.
/// </summary>
/// <param name="handler">The handler that fulfils the request.</param>
public void RegisterHandler(Func<TInput, Task<TOutput>> handler) => _handler = handler; public void RegisterHandler(Func<TInput, Task<TOutput>> handler) => _handler = handler;
/// <summary> /// <summary>Invokes the registered handler.</summary>
/// Invokes the registered handler.
/// </summary>
/// <param name="input">The request payload.</param>
/// <returns>The handler's answer.</returns>
/// <exception cref="InvalidOperationException">No handler has been registered.</exception> /// <exception cref="InvalidOperationException">No handler has been registered.</exception>
public Task<TOutput> Handle(TInput input) => public Task<TOutput> Handle(TInput input) =>
_handler is null _handler is null
+68 -116
View File
@@ -1,151 +1,103 @@
using System.Diagnostics; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.ComponentModel;
using YKanBan.Launching;
using YKanBan.Services; using YKanBan.Services;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.ViewModels.Dialogs; using YKanBan.ViewModels.Pages;
using YKanBan.ViewModels.ErrorPages;
namespace YKanBan.ViewModels; namespace YKanBan.ViewModels;
/// <summary> /// <summary>
/// The main window view model. It resolves the launch arguments into either the /// Root view model: owns the sidebar and the current content page (welcome,
/// normal workspace view or one of the full-window error pages, and owns the /// an open workspace, or a failure state page).
/// interactions that the view fulfils by opening dialogs.
/// </summary> /// </summary>
public sealed partial class MainWindowViewModel : ViewModelBase public partial class MainWindowViewModel : ViewModelBase
{ {
private readonly AppServices _services; public MainWindowViewModel(AppServices services)
private readonly IDialogService _dialogs;
/// <summary>
/// Initializes the view model and resolves the workspace state.
/// </summary>
/// <param name="services">The process composition root.</param>
/// <param name="dialogs">The modal dialog service used by the board.</param>
/// <param name="arguments">The command-line arguments (excluding the executable).</param>
public MainWindowViewModel(AppServices services, IDialogService dialogs, IReadOnlyList<string> arguments)
{ {
_services = services; Services = services;
_dialogs = dialogs; Sidebar = new SidebarViewModel(this, services);
ShowSettings = new Interaction<Unit>(); CurrentContent = new WelcomePageViewModel();
ShowAbout = new Interaction<Unit>(); }
InitializeWorkspace = new Interaction<Unit>();
InitializeWorkspace.RegisterHandler(_ => InitializeCurrentWorkspaceAsync()); /// <summary>The composition root.</summary>
Resolve(arguments); public AppServices Services { get; }
/// <summary>The workspace sidebar.</summary>
public SidebarViewModel Sidebar { get; }
/// <summary>The currently displayed content page.</summary>
[ObservableProperty]
private object? currentContent;
/// <summary>Shows the welcome page (no workspace active).</summary>
public void ShowWelcome()
{
CurrentContent = new WelcomePageViewModel();
} }
/// <summary> /// <summary>
/// Gets the interaction that opens the settings dialog. /// Opens (or switches to) a workspace from the UI flow: a plain folder
/// prompts for initialization before opening.
/// </summary> /// </summary>
public Interaction<Unit> ShowSettings { get; } public async Task OpenWorkspaceWithInitializePromptAsync(string folderPath)
/// <summary>
/// Gets the interaction that opens the about dialog.
/// </summary>
public Interaction<Unit> ShowAbout { get; }
/// <summary>
/// Gets the interaction that initializes the not-initialized workspace.
/// </summary>
public Interaction<Unit> InitializeWorkspace { get; }
/// <summary>
/// Gets or sets the window title.
/// </summary>
[ObservableProperty]
private string title = Resources.App_Name;
/// <summary>
/// Gets or sets the current content: the workspace view or an error page.
/// </summary>
[ObservableProperty]
private ViewModelBase? content;
/// <summary>
/// Resolves the launch arguments into a content view model.
/// </summary>
/// <param name="arguments">The command-line arguments.</param>
private void Resolve(IReadOnlyList<string> arguments)
{ {
if (!LaunchArguments.TryParse(arguments, out string? folderPath)) string canonical = Services.PathComparison.Normalize(folderPath);
if (!WorkspaceInitializer.IsWorkspace(canonical))
{ {
Content = new ArgumentErrorPageViewModel(); if (!Directory.Exists(canonical))
{
ShowFailure(Resources.State_DirectoryMissing_Title, Resources.State_DirectoryMissing_Detail);
return; return;
} }
if (!Directory.Exists(folderPath)) bool confirmed = await Sidebar.ConfirmInitialize.Handle(canonical);
if (!confirmed)
{ {
Content = new DirectoryMissingPageViewModel(folderPath);
return; return;
} }
WorkspaceInitializer.Initialize(canonical);
WorkspacePreset.SeedColumns(canonical);
}
TryOpenWorkspaceSession(canonical);
}
/// <summary>Opens (or switches to) a workspace without any initialization prompt (IPC entry).</summary>
public void OpenWorkspaceFromLaunch(string folderPath)
{
TryOpenWorkspaceSession(Services.PathComparison.Normalize(folderPath));
}
/// <summary>Opens the session through the pool; typed failures map to localized state pages.</summary>
public void TryOpenWorkspaceSession(string canonicalPath)
{
try try
{ {
OpenWorkspace(folderPath); WorkspaceSession session = Services.Pool.Open(canonicalPath);
CurrentContent = new WorkspacePageViewModel(session);
Sidebar.RebuildWorkspaceList();
} }
catch (WorkspaceNotInitializedException) catch (Exception ex)
{ {
Content = new NotInitializedPageViewModel(folderPath, InitializeWorkspace); (string title, string detail) = DescribeOpenFailure(ex);
} ShowFailure(title, detail);
catch (WorkspaceLockException)
{
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);
} }
} }
/// <summary> /// <summary>Displays a localized failure state page.</summary>
/// Opens the workspace and switches the content to the normal view. private void ShowFailure(string title, string detail)
/// </summary>
/// <param name="folderPath">The workspace folder to open.</param>
private void OpenWorkspace(string folderPath) => ShowWorkspace(folderPath, _services.OpenWorkspace(folderPath));
/// <summary>
/// Switches the content to the normal view of an opened workspace.
/// </summary>
/// <param name="folderPath">The workspace folder.</param>
/// <param name="session">The opened workspace session.</param>
private void ShowWorkspace(string folderPath, WorkspaceSession session)
{ {
Content = new WorkspaceViewModel(session, ShowSettings, ShowAbout, _services.Config, _dialogs); CurrentContent = new MessagePageViewModel(title, detail);
Title = $"{new DirectoryInfo(folderPath).Name} - {Resources.App_Name}";
} }
/// <summary> /// <summary>Maps an open failure to localized title/detail text by exception type.</summary>
/// Initializes the folder shown by the not-initialized page with its preset private static (string Title, string Detail) DescribeOpenFailure(Exception exception) => exception switch
/// columns and opens the resulting workspace.
/// </summary>
/// <returns>A completed task once initialization has been attempted.</returns>
private Task InitializeCurrentWorkspaceAsync()
{ {
if (Content is not NotInitializedPageViewModel page) WorkspaceLockException => (Resources.State_LockConflict_Title, Resources.State_LockConflict_Detail),
{ WorkspaceNotInitializedException => (Resources.State_NotInitialized_Title, Resources.State_NotInitialized_Detail),
return Task.CompletedTask; WorkspaceDirectoryMissingException => (Resources.State_DirectoryMissing_Title, Resources.State_DirectoryMissing_Detail),
} SchemaVersionException => (Resources.State_SchemaVersion_Title, Resources.State_SchemaVersion_Detail),
_ => (Resources.State_Unknown_Title, exception.Message),
try };
{
ShowWorkspace(page.FolderPath, _services.InitializeWorkspace(page.FolderPath));
}
catch (WorkspaceLockException)
{
// Another instance got there first and holds the workspace: same page as at startup.
Content = new LockConflictPageViewModel(page.FolderPath);
}
catch (Exception exception)
{
// Initialization failed: switch to the open-failed page, which has no operations.
Debug.WriteLine(exception);
Content = new OpenFailedPageViewModel(page.FolderPath, exception);
}
return Task.CompletedTask;
}
} }
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more