Compare commits
39
Commits
b5614ff59b
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0672735fe0 | ||
|
|
62c62956d3 | ||
|
|
97b44a4b85 | ||
|
|
309f37eead | ||
|
|
6b5a59cd87 | ||
|
|
506fb4b2f1 | ||
|
|
b7a6373e17 | ||
|
|
2220fcf48b | ||
|
|
b0024f3aa4 | ||
|
|
aba62a58c2 | ||
|
|
61d3a0c03c | ||
|
|
c2b744e742 | ||
|
|
9c47ce6b38 | ||
|
|
704b0ff3cf | ||
|
|
a9e97d9b35 | ||
|
|
da2a73d70f | ||
|
|
68e4ace92b | ||
|
|
e9f39a3a53 | ||
|
|
60619e0290 | ||
|
|
e3265e3c89 | ||
|
|
157f597eed | ||
|
|
1140cd500b | ||
|
|
7f277d1630 | ||
|
|
647232c447 | ||
|
|
78e5faa3c4 | ||
|
|
97f79db3f1 | ||
|
|
90a7531a27 | ||
|
|
8b7e50a955 | ||
|
|
9ea551b600 | ||
|
|
8a7c6fe8d6 | ||
|
|
d8a4dd6190 | ||
|
|
0fdd94d109 | ||
|
|
830f1153fd | ||
|
|
f36561cb7f | ||
|
|
22a0f61cb5 | ||
|
|
941e22c7ff | ||
|
|
c2ee02c209 | ||
|
|
a5edad4aad | ||
|
|
93ea102d89 |
No files matched your search
+1
-1
@@ -18,7 +18,7 @@ indent_size = 4
|
||||
tab_width = 4
|
||||
|
||||
# New line preferences
|
||||
insert_final_newline = false
|
||||
insert_final_newline = true
|
||||
|
||||
#### .NET Coding Conventions ####
|
||||
[*.{cs,vb}]
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# Shell scripts run under bash on every CI runner, including Windows checkouts with autocrlf.
|
||||
*.sh text eol=lf
|
||||
@@ -0,0 +1,71 @@
|
||||
# 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.
|
||||
# win-x64 packs an Inno Setup installer; linux-x64 a tar.gz; osx-arm64 a
|
||||
# drag-to-Applications dmg.
|
||||
# Artifacts are uploaded unzipped (upload-artifact archive: false): each RID's
|
||||
# dist/ holds exactly one file, and its name becomes the artifact name.
|
||||
# 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-arm64
|
||||
os: macos-latest
|
||||
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
|
||||
run: |
|
||||
version="$(dotnet msbuild YKanBan/YKanBan.csproj -getProperty:Version)"
|
||||
bash packaging/package.sh ${{ matrix.rid }} publish/${{ matrix.rid }} dist "$version"
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
# archive: false uploads the single matched file as-is (no zip
|
||||
# wrapper); the file name doubles as the artifact name.
|
||||
path: dist/*
|
||||
archive: false
|
||||
if-no-files-found: error
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 yyc12345
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,5 +1,28 @@
|
||||
# YKanBan
|
||||
|
||||
My personal used local/offline kanban.
|
||||
A personal, local/offline kanban board. Cross-platform desktop app built with Avalonia UI and MVVM. Each workspace stores its data in a `.ykanban` folder at the project root, Git-style; start it with `ykanban <path>`.
|
||||
|
||||
WIP.
|
||||
- One board per workspace, with columns, cards and colored tags.
|
||||
- Strict search expressions, for example `tag:bug OR title:login`.
|
||||
- Markdown export of the whole board, and a tag manager.
|
||||
- Multi-language interface; light, dark or system theme.
|
||||
|
||||
See [USAGE.md](USAGE.md) for installing, starting YKanBan, workspaces and backups, the search syntax and the settings file.
|
||||
|
||||
## Building
|
||||
|
||||
Requires the .NET 10 SDK.
|
||||
|
||||
```
|
||||
dotnet build YKanBan.slnx
|
||||
dotnet test YKanBan.slnx
|
||||
dotnet run --project YKanBan -- <path>
|
||||
```
|
||||
|
||||
Packages are pinned in `YKanBan/YKanBan.csproj`.
|
||||
|
||||
Release archives for win-x64, linux-x64 and osx-arm64 are produced by the manually triggered workflow in `.github/workflows/build.yml`; `packaging/package.sh` packs one published RID.
|
||||
|
||||
## License
|
||||
|
||||
MIT — see [LICENSE](LICENSE).
|
||||
@@ -0,0 +1,194 @@
|
||||
# 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
|
||||
|
||||
Each release build is self-contained; no .NET runtime is needed.
|
||||
|
||||
| Platform | Package | Executable |
|
||||
|---|---|---|
|
||||
| Windows x64 | `YKanBan-<version>-win-x64-setup.exe` | `YKanBan.exe` |
|
||||
| Linux x64 | `YKanBan-<version>-linux-x64.tar.gz` | `YKanBan` |
|
||||
| macOS Apple silicon | `YKanBan-<version>-osx-arm64.dmg` | `YKanBan.app` (see [macOS](#macos)) |
|
||||
|
||||
Only Apple silicon macOS is a release target; there is no Intel Mac build.
|
||||
|
||||
On Windows, run the installer. On Linux, extract the archive anywhere. On macOS, open the disk image and drag `YKanBan.app` into `Applications` (or any other folder). 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 installed folder to `PATH` (the default is `C:\Program Files\YKanBan`); `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`.
|
||||
|
||||
The path must exist and be a folder. 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`), a path the operating system cannot represent (for example one containing a NUL character), or a path that does not exist or is not a folder. Shows the usage line. |
|
||||
| No workspace here | `<path>` exists but has no `.ykanban`. The **Initialize workspace** button creates one, with the columns To Do / In Progress / Done and the preset tags (both 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 dragging it out of the disk image, 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. The file itself is kept empty; only the exclusive OS handle it carries has meaning.
|
||||
|
||||
## 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.
|
||||
- An active search keeps the result set it produced until you search again: after adding, editing, moving or deleting cards the board shows the same matching cards as before, minus any that were deleted. Adding or editing a card does not change whether it is currently shown; press **Search** again to refresh the result.
|
||||
|
||||
### 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 each be unique, but the uniqueness check is case-sensitive: `Bug` and `bug` are different names and can both exist. Because matching folds case, a query such as `tag:bug` then 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)` |
|
||||
| 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. With several instances running, the last one to exit overwrites the file with its own settings.
|
||||
- A language change takes effect after restarting YKanBan; a theme change applies as soon as the settings dialog is accepted.
|
||||
- A missing file is normal on first run and yields the defaults. If the file exists but cannot be read (an I/O or permission error), the defaults are used.
|
||||
- If the file cannot be parsed, it is saved as `app.json.bak` and the defaults are used. This also covers an invalid enum value: an unknown theme, sort or width string, or a numeric enum value, makes the whole file fall back to defaults. A section that is simply missing falls back to its own defaults.
|
||||
@@ -0,0 +1,53 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace YKanBan.Tests.Conventions;
|
||||
|
||||
/// <summary>
|
||||
/// Source-level guards for code-behind conventions (plan §8.1): inside control,
|
||||
/// window and application code-behind a bare <c>Resources.Key</c> resolves to
|
||||
/// the <c>StyledElement.Resources</c> instance property, so the generated class
|
||||
/// must be written as <c>YKanBan.Resources</c> (or through a using alias).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public partial class CodeBehindConventionTests {
|
||||
/// <summary>A <c>Resources.</c> member access not preceded by a qualifier or identifier character.</summary>
|
||||
[GeneratedRegex(@"(?<![\w.])Resources\.")]
|
||||
private static partial Regex BareResourcesAccess();
|
||||
|
||||
/// <summary>
|
||||
/// Locates the application project's source folder from this file's compile-time path.
|
||||
/// </summary>
|
||||
/// <param name="thisFile">Filled in by the compiler.</param>
|
||||
/// <returns>The YKanBan project folder.</returns>
|
||||
private static string ApplicationSourceFolder([CallerFilePath] string thisFile = "") {
|
||||
DirectoryInfo? directory = new FileInfo(thisFile).Directory;
|
||||
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "YKanBan", "YKanBan.csproj"))) {
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
Assert.IsNotNull(directory, "Repository root not found from the test source path.");
|
||||
return Path.Combine(directory.FullName, "YKanBan");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CodeBehindNeverUsesBareResourcesClassName() {
|
||||
string root = ApplicationSourceFolder();
|
||||
string[] files = Directory.GetFiles(root, "*.axaml.cs", SearchOption.AllDirectories)
|
||||
.Where(path => !path.Split(Path.DirectorySeparatorChar).Any(part => part is "obj" or "bin"))
|
||||
.ToArray();
|
||||
Assert.IsTrue(files.Length > 0, "No code-behind files found.");
|
||||
|
||||
var offenders = new List<string>();
|
||||
foreach (string file in files) {
|
||||
string[] lines = File.ReadAllLines(file);
|
||||
for (int index = 0; index < lines.Length; index++) {
|
||||
if (BareResourcesAccess().IsMatch(lines[index])) {
|
||||
offenders.Add($"{Path.GetRelativePath(root, file)}:{index + 1}: {lines[index].Trim()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, offenders.Count, "Use YKanBan.Resources in code-behind:" + Environment.NewLine + string.Join(Environment.NewLine, offenders));
|
||||
}
|
||||
}
|
||||
@@ -1,31 +1,52 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
using YKanBan.Export;
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.Tests.Export;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the Markdown exporter. Mutates the global Resources.Culture,
|
||||
/// therefore marked DoNotParallelize. Asserts real localized output for
|
||||
/// both supported languages.
|
||||
/// Tests for the Markdown exporter. Mutates the global
|
||||
/// <see cref="Resources.Culture"/>, therefore marked do-not-parallelize.
|
||||
/// Expected documents are assembled from the same ResX template keys as the
|
||||
/// exporter (plus fixed fixture values), so no localized text is hard-coded
|
||||
/// here.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[DoNotParallelize]
|
||||
public class MarkdownExporterTests
|
||||
{
|
||||
public class MarkdownExporterTests {
|
||||
private static readonly DateTimeOffset ExportedAt = new(2026, 9, 30, 14, 25, 37, TimeSpan.Zero);
|
||||
|
||||
/// <summary>A local wall-clock moment, matching the exporter's conversion path.</summary>
|
||||
/// <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) =>
|
||||
new DateTimeOffset(new DateTime(year, month, day, hour, minute, 0)).ToLocalTime();
|
||||
|
||||
/// <summary>Unix seconds for a local wall-clock time.</summary>
|
||||
/// <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) =>
|
||||
Local(year, month, day, hour, minute).ToUnixTimeSeconds();
|
||||
|
||||
/// <summary>Builds the board fixture: one working column with two cards, one empty column, two tags.</summary>
|
||||
private static (IReadOnlyList<ColumnModel> Columns, IReadOnlyList<CardModel> Cards, IReadOnlyList<(TagModel, long)> Tags) CreateBoard()
|
||||
{
|
||||
/// <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() {
|
||||
long created = UnixTimeOf(2026, 9, 1, 10, 0);
|
||||
long updated = UnixTimeOf(2026, 9, 28, 18, 30);
|
||||
|
||||
@@ -45,126 +66,180 @@ public class MarkdownExporterTests
|
||||
return (columns, cards, tags);
|
||||
}
|
||||
|
||||
private static string Export(CultureInfo culture)
|
||||
{
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
Resources.Culture = culture;
|
||||
/// <summary>
|
||||
/// 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);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Resources.Culture = original;
|
||||
}
|
||||
|
||||
/// <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 CRLF line endings so expected and actual compare consistently.
|
||||
/// </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");
|
||||
|
||||
[TestMethod]
|
||||
public void EnglishOutputMatchesTemplate()
|
||||
{
|
||||
string created = Local(2026, 9, 1, 10, 0).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
|
||||
string updated = Local(2026, 9, 28, 18, 30).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
|
||||
|
||||
string expected = Normalize($"""
|
||||
# MyRepo
|
||||
> Exported at: 2026-09-30 14:25:37
|
||||
|
||||
## Column: In Progress (2)
|
||||
The work column
|
||||
|
||||
### #61 Fix login
|
||||
Body text
|
||||
- Tags: `bug` `ui`
|
||||
- Created: {created} Modified: {updated}
|
||||
|
||||
### #62
|
||||
- Created: {created} Modified: {updated}
|
||||
|
||||
## Column: Empty (0)
|
||||
|
||||
## Tags
|
||||
| Name | Color | Description | Usage |
|
||||
|---|---|---|---|
|
||||
| bug | #ff0000 | | 1 |
|
||||
| ui | #00ff00 | Interface work | 1 |
|
||||
""");
|
||||
|
||||
Assert.AreEqual(expected + "\n", Normalize(Export(new CultureInfo("en"))));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ChineseOutputMatchesTemplate()
|
||||
{
|
||||
var chinese = new CultureInfo("zh-Hans");
|
||||
string created = Local(2026, 9, 1, 10, 0).ToString("yyyy年M月d日 HH:mm", chinese);
|
||||
string updated = Local(2026, 9, 28, 18, 30).ToString("yyyy年M月d日 HH:mm", chinese);
|
||||
|
||||
string expected = Normalize($"""
|
||||
# MyRepo
|
||||
> 导出时间:2026年9月30日 14:25
|
||||
|
||||
## 列:In Progress(2)
|
||||
The work column
|
||||
|
||||
### #61 Fix login
|
||||
Body text
|
||||
- 标签:`bug` `ui`
|
||||
- 创建:{created} 修改:{updated}
|
||||
|
||||
### #62
|
||||
- 创建:{created} 修改:{updated}
|
||||
|
||||
## 列:Empty(0)
|
||||
|
||||
## 标签总表
|
||||
| 名称 | 颜色 | 描述 | 使用数 |
|
||||
|---|---|---|---|
|
||||
| bug | #ff0000 | | 1 |
|
||||
| ui | #00ff00 | Interface work | 1 |
|
||||
""");
|
||||
|
||||
Assert.AreEqual(expected + "\n", Normalize(Export(new CultureInfo("zh-Hans"))));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FileNameFollowsLanguage()
|
||||
{
|
||||
/// <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;
|
||||
try
|
||||
{
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
Assert.AreEqual("MyRepo-export-20260930-142537.md", MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
|
||||
|
||||
Resources.Culture = new CultureInfo("zh-Hans");
|
||||
Assert.AreEqual("MyRepo-导出-20260930-142537.md", MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
|
||||
}
|
||||
finally
|
||||
{
|
||||
try {
|
||||
Resources.Culture = culture;
|
||||
Assert.AreEqual(Normalize(BuildExpected(culture)), Normalize(ExportBoard()));
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagTableCellsEscapePipesAndLineBreaks()
|
||||
{
|
||||
public void EnglishOutputMatchesTemplate() {
|
||||
AssertOutputMatches(new CultureInfo("en"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ChineseOutputMatchesTemplate() {
|
||||
AssertOutputMatches(new CultureInfo("zh-Hans"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FileNameFollowsLanguage() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
Assert.AreEqual(
|
||||
string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt),
|
||||
MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
|
||||
|
||||
Resources.Culture = new CultureInfo("zh-Hans");
|
||||
Assert.AreEqual(
|
||||
string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt),
|
||||
MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagTableCellsEscapePipesAndLineBreaks() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
var tag = new TagModel(1, "a|b", RgbColor.Parse("#112233"), "first\nsecond");
|
||||
string markdown = MarkdownExporter.Export("W",
|
||||
string markdown = MarkdownExporter.Export(
|
||||
"W",
|
||||
[new ColumnModel(1, "C", string.Empty, 1, 1)],
|
||||
[],
|
||||
[(tag, 0L)],
|
||||
ExportedAt);
|
||||
|
||||
StringAssert.Contains(markdown, "| a\\|b | #112233 | first second | 0 |");
|
||||
StringAssert.Contains(markdown, "| a\\|b | #112233 | first<br>second | 0 |");
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
finally
|
||||
{
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagTableCellsEscapeBackslashes() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
var tag = new TagModel(1, "a\\b", RgbColor.Parse("#112233"), "c\\|d");
|
||||
string markdown = MarkdownExporter.Export(
|
||||
"W",
|
||||
[new ColumnModel(1, "C", string.Empty, 1, 1)],
|
||||
[],
|
||||
[(tag, 0L)],
|
||||
ExportedAt);
|
||||
|
||||
StringAssert.Contains(markdown, "| a\\\\b | #112233 | c\\\\\\|d | 0 |");
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagNameWithBacktickUsesLongerFence() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
var tag = new TagModel(1, "a`b", RgbColor.Parse("#112233"), string.Empty);
|
||||
string markdown = MarkdownExporter.Export(
|
||||
"W",
|
||||
[new ColumnModel(1, "C", string.Empty, 1, 1)],
|
||||
[new CardModel(1, 1, "T", string.Empty, 1, 1, [tag])],
|
||||
[(tag, 1L)],
|
||||
ExportedAt);
|
||||
|
||||
StringAssert.Contains(markdown, "``a`b``");
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FileNameDropsInvalidCharactersAndFallsBackToAppName() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
|
||||
// A drive root workspace name "D:\" must not leak ':' or '\' into the file name.
|
||||
string name = MarkdownExporter.BuildFileName("D:\\", ExportedAt);
|
||||
Assert.IsFalse(name.Contains(':'));
|
||||
Assert.IsFalse(name.Contains('\\'));
|
||||
|
||||
// A name made only of invalid characters falls back to the application name.
|
||||
string fallback = MarkdownExporter.BuildFileName("///", ExportedAt);
|
||||
StringAssert.StartsWith(fallback, Resources.App_Name);
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
using YKanBan.Launching;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
|
||||
namespace YKanBan.Tests.Launching;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the <c>ykanban <path></c> command-line contract: exactly one
|
||||
/// existing folder, resolved to an absolute path; everything else is rejected.
|
||||
/// </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]
|
||||
[DataRow("--help")]
|
||||
[DataRow("-x")]
|
||||
public void OptionLikeArgumentIsRejected(string argument) {
|
||||
Assert.IsFalse(LaunchArguments.TryParse([argument], out string? path));
|
||||
Assert.IsNull(path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NonExistentFolderIsRejected() {
|
||||
using var directory = new TempDirectory();
|
||||
string missing = Path.Combine(directory.FullPath, "nope");
|
||||
|
||||
Assert.IsFalse(LaunchArguments.TryParse([missing], out string? path));
|
||||
Assert.IsNull(path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FileInsteadOfFolderIsRejected() {
|
||||
using var directory = new TempDirectory();
|
||||
string file = Path.Combine(directory.FullPath, "file.txt");
|
||||
File.WriteAllText(file, "x");
|
||||
|
||||
Assert.IsFalse(LaunchArguments.TryParse([file], out string? path));
|
||||
Assert.IsNull(path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ExistingFolderIsAcceptedAsAnAbsolutePath() {
|
||||
using var directory = new TempDirectory();
|
||||
|
||||
bool parsed = LaunchArguments.TryParse([directory.FullPath], out string? path);
|
||||
|
||||
Assert.IsTrue(parsed);
|
||||
Assert.AreEqual(Path.GetFullPath(directory.FullPath), path);
|
||||
Assert.IsTrue(Path.IsPathRooted(path));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void RelativePathIsResolvedToAbsolute() {
|
||||
using var directory = new TempDirectory();
|
||||
string relative = Path.GetRelativePath(Environment.CurrentDirectory, directory.FullPath);
|
||||
|
||||
bool parsed = LaunchArguments.TryParse([relative], out string? path);
|
||||
|
||||
Assert.IsTrue(parsed);
|
||||
Assert.IsTrue(Path.IsPathRooted(path));
|
||||
Assert.AreEqual(Path.GetFullPath(relative), path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MalformedPathIsRejected() {
|
||||
Assert.IsFalse(LaunchArguments.TryParse(["bad\0path"], out string? path));
|
||||
Assert.IsNull(path);
|
||||
}
|
||||
}
|
||||
@@ -2,71 +2,67 @@ using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.Tests.Models;
|
||||
|
||||
/// <summary>Tests for the RGB color value type and its #RRGGBB text conversions.</summary>
|
||||
/// <summary>
|
||||
/// Tests for the RGB color value type: component storage and the text
|
||||
/// boundary in both directions.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class RgbColorTests
|
||||
{
|
||||
public class RgbColorTests {
|
||||
[TestMethod]
|
||||
public void ParseExtractsComponents()
|
||||
{
|
||||
RgbColor color = RgbColor.Parse("#ff0a00");
|
||||
Assert.AreEqual(new RgbColor(0xFF, 0x0A, 0x00), color);
|
||||
public void ParseSplitsComponents() {
|
||||
RgbColor color = RgbColor.Parse("#102030");
|
||||
Assert.AreEqual((byte)0x10, color.R);
|
||||
Assert.AreEqual((byte)0x20, color.G);
|
||||
Assert.AreEqual((byte)0x30, color.B);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParseAcceptsUppercaseAndMixedCaseHex()
|
||||
{
|
||||
Assert.AreEqual(new RgbColor(0xAB, 0xCD, 0xEF), RgbColor.Parse("#ABCDEF"));
|
||||
Assert.AreEqual(new RgbColor(0xAB, 0xCD, 0xEF), RgbColor.Parse("#aBcDeF"));
|
||||
[DataRow("#a1B2c3")]
|
||||
[DataRow("#A1B2C3")]
|
||||
[DataRow("#a1b2c3")]
|
||||
public void ParseIsCaseInsensitive(string text) {
|
||||
Assert.AreEqual(new RgbColor(0xA1, 0xB2, 0xC3), RgbColor.Parse(text));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("ff0000")]
|
||||
[DataRow("#ff000")]
|
||||
[DataRow("#ff00000")]
|
||||
[DataRow("#gg0000")]
|
||||
[DataRow("#ff 000")]
|
||||
[DataRow(" #ff0000")]
|
||||
[DataRow("#ff0000 ")]
|
||||
[DataRow("#")]
|
||||
[DataRow("")]
|
||||
public void TryParseRejectsMalformedText(string text)
|
||||
{
|
||||
Assert.IsFalse(RgbColor.TryParse(text, out _));
|
||||
[DataRow("112233")]
|
||||
[DataRow("#11223")]
|
||||
[DataRow("#1122334")]
|
||||
[DataRow("#GGGGGG")]
|
||||
[DataRow("#12345g")]
|
||||
[DataRow(" #112233")]
|
||||
[DataRow("#112233 ")]
|
||||
public void ParseRejectsMalformedText(string text) {
|
||||
Assert.ThrowsExactly<FormatException>(() => RgbColor.Parse(text));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TryParseRejectsNull()
|
||||
{
|
||||
Assert.IsFalse(RgbColor.TryParse(null, out _));
|
||||
public void TryParseRejectsNull() {
|
||||
Assert.IsFalse(RgbColor.TryParse(null, out RgbColor color));
|
||||
Assert.AreEqual(default, color);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParseThrowsFormatExceptionForMalformedText()
|
||||
{
|
||||
Assert.ThrowsExactly<FormatException>(() => RgbColor.Parse("red"));
|
||||
public void TryParseAcceptsValidText() {
|
||||
Assert.IsTrue(RgbColor.TryParse("#010203", out RgbColor color));
|
||||
Assert.AreEqual(new RgbColor(1, 2, 3), color);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ToStringProducesCanonicalLowercaseForm()
|
||||
{
|
||||
Assert.AreEqual("#ee0a0a", new RgbColor(0xEE, 0x0A, 0x0A).ToString());
|
||||
|
||||
// Uppercase input normalizes to the canonical lowercase output.
|
||||
Assert.AreEqual("#ee0a0a", RgbColor.Parse("#EE0A0A").ToString());
|
||||
public void ToStringUsesCanonicalLowercase() {
|
||||
Assert.AreEqual("#ff0a00", new RgbColor(0xFF, 0x0A, 0x00).ToString());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EqualityComparesComponents()
|
||||
{
|
||||
Assert.AreEqual(RgbColor.Parse("#ff0000"), RgbColor.Parse("#FF0000"));
|
||||
Assert.AreNotEqual(RgbColor.Parse("#ff0000"), RgbColor.Parse("#ff0001"));
|
||||
public void TextRoundTrips() {
|
||||
var color = new RgbColor(0x12, 0xAB, 0xCD);
|
||||
Assert.AreEqual(color, RgbColor.Parse(color.ToString()));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TextRoundTripPreservesColor()
|
||||
{
|
||||
RgbColor original = new(0x12, 0x34, 0x56);
|
||||
Assert.AreEqual(original, RgbColor.Parse(original.ToString()));
|
||||
public void EqualityComparesComponents() {
|
||||
Assert.AreEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 3));
|
||||
Assert.AreNotEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 4));
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -3,30 +3,31 @@ using YKanBan.Search;
|
||||
namespace YKanBan.Tests.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Structural comparer for search AST nodes, used by assertions only. The
|
||||
/// AST records compare by reference for their Terms collections by design
|
||||
/// (see the YYC MARK note in SearchNodes.cs), so tests provide equality
|
||||
/// explicitly.
|
||||
/// Structural comparer for search AST nodes, used by assertions only. The AST
|
||||
/// records compare by reference for their Terms collections by design (see the
|
||||
/// YYC MARK note in SearchNodes.cs), so tests provide equality explicitly.
|
||||
/// </summary>
|
||||
public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
|
||||
{
|
||||
/// <summary>Shared comparer instance.</summary>
|
||||
public sealed class SearchNodeComparer : IEqualityComparer<SearchNode> {
|
||||
/// <summary>
|
||||
/// Gets the shared comparer instance.
|
||||
/// </summary>
|
||||
public static SearchNodeComparer Instance { get; } = new();
|
||||
|
||||
/// <summary>Determines structural equality of two nodes.</summary>
|
||||
public bool Equals(SearchNode? x, SearchNode? y)
|
||||
{
|
||||
if (ReferenceEquals(x, y))
|
||||
{
|
||||
/// <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) {
|
||||
if (ReferenceEquals(x, y)) {
|
||||
return true;
|
||||
}
|
||||
if (x is null || y is null || x.GetType() != y.GetType())
|
||||
{
|
||||
if (x is null || y is null || x.GetType() != y.GetType()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (x, y) switch
|
||||
{
|
||||
return (x, y) switch {
|
||||
(SearchNode.Or a, SearchNode.Or b) => SequencesEqual(a.Terms, b.Terms),
|
||||
(SearchNode.And a, SearchNode.And b) => SequencesEqual(a.Terms, b.Terms),
|
||||
(SearchNode.FreeText a, SearchNode.FreeText b) => a.Text == b.Text,
|
||||
@@ -38,17 +39,24 @@ public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Not supported: the comparer exists for assertions, not hashing.</summary>
|
||||
/// <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) =>
|
||||
throw new NotSupportedException("Structural comparison for assertions only; hashing is not supported.");
|
||||
|
||||
/// <summary>Order-sensitive element-wise comparison.</summary>
|
||||
private static bool SequencesEqual(IReadOnlyList<SearchNode> x, IReadOnlyList<SearchNode> y)
|
||||
{
|
||||
if (x.Count != y.Count)
|
||||
{
|
||||
/// <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) {
|
||||
if (x.Count != y.Count) {
|
||||
return false;
|
||||
}
|
||||
return Enumerable.Zip(x, y, (a, b) => (a, b)).All(pair => Instance.Equals(pair.a, pair.b));
|
||||
return x.Zip(y).All(pair => Instance.Equals(pair.First, pair.Second));
|
||||
}
|
||||
}
|
||||
@@ -4,65 +4,66 @@ namespace YKanBan.Tests.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the search parser: the full grammar branches plus the strict
|
||||
/// failure behavior (malformed input always throws SearchSyntaxException).
|
||||
/// failure behavior (malformed input always throws
|
||||
/// <see cref="SearchSyntaxException"/>).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class SearchQueryParserTests
|
||||
{
|
||||
/// <summary>Parses and asserts structural equality against the expected AST.</summary>
|
||||
private static void AssertParsesTo(SearchNode expected, string text)
|
||||
{
|
||||
public class SearchQueryParserTests {
|
||||
/// <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) {
|
||||
SearchNode? parsed = SearchQueryParser.Parse(text);
|
||||
Assert.IsNotNull(parsed, $"Blank-looking input: '{text}'.");
|
||||
Assert.AreEqual(expected, parsed, SearchNodeComparer.Instance);
|
||||
}
|
||||
|
||||
/// <summary>Asserts that the input violates the grammar.</summary>
|
||||
private static void AssertSyntaxError(string text)
|
||||
{
|
||||
/// <summary>
|
||||
/// Asserts that the input violates the grammar.
|
||||
/// </summary>
|
||||
/// <param name="text">The search text.</param>
|
||||
private static void AssertSyntaxError(string text) {
|
||||
Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse(text));
|
||||
}
|
||||
|
||||
#region Successful parses
|
||||
|
||||
[TestMethod]
|
||||
public void BlankInputReturnsNull()
|
||||
{
|
||||
public void BlankInputReturnsNull() {
|
||||
Assert.IsNull(SearchQueryParser.Parse(string.Empty));
|
||||
Assert.IsNull(SearchQueryParser.Parse(" "));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SingleWordIsFreeText()
|
||||
{
|
||||
public void SingleWordIsFreeText() {
|
||||
AssertParsesTo(new SearchNode.FreeText("login"), "login");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AdjacentWordsAreImplicitAnd()
|
||||
{
|
||||
public void AdjacentWordsAreImplicitAnd() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([new SearchNode.FreeText("fix"), new SearchNode.FreeText("login")]),
|
||||
"fix login");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ExplicitAndKeyword()
|
||||
{
|
||||
public void ExplicitAndKeyword() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||
"a AND b");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OrKeyword()
|
||||
{
|
||||
public void OrKeyword() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||
"a OR b");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ImplicitAndBindsTighterThanOr()
|
||||
{
|
||||
public void ImplicitAndBindsTighterThanOr() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.Or([
|
||||
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||
@@ -71,8 +72,7 @@ public class SearchQueryParserTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParenthesesForceGrouping()
|
||||
{
|
||||
public void ParenthesesForceGrouping() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([
|
||||
new SearchNode.FreeText("a"),
|
||||
@@ -81,16 +81,14 @@ public class SearchQueryParserTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NestedParenthesesCollapse()
|
||||
{
|
||||
public void NestedParenthesesCollapse() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||
"((a OR b))");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LowercaseKeywordsArePlainWords()
|
||||
{
|
||||
public void LowercaseKeywordsArePlainWords() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([
|
||||
new SearchNode.FreeText("a"),
|
||||
@@ -101,122 +99,238 @@ public class SearchQueryParserTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PhraseIsFreeText()
|
||||
{
|
||||
public void PhraseIsFreeText() {
|
||||
AssertParsesTo(new SearchNode.FreeText("hello world"), "\"hello world\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PhraseSupportsEscapes()
|
||||
{
|
||||
// Escaped quote, escaped backslash, and a lone backslash kept literally.
|
||||
AssertParsesTo(new SearchNode.FreeText("a\"b"), "\"a\\\"b\"");
|
||||
AssertParsesTo(new SearchNode.FreeText("a\\b"), "\"a\\\\b\"");
|
||||
AssertParsesTo(new SearchNode.FreeText("C:\\x"), "\"C:\\x\"");
|
||||
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]
|
||||
public void TagQualifier()
|
||||
{
|
||||
public void PhraseSupportsEscapes() {
|
||||
// Escaped quote and escaped backslash.
|
||||
AssertParsesTo(new SearchNode.FreeText("a\"b"), "\"a\\\"b\"");
|
||||
AssertParsesTo(new SearchNode.FreeText("a\\b"), "\"a\\\\b\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagQualifier() {
|
||||
AssertParsesTo(new SearchNode.TagName("bug"), "tag:bug");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagQualifierAcceptsPhraseValue()
|
||||
{
|
||||
public void TagQualifierAcceptsPhraseValue() {
|
||||
AssertParsesTo(new SearchNode.TagName("a b"), "tag:\"a b\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TitleAndContentQualifiers()
|
||||
{
|
||||
public void QuotedQualifierValueMayContainColonsAndOperators() {
|
||||
AssertParsesTo(new SearchNode.TagName("a:b"), "tag:\"a:b\"");
|
||||
AssertParsesTo(new SearchNode.TagName("AND"), "tag:\"AND\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TitleAndContentQualifiers() {
|
||||
AssertParsesTo(new SearchNode.FieldText(SearchField.Title, "foo"), "title:foo");
|
||||
AssertParsesTo(new SearchNode.FieldText(SearchField.Content, "foo"), "content:foo");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnQualifierAcceptsPhraseValue()
|
||||
{
|
||||
public void ColumnQualifierAcceptsPhraseValue() {
|
||||
AssertParsesTo(new SearchNode.ColumnTitle("To Do"), "column:\"To Do\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void IdQualifierParsesNumber()
|
||||
{
|
||||
public void IdQualifierParsesNumber() {
|
||||
AssertParsesTo(new SearchNode.CardId(42), "id:42");
|
||||
AssertParsesTo(new SearchNode.CardId(12), "id:\"12\"");
|
||||
AssertParsesTo(new SearchNode.CardId(61), "id:#61");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void QualifierKeysAreCaseSensitive()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.FreeText("Tag:x"), "Tag:x");
|
||||
public void QuotedTextWithColonIsFreeText() {
|
||||
AssertParsesTo(new SearchNode.FreeText("http://x"), "\"http://x\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnterminatedPhraseIsAnError()
|
||||
{
|
||||
public void WordMayContainHashAndPunctuation() {
|
||||
AssertParsesTo(new SearchNode.FreeText("#61"), "#61");
|
||||
AssertParsesTo(new SearchNode.FreeText("c#/.net"), "c#/.net");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Strict failures
|
||||
|
||||
[TestMethod]
|
||||
public void UnterminatedPhraseIsAnError() {
|
||||
AssertSyntaxError("\"abc def");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnbalancedOpenParenIsAnError()
|
||||
{
|
||||
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]
|
||||
public void UnbalancedOpenParenIsAnError() {
|
||||
AssertSyntaxError("(a");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void StrayCloseParenIsAnError()
|
||||
{
|
||||
public void StrayCloseParenIsAnError() {
|
||||
AssertSyntaxError("a)");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EmptyParensAreAnError()
|
||||
{
|
||||
public void EmptyParensAreAnError() {
|
||||
AssertSyntaxError("()");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DanglingOrIsAnError()
|
||||
{
|
||||
public void DanglingOrIsAnError() {
|
||||
AssertSyntaxError("a OR");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DanglingAndIsAnError()
|
||||
{
|
||||
public void DanglingAndIsAnError() {
|
||||
AssertSyntaxError("a AND");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LeadingAndIsAnError()
|
||||
{
|
||||
public void LeadingAndIsAnError() {
|
||||
AssertSyntaxError("AND a");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OperatorAtOperandPositionIsAnError()
|
||||
{
|
||||
public void OperatorAtOperandPositionIsAnError() {
|
||||
AssertSyntaxError("a AND OR b");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void QualifierWithoutValueIsAnError()
|
||||
{
|
||||
public void QualifierWithoutValueIsAnError() {
|
||||
AssertSyntaxError("tag:");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NonNumericIdIsAnError()
|
||||
{
|
||||
AssertSyntaxError("id:12x");
|
||||
public void SpacedQualifierValueIsAnError() {
|
||||
AssertSyntaxError("tag: bug");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SyntaxErrorCarriesDescriptiveMessage()
|
||||
{
|
||||
SearchSyntaxException ex = Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse("a AND"));
|
||||
Assert.IsFalse(string.IsNullOrEmpty(ex.Message));
|
||||
[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]
|
||||
public void SyntaxErrorCarriesDescriptiveMessage() {
|
||||
SearchSyntaxException exception = Assert.ThrowsExactly<SearchSyntaxException>(
|
||||
() => SearchQueryParser.Parse("a AND"));
|
||||
Assert.IsFalse(string.IsNullOrEmpty(exception.Message));
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -1,39 +1,39 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Search;
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
|
||||
namespace YKanBan.Tests.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the query-to-SQL compiler, executed end-to-end against a
|
||||
/// fixture workspace database.
|
||||
/// Tests for the query-to-SQL compiler, executed end-to-end against a fixture
|
||||
/// workspace database.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class SearchSqlCompilerTests
|
||||
{
|
||||
/// <summary>Owns a workspace with a fixed card/tag fixture.</summary>
|
||||
private sealed class SearchFixture : IDisposable
|
||||
{
|
||||
public class SearchSqlCompilerTests {
|
||||
/// <summary>
|
||||
/// Owns a workspace with a fixed card/tag fixture.
|
||||
/// </summary>
|
||||
private sealed class SearchFixture : IDisposable {
|
||||
public TempDirectory Directory { get; } = new();
|
||||
|
||||
public SqliteConnection Connection { get; }
|
||||
|
||||
public SearchFixture()
|
||||
{
|
||||
public SearchFixture() {
|
||||
WorkspaceInitializer.Initialize(Directory.FullPath);
|
||||
using (SqliteConnection setup = SqliteTestHelper.OpenWorkspace(Directory.FullPath))
|
||||
{
|
||||
using (SqliteConnection setup = SqliteTestHelper.OpenWorkspace(Directory.FullPath)) {
|
||||
// Columns: 1 "To Do", 2 "In Progress".
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('To Do', '', 1, 1);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('In Progress', '', 1, 1);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Archive', '', 1, 1);");
|
||||
|
||||
// Cards: 1 titled, 2 title-or-content matches, 3 untitled, 4 wildcard chars.
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, 'Fix login', 'Cannot sign in', 1, 1);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (2, 'Green apple', 'the apple pie', 1, 1);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (2, '', 'banana split', 1, 1);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, '100% done', 'a_b test', 1, 1);");
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (3, 'ÄÖÜ Straße', '', 1, 1);");
|
||||
|
||||
// Tags: mixed case names plus one containing spaces.
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO tags (name, color, description) VALUES ('Bug', '#ff0000', '');");
|
||||
@@ -48,39 +48,38 @@ public class SearchSqlCompilerTests
|
||||
Connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath);
|
||||
}
|
||||
|
||||
/// <summary>Runs a query and returns the ids of the matching cards.</summary>
|
||||
public List<long> Search(string queryText)
|
||||
{
|
||||
/// <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) {
|
||||
SearchNode? query = SearchQueryParser.Parse(queryText);
|
||||
Assert.IsNotNull(query, "Blank fixture queries are not expected here.");
|
||||
CompiledSearch compiled = SearchSqlCompiler.Compile(query);
|
||||
|
||||
using var command = Connection.CreateCommand();
|
||||
command.CommandText = $"SELECT c.id FROM cards c WHERE {compiled.Predicate} ORDER BY c.id ASC;";
|
||||
foreach ((string name, object value) in compiled.Parameters)
|
||||
{
|
||||
foreach ((string name, object value) in compiled.Parameters) {
|
||||
command.Parameters.AddWithValue(name, value);
|
||||
}
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var ids = new List<long>();
|
||||
while (reader.Read())
|
||||
{
|
||||
while (reader.Read()) {
|
||||
ids.Add(reader.GetInt64(0));
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
public void Dispose() {
|
||||
Connection.Dispose();
|
||||
Directory.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FreeTextMatchesTitleOrContentCaseInsensitively()
|
||||
{
|
||||
public void FreeTextMatchesTitleOrContentCaseInsensitively() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple"));
|
||||
CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("login"));
|
||||
@@ -89,8 +88,7 @@ public class SearchSqlCompilerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FieldQualifiersScopeToTheirField()
|
||||
{
|
||||
public void FieldQualifiersScopeToTheirField() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("title:apple"));
|
||||
CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("content:banana"));
|
||||
@@ -98,8 +96,7 @@ public class SearchSqlCompilerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagQualifierMatchesExactlyAndCaseInsensitively()
|
||||
{
|
||||
public void TagQualifierMatchesExactlyAndCaseInsensitively() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("tag:bug"));
|
||||
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("tag:ui"));
|
||||
@@ -111,8 +108,7 @@ public class SearchSqlCompilerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnQualifierMatchesColumnTitleExactly()
|
||||
{
|
||||
public void ColumnQualifierMatchesColumnTitleExactly() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 1L, 4L }, fixture.Search("column:\"to do\""));
|
||||
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("column:\"in progress\""));
|
||||
@@ -123,16 +119,14 @@ public class SearchSqlCompilerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void IdQualifierMatchesExactly()
|
||||
{
|
||||
public void IdQualifierMatchesExactly() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("id:3"));
|
||||
Assert.AreEqual(0, fixture.Search("id:99").Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AndOrCombination()
|
||||
{
|
||||
public void AndOrCombination() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("apple OR banana"));
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple AND id:2"));
|
||||
@@ -140,8 +134,7 @@ public class SearchSqlCompilerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParenthesizedGrouping()
|
||||
{
|
||||
public void ParenthesizedGrouping() {
|
||||
using var fixture = new SearchFixture();
|
||||
|
||||
// (apple OR banana) hits cards 2,3; intersected with column "In Progress" (2,3).
|
||||
@@ -152,22 +145,27 @@ public class SearchSqlCompilerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LikeWildcardsInUserTextMatchLiterally()
|
||||
{
|
||||
public void PercentAndUnderscoreInUserTextMatchLiterally() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("100%"));
|
||||
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("a_b"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CompiledPredicateUsesNamedParameters()
|
||||
{
|
||||
public void UnicodeCaseFoldingMatchesNonAscii() {
|
||||
using var fixture = new SearchFixture();
|
||||
|
||||
// SQLite's LIKE would only fold ASCII; the ykb_fold function folds these too.
|
||||
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("äöü"));
|
||||
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("straße"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CompiledPredicateUsesNamedParameters() {
|
||||
CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("x"));
|
||||
|
||||
StringAssert.Contains(compiled.Predicate, "$p0");
|
||||
StringAssert.Contains(compiled.Predicate, "$p1");
|
||||
Assert.AreEqual(2, compiled.Parameters.Count);
|
||||
Assert.AreEqual("%x%", compiled.Parameters[0].Value);
|
||||
Assert.AreEqual("%x%", compiled.Parameters[1].Value);
|
||||
Assert.AreEqual(1, compiled.Parameters.Count);
|
||||
Assert.AreEqual("x", compiled.Parameters[0].Value);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
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,24 +3,26 @@ using YKanBan.Tests.TestUtilities;
|
||||
|
||||
namespace YKanBan.Tests.Storage.AppData;
|
||||
|
||||
/// <summary>Tests for app.json load/save and its degradation rules.</summary>
|
||||
/// <summary>
|
||||
/// Tests for app.json round-tripping, kebab-case naming and graceful
|
||||
/// degradation on a missing or corrupt file.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class AppConfigStoreTests
|
||||
{
|
||||
public class AppConfigStoreTests {
|
||||
[TestMethod]
|
||||
public void MissingFileYieldsDefaults()
|
||||
{
|
||||
public void LoadMissingFileReturnsDefaults() {
|
||||
using var directory = new TempDirectory();
|
||||
var store = new AppConfigStore(Path.Combine(directory.FullPath, "app.json"));
|
||||
|
||||
AppConfig config = store.Load();
|
||||
|
||||
Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version);
|
||||
Assert.AreEqual("en", config.Language);
|
||||
Assert.AreEqual(AppConfig.DefaultLanguage, config.Language);
|
||||
Assert.AreEqual(ThemeOption.FollowSystem, config.Theme);
|
||||
Assert.AreEqual(CardSortOption.Id, config.Sort.Card);
|
||||
Assert.AreEqual(SidebarSortOption.NameAsc, config.Sort.Sidebar);
|
||||
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset);
|
||||
Assert.AreEqual(320, config.ColumnWidth.CustomPixels);
|
||||
Assert.AreEqual(SortOption.IdAscending, config.Display.CardSort);
|
||||
Assert.AreEqual(SortOption.IdAscending, config.Display.ColumnSort);
|
||||
Assert.AreEqual(ColumnWidthPreset.Standard, config.Display.ColumnWidth.Preset);
|
||||
Assert.AreEqual(320, config.Display.ColumnWidth.CustomPixels);
|
||||
Assert.IsTrue(config.Confirmations.DeleteCard);
|
||||
Assert.IsTrue(config.Confirmations.DeleteColumn);
|
||||
Assert.IsTrue(config.Confirmations.DeleteTag);
|
||||
@@ -28,136 +30,82 @@ public class AppConfigStoreTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CorruptJsonIsBackedUpAndDefaultsAreUsed()
|
||||
{
|
||||
public void LoadCorruptFileBacksUpAndReturnsDefaults() {
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.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]");
|
||||
File.WriteAllText(path, "{ this is not valid json");
|
||||
var store = new AppConfigStore(path);
|
||||
|
||||
AppConfig config = store.Load();
|
||||
|
||||
Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version);
|
||||
Assert.IsTrue(File.Exists(path + ".bak"));
|
||||
Assert.AreEqual("{ this is not valid json", File.ReadAllText(path + ".bak"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
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()
|
||||
{
|
||||
public void LoadJsonNullReturnsDefaults() {
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
File.WriteAllText(path, "null");
|
||||
var store = new AppConfigStore(path);
|
||||
|
||||
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"));
|
||||
Assert.AreEqual(AppConfig.CurrentFormatVersion, store.Load().Version);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MissingSectionsFallBackToTheirDefaults()
|
||||
{
|
||||
public void LoadNumericEnumValueIsRejectedAndBackedUp() {
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
File.WriteAllText(path, $$"""
|
||||
{
|
||||
"version": {{AppConfig.CurrentFormatVersion}},
|
||||
"language": "zh-Hans"
|
||||
}
|
||||
""");
|
||||
|
||||
// Integer enum values are not accepted; the file is treated like corrupt.
|
||||
File.WriteAllText(path, """{ "theme": 1 }""");
|
||||
var store = new AppConfigStore(path);
|
||||
|
||||
AppConfig config = store.Load();
|
||||
|
||||
// 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);
|
||||
Assert.AreEqual(ThemeOption.FollowSystem, config.Theme);
|
||||
Assert.IsTrue(File.Exists(path + ".bak"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LoadPreservesUnknownFieldsTolerantly()
|
||||
{
|
||||
public void LoadUnreadableFileReturnsDefaults() {
|
||||
// File sharing is only reliably enforced on Windows, so this branch is exercised there.
|
||||
if (!OperatingSystem.IsWindows()) {
|
||||
return;
|
||||
}
|
||||
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
File.WriteAllText(path, """{ "version": 1 }""");
|
||||
|
||||
// Hold the file exclusively so the store's read fails with an I/O error.
|
||||
using FileStream hold = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None);
|
||||
var store = new AppConfigStore(path);
|
||||
|
||||
Assert.AreEqual(AppConfig.CurrentFormatVersion, store.Load().Version);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LoadReadsKebabCaseKeysAndEnumValues() {
|
||||
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
|
||||
"theme": "dark",
|
||||
"display": {
|
||||
"column-width": { "preset": "custom", "custom-pixels": 400 },
|
||||
"card-sort": "title-asc",
|
||||
"column-sort": "id-desc"
|
||||
},
|
||||
"confirmations": {
|
||||
"delete-card": false,
|
||||
"delete-column": false,
|
||||
"delete-tag": false,
|
||||
"discard-edit": false
|
||||
}
|
||||
}
|
||||
""");
|
||||
var store = new AppConfigStore(path);
|
||||
@@ -165,5 +113,87 @@ public class AppConfigStoreTests
|
||||
AppConfig config = store.Load();
|
||||
|
||||
Assert.AreEqual("zh-Hans", config.Language);
|
||||
Assert.AreEqual(ThemeOption.Dark, config.Theme);
|
||||
Assert.AreEqual(SortOption.TitleAscending, config.Display.CardSort);
|
||||
Assert.AreEqual(SortOption.IdDescending, config.Display.ColumnSort);
|
||||
Assert.AreEqual(ColumnWidthPreset.Custom, config.Display.ColumnWidth.Preset);
|
||||
Assert.AreEqual(400, config.Display.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.Display);
|
||||
Assert.IsNotNull(config.Display.ColumnWidth);
|
||||
Assert.IsNotNull(config.Confirmations);
|
||||
Assert.AreEqual(ColumnWidthPreset.Standard, config.Display.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,
|
||||
Display = new DisplaySettings {
|
||||
CardSort = SortOption.UpdatedDescending,
|
||||
ColumnSort = SortOption.CreatedAscending,
|
||||
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, "\"card-sort\"");
|
||||
StringAssert.Contains(json, "\"column-sort\"");
|
||||
StringAssert.Contains(json, "\"custom-pixels\"");
|
||||
StringAssert.Contains(json, "\"follow-system\"");
|
||||
StringAssert.Contains(json, "\"updated-desc\"");
|
||||
StringAssert.Contains(json, "\"created-asc\"");
|
||||
// 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,
|
||||
Display = new DisplaySettings {
|
||||
CardSort = SortOption.CreatedDescending,
|
||||
ColumnSort = SortOption.TitleAscending,
|
||||
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.Display.CardSort, reloaded.Display.CardSort);
|
||||
Assert.AreEqual(config.Display.ColumnSort, reloaded.Display.ColumnSort);
|
||||
Assert.AreEqual(config.Display.ColumnWidth.Preset, reloaded.Display.ColumnWidth.Preset);
|
||||
Assert.AreEqual(config.Confirmations.DiscardEdit, reloaded.Confirmations.DiscardEdit);
|
||||
}
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
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;"));
|
||||
}
|
||||
}
|
||||
@@ -1,114 +1,76 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
|
||||
namespace YKanBan.Tests.Storage;
|
||||
|
||||
/// <summary>Tests for PRAGMA application and user_version migration machinery.</summary>
|
||||
/// <summary>
|
||||
/// Tests for the shared SQLite plumbing: mandatory PRAGMAs and the
|
||||
/// user_version-driven migration runner.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
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);"),
|
||||
];
|
||||
|
||||
public class SqliteDatabaseTests {
|
||||
[TestMethod]
|
||||
public void OpenAppliesMandatedPragmas()
|
||||
{
|
||||
public void OpenAppliesMandatoryPragmas() {
|
||||
using var directory = new TempDirectory();
|
||||
string dbPath = Path.Combine(directory.FullPath, "test.db");
|
||||
string databasePath = Path.Combine(directory.FullPath, "pragmas.db");
|
||||
|
||||
using var connection = SqliteDatabase.Open(dbPath, []);
|
||||
using SqliteConnection connection = SqliteDatabase.Open(databasePath, []);
|
||||
Assert.AreEqual("wal", SqliteTestHelper.ScalarString(connection, "PRAGMA journal_mode;"));
|
||||
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "PRAGMA synchronous;"));
|
||||
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "PRAGMA foreign_keys;"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OpenSetsUserVersionToLatestWorkspaceMigration()
|
||||
{
|
||||
public void OpenSetsUserVersionToLatestMigration() {
|
||||
using var directory = new TempDirectory();
|
||||
string dbPath = Path.Combine(directory.FullPath, "test.db");
|
||||
string databasePath = Path.Combine(directory.FullPath, "version.db");
|
||||
|
||||
using var connection = SqliteDatabase.Open(dbPath, WorkspaceSchema.Migrations);
|
||||
using SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations);
|
||||
Assert.AreEqual(WorkspaceSchema.CurrentVersion, SqliteDatabase.ReadUserVersion(connection));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MigrationsApplyIncrementallyOnReopen()
|
||||
{
|
||||
public void ReopenKeepsWalJournalMode() {
|
||||
using var directory = new TempDirectory();
|
||||
string dbPath = Path.Combine(directory.FullPath, "test.db");
|
||||
string databasePath = Path.Combine(directory.FullPath, "wal.db");
|
||||
|
||||
// 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"));
|
||||
using (SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)) {
|
||||
}
|
||||
|
||||
// Reopen with v1+v2: only v2 runs, v1 data untouched.
|
||||
using (var connection = SqliteDatabase.Open(dbPath, V1AndV2))
|
||||
{
|
||||
Assert.AreEqual(2L, SqliteDatabase.ReadUserVersion(connection));
|
||||
Assert.IsTrue(SqliteTestHelper.TableExists(connection, "t1"));
|
||||
Assert.IsTrue(SqliteTestHelper.TableExists(connection, "t2"));
|
||||
}
|
||||
// WAL mode is stored in the database header, so a fresh connection keeps it.
|
||||
using SqliteConnection reopened = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations);
|
||||
Assert.AreEqual("wal", SqliteTestHelper.ScalarString(reopened, "PRAGMA journal_mode;"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ReopenWithCurrentSchemaIsIdempotent()
|
||||
{
|
||||
public void OpenRejectsNewerStoredSchemaVersion() {
|
||||
using var directory = new TempDirectory();
|
||||
string dbPath = Path.Combine(directory.FullPath, "test.db");
|
||||
string databasePath = Path.Combine(directory.FullPath, "newer.db");
|
||||
|
||||
SqliteDatabase.Open(dbPath, V1AndV2).Dispose();
|
||||
using (var connection = SqliteDatabase.Open(dbPath, V1AndV2))
|
||||
{
|
||||
// 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);");
|
||||
long newerVersion = WorkspaceSchema.CurrentVersion + 1;
|
||||
using (SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)) {
|
||||
SqliteTestHelper.Exec(connection, $"PRAGMA user_version={newerVersion};");
|
||||
}
|
||||
|
||||
using (var connection = SqliteDatabase.Open(dbPath, V1AndV2))
|
||||
{
|
||||
Assert.AreEqual(42L, SqliteTestHelper.ScalarLong(connection, "SELECT id FROM t1;"));
|
||||
}
|
||||
SchemaVersionException exception = Assert.ThrowsExactly<SchemaVersionException>(
|
||||
() => SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations));
|
||||
Assert.AreEqual(newerVersion, exception.StoredVersion);
|
||||
Assert.AreEqual(WorkspaceSchema.CurrentVersion, exception.SupportedVersion);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NewerSchemaVersionIsRejected()
|
||||
{
|
||||
public void OpenRejectsNonContiguousMigrationList() {
|
||||
using var directory = new TempDirectory();
|
||||
string dbPath = Path.Combine(directory.FullPath, "test.db");
|
||||
string databasePath = Path.Combine(directory.FullPath, "gap.db");
|
||||
|
||||
// Simulate a database written by a newer build.
|
||||
using (var connection = SqliteDatabase.Open(dbPath, []))
|
||||
{
|
||||
SqliteTestHelper.Exec(connection, "PRAGMA user_version=5;");
|
||||
}
|
||||
SchemaMigration[] broken =
|
||||
[
|
||||
new SchemaMigration(2, "starts too high", "SELECT 1;"),
|
||||
];
|
||||
|
||||
SchemaVersionException ex = Assert.ThrowsExactly<SchemaVersionException>(
|
||||
() => SqliteDatabase.Open(dbPath, V1AndV2));
|
||||
Assert.AreEqual(5L, ex.StoredVersion);
|
||||
Assert.AreEqual(2, ex.SupportedVersion);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NonContiguousMigrationListIsRejected()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string dbPath = Path.Combine(directory.FullPath, "test.db");
|
||||
var bad = new[] { new SchemaMigration(2, "gap", "CREATE TABLE t (id INTEGER);") };
|
||||
|
||||
Assert.ThrowsExactly<ArgumentException>(() => SqliteDatabase.Open(dbPath, bad));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => SqliteDatabase.Open(databasePath, broken));
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
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,50 +1,57 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
|
||||
namespace YKanBan.Tests.Storage.Workspace;
|
||||
|
||||
/// <summary>Tests for .ykanban folder and empty database creation.</summary>
|
||||
/// <summary>
|
||||
/// Tests for workspace detection and initialization. Initialization creates
|
||||
/// the structure and an empty migrated database, but deliberately adds no
|
||||
/// content.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class WorkspaceInitializerTests
|
||||
{
|
||||
public class WorkspaceInitializerTests {
|
||||
[TestMethod]
|
||||
public void InitializeCreatesYkanbanFolderAndDatabase()
|
||||
{
|
||||
public void IsWorkspaceReflectsInitializationState() {
|
||||
using var directory = new TempDirectory();
|
||||
|
||||
Assert.IsFalse(WorkspaceInitializer.IsWorkspace(directory.FullPath));
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
WorkspaceInitializer.Initialize(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]
|
||||
public void InitializeLeavesDatabaseEmpty()
|
||||
{
|
||||
// Initialization creates structure only; preset content is seeded separately.
|
||||
public void InitializeCreatesStructureAndMigratedEmptyDatabase() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||
Assert.IsTrue(Directory.Exists(WorkspacePaths.Root(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 cards;"));
|
||||
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM tags;"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InitializeThrowsWhenDirectoryIsMissing()
|
||||
{
|
||||
string missing = Path.Combine(Path.GetTempPath(), "ykanban-tests-" + Guid.NewGuid().ToString("N"));
|
||||
Assert.ThrowsExactly<WorkspaceDirectoryMissingException>(() => WorkspaceInitializer.Initialize(missing));
|
||||
public void InitializeMissingFolderThrows() {
|
||||
using var directory = new TempDirectory();
|
||||
string missing = Path.Combine(directory.FullPath, "not-created");
|
||||
|
||||
WorkspaceDirectoryMissingException exception = Assert.ThrowsExactly<WorkspaceDirectoryMissingException>(
|
||||
() => WorkspaceInitializer.Initialize(missing));
|
||||
Assert.AreEqual(missing, exception.FolderPath);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InitializeThrowsWhenDatabaseAlreadyExists()
|
||||
{
|
||||
public void InitializeTwiceThrows() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
|
||||
@@ -4,13 +4,13 @@ using YKanBan.Tests.TestUtilities;
|
||||
|
||||
namespace YKanBan.Tests.Storage.Workspace;
|
||||
|
||||
/// <summary>Tests for exclusive lock acquisition, diagnostics and release.</summary>
|
||||
/// <summary>
|
||||
/// Tests for exclusive lock acquisition and release.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class WorkspaceLockTests
|
||||
{
|
||||
public class WorkspaceLockTests {
|
||||
[TestMethod]
|
||||
public void AcquireThenDisposeThenAcquireAgainSucceeds()
|
||||
{
|
||||
public void AcquireThenDisposeThenAcquireAgainSucceeds() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
@@ -20,38 +20,32 @@ public class WorkspaceLockTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SecondAcquireWhileHeldThrows()
|
||||
{
|
||||
public void SecondAcquireWhileHeldThrows() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
using WorkspaceLock first = WorkspaceLock.Acquire(directory.FullPath);
|
||||
WorkspaceLockException ex = Assert.ThrowsExactly<WorkspaceLockException>(
|
||||
WorkspaceLockException exception = Assert.ThrowsExactly<WorkspaceLockException>(
|
||||
() => WorkspaceLock.Acquire(directory.FullPath));
|
||||
Assert.AreEqual(WorkspacePaths.LockFile(directory.FullPath), ex.LockFilePath);
|
||||
Assert.AreEqual(WorkspacePaths.LockFile(directory.FullPath), exception.LockFilePath);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AcquireWithoutYkanbanThrowsNotInitialized()
|
||||
{
|
||||
public void AcquireWithoutYkanbanThrowsNotInitialized() {
|
||||
using var directory = new TempDirectory();
|
||||
Assert.ThrowsExactly<WorkspaceNotInitializedException>(
|
||||
() => WorkspaceLock.Acquire(directory.FullPath));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LockFileContainsHolderDiagnostics()
|
||||
{
|
||||
public void LockFileIsEmptyAfterRelease() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
using (WorkspaceLock.Acquire(directory.FullPath))
|
||||
{
|
||||
using (WorkspaceLock.Acquire(directory.FullPath)) {
|
||||
}
|
||||
|
||||
// The file survives release and carries PID / machine name / time for humans.
|
||||
string content = File.ReadAllText(WorkspacePaths.LockFile(directory.FullPath));
|
||||
StringAssert.Contains(content, "pid=");
|
||||
StringAssert.Contains(content, $"machine={Environment.MachineName}");
|
||||
// The lock file survives release but carries no content; only the OS handle matters.
|
||||
Assert.AreEqual(0L, new FileInfo(WorkspacePaths.LockFile(directory.FullPath)).Length);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +1,140 @@
|
||||
using System.Globalization;
|
||||
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
|
||||
namespace YKanBan.Tests.Storage.Workspace;
|
||||
|
||||
/// <summary>Tests for seeding preset workspace content.</summary>
|
||||
/// <summary>
|
||||
/// Verifies that the preset columns and tags 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]
|
||||
public class WorkspacePresetTests
|
||||
{
|
||||
[DoNotParallelize]
|
||||
public class WorkspacePresetTests {
|
||||
[TestMethod]
|
||||
public void SeedAddsThreeDistinctPresetColumns()
|
||||
{
|
||||
public void AddPresetColumnsStoresEnglishTextUnderEnglishCulture() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
WorkspacePreset.SeedColumns(directory.FullPath);
|
||||
WorkspacePreset.AddPresetColumns(directory.FullPath);
|
||||
|
||||
using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||
List<string> titles = SqliteTestHelper.GetColumnTitles(connection);
|
||||
|
||||
Assert.AreEqual(3, titles.Count);
|
||||
Assert.AreEqual(titles.Count, titles.Distinct().Count());
|
||||
Assert.IsTrue(titles.All(title => title.Length > 0));
|
||||
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||
CollectionAssert.AreEqual(
|
||||
new[]
|
||||
{
|
||||
Resources.PresetColumn_Todo,
|
||||
Resources.PresetColumn_InProgress,
|
||||
Resources.PresetColumn_Done,
|
||||
},
|
||||
SqliteTestHelper.GetColumnTitles(connection));
|
||||
CollectionAssert.AreEqual(
|
||||
new[]
|
||||
{
|
||||
Resources.PresetColumn_Todo_Description,
|
||||
Resources.PresetColumn_InProgress_Description,
|
||||
Resources.PresetColumn_Done_Description,
|
||||
},
|
||||
SqliteTestHelper.GetColumnDescriptions(connection));
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SeedPresetColumnsShareOneTimestamp()
|
||||
{
|
||||
public void AddPresetColumnsStoresChineseTextUnderChineseCulture() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("zh-Hans");
|
||||
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
WorkspacePreset.SeedColumns(directory.FullPath);
|
||||
WorkspacePreset.AddPresetColumns(directory.FullPath);
|
||||
|
||||
using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||
CollectionAssert.AreEqual(
|
||||
new[]
|
||||
{
|
||||
Resources.PresetColumn_Todo,
|
||||
Resources.PresetColumn_InProgress,
|
||||
Resources.PresetColumn_Done,
|
||||
},
|
||||
SqliteTestHelper.GetColumnTitles(connection));
|
||||
// Chinese resources must resolve to different text than English.
|
||||
Assert.AreEqual("待办", Resources.PresetColumn_Todo);
|
||||
Assert.AreEqual("已完成的任务。", Resources.PresetColumn_Done_Description);
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
// Creation writes created_at = updated_at; all three columns share one moment.
|
||||
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;"));
|
||||
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(DISTINCT created_at) FROM columns;"));
|
||||
[TestMethod]
|
||||
public void AddPresetTagsStoresEightTagsUnderEnglishCulture() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
WorkspacePreset.AddPresetTags(directory.FullPath);
|
||||
|
||||
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||
List<(string Name, string Color, string Description)> tags = SqliteTestHelper.GetTags(connection);
|
||||
|
||||
Assert.AreEqual(8, tags.Count);
|
||||
Assert.AreEqual(("bug", "#d73a4a", "Something isn't working"), tags[0]);
|
||||
Assert.AreEqual(("documentation", "#0075ca", "Improvements or additions to documentation"), tags[1]);
|
||||
Assert.AreEqual(("wontfix", "#ffffff", "This will not be worked on"), tags[7]);
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddPresetTagsStoresChineseNamesUnderChineseCulture() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("zh-Hans");
|
||||
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
WorkspacePreset.AddPresetTags(directory.FullPath);
|
||||
|
||||
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||
List<(string Name, string Color, string Description)> tags = SqliteTestHelper.GetTags(connection);
|
||||
|
||||
Assert.AreEqual(8, tags.Count);
|
||||
Assert.AreEqual("缺陷", tags[0].Name);
|
||||
Assert.AreEqual("功能没有正常工作", tags[0].Description);
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PresetContentIsDataAndIgnoresLaterCultureChanges() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
WorkspacePreset.AddPresetColumns(directory.FullPath);
|
||||
WorkspacePreset.AddPresetTags(directory.FullPath);
|
||||
|
||||
// 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);
|
||||
Assert.AreEqual("To Do", SqliteTestHelper.GetColumnTitles(connection)[0]);
|
||||
Assert.AreEqual("bug", SqliteTestHelper.GetTags(connection)[0].Name);
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Search;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
|
||||
@@ -8,25 +9,19 @@ namespace YKanBan.Tests.Storage.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for workspace CRUD, the three cascade chains, edit-confirm
|
||||
/// transaction atomicity, timestamp refresh rules and the last_edited_at
|
||||
/// write-through.
|
||||
/// transaction atomicity and the timestamp refresh rules.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class WorkspaceRepositoryTests
|
||||
{
|
||||
public class WorkspaceRepositoryTests {
|
||||
/// <summary>
|
||||
/// Owns a workspace with fixed-timestamp fixture data (one column, one
|
||||
/// card, two tags linked to the card), a fake-clock app.db and the
|
||||
/// repository under test.
|
||||
/// card, two tags linked to the card) plus the repository under test.
|
||||
/// Fixture timestamps are small literal values so that any real write,
|
||||
/// which stamps the current Unix time, is observable.
|
||||
/// </summary>
|
||||
private sealed class RepositoryFixture : IDisposable
|
||||
{
|
||||
private sealed class RepositoryFixture : IDisposable {
|
||||
public TempDirectory Directory { get; } = new();
|
||||
|
||||
public long Clock { get; set; } = 1000;
|
||||
|
||||
public AppDatabase AppDb { get; }
|
||||
|
||||
public WorkspaceRepository Repository { get; }
|
||||
|
||||
public long ColumnId { get; } = 1;
|
||||
@@ -37,63 +32,66 @@ public class WorkspaceRepositoryTests
|
||||
|
||||
public long UiTagId { get; } = 2;
|
||||
|
||||
public RepositoryFixture()
|
||||
{
|
||||
public RepositoryFixture() {
|
||||
WorkspaceInitializer.Initialize(Directory.FullPath);
|
||||
|
||||
// Fixture rows carry literal timestamps so refresh vs. no-refresh stays observable.
|
||||
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath);
|
||||
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 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 ('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, 2);");
|
||||
|
||||
AppDb = new AppDatabase(Path.Combine(Directory.FullPath, "app.db"), () => Clock);
|
||||
Repository = new WorkspaceRepository(Directory.FullPath, AppDb);
|
||||
}
|
||||
|
||||
/// <summary>The last_edited_at currently mirrored into the registry.</summary>
|
||||
public long LastEditedAt => AppDb.GetWorkspaces().Single().LastEditedAt;
|
||||
Repository = new WorkspaceRepository(Directory.FullPath);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
public void Dispose() {
|
||||
Repository.Dispose();
|
||||
AppDb.Dispose();
|
||||
Directory.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateColumnWithoutChangeWritesNothing()
|
||||
{
|
||||
public void GetColumnsReturnsTheSeededColumn() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
ColumnModel before = fixture.Repository.GetColumn(fixture.ColumnId)!;
|
||||
|
||||
ColumnModel result = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col", "");
|
||||
|
||||
Assert.AreEqual(before.UpdatedAt, result.UpdatedAt);
|
||||
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
|
||||
ColumnModel column = fixture.Repository.GetColumn(fixture.ColumnId)!;
|
||||
Assert.AreEqual("Col", column.Title);
|
||||
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateColumnChangeRefreshesColumnTimestampAndLastEdited()
|
||||
{
|
||||
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]
|
||||
public void UpdateColumnWithoutChangeWritesNothing() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
ColumnModel result = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col", "");
|
||||
|
||||
// A no-op must not refresh the fixed fixture timestamp.
|
||||
Assert.AreEqual(100L, result.UpdatedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateColumnChangeRefreshesTimestamp() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
fixture.Clock = 2000;
|
||||
|
||||
ColumnModel updated = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col2", "desc");
|
||||
|
||||
Assert.IsTrue(updated.UpdatedAt > 100L);
|
||||
Assert.AreEqual(2000L, fixture.LastEditedAt);
|
||||
Assert.AreEqual(100L, updated.CreatedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeleteColumnCascadesToCardsAndTagLinks()
|
||||
{
|
||||
public void DeleteColumnCascadesToCardsAndTagLinks() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
fixture.Clock = 2000;
|
||||
|
||||
Assert.IsTrue(fixture.Repository.DeleteColumn(fixture.ColumnId));
|
||||
|
||||
@@ -102,12 +100,10 @@ public class WorkspaceRepositoryTests
|
||||
Assert.AreEqual(2, fixture.Repository.GetTags().Count);
|
||||
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(fixture.Directory.FullPath);
|
||||
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM card_tags;"));
|
||||
Assert.AreEqual(2000L, fixture.LastEditedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeleteCardRemovesTagLinksButKeepsTags()
|
||||
{
|
||||
public void DeleteCardRemovesTagLinksButKeepsTags() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
Assert.IsTrue(fixture.Repository.DeleteCard(fixture.CardId));
|
||||
@@ -119,8 +115,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeleteTagDetachesFromCardsButKeepsCards()
|
||||
{
|
||||
public void DeleteTagDetachesFromCardsButKeepsCards() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
Assert.IsTrue(fixture.Repository.DeleteTag(fixture.BugTagId));
|
||||
@@ -132,48 +127,39 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateCardWithoutEffectiveChangeWritesNothing()
|
||||
{
|
||||
public void UpdateCardWithoutEffectiveChangeWritesNothing() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
fixture.Clock = 2000;
|
||||
CardModel before = fixture.Repository.GetCard(fixture.CardId)!;
|
||||
|
||||
CardModel result = fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.BugTagId, fixture.UiTagId]);
|
||||
CardModel result = fixture.Repository.UpdateCard(
|
||||
fixture.CardId, "T", "C", [fixture.BugTagId, fixture.UiTagId]);
|
||||
|
||||
Assert.AreEqual(before.UpdatedAt, result.UpdatedAt);
|
||||
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
|
||||
Assert.AreEqual(100L, result.UpdatedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateCardTitleChangeRefreshesTimestampsAndLastEdited()
|
||||
{
|
||||
public void UpdateCardTitleChangeRefreshesTimestamp() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
fixture.Clock = 2000;
|
||||
|
||||
CardModel updated = fixture.Repository.UpdateCard(fixture.CardId, "T2", "C", [fixture.BugTagId, fixture.UiTagId]);
|
||||
CardModel updated = fixture.Repository.UpdateCard(
|
||||
fixture.CardId, "T2", "C", [fixture.BugTagId, fixture.UiTagId]);
|
||||
|
||||
Assert.IsTrue(updated.UpdatedAt > 100L);
|
||||
Assert.AreEqual(2000L, fixture.LastEditedAt);
|
||||
Assert.AreEqual(100L, updated.CreatedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateCardTagSetOnlyChangeStillRefreshesCardTimestamp()
|
||||
{
|
||||
public void UpdateCardTagSetOnlyChangeStillRefreshesTimestamp() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
fixture.Clock = 2000;
|
||||
|
||||
CardModel updated = fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.BugTagId]);
|
||||
|
||||
Assert.IsTrue(updated.UpdatedAt > 100L);
|
||||
Assert.AreEqual(1, updated.Tags.Count);
|
||||
Assert.AreEqual(2000L, fixture.LastEditedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateCardWithUnknownTagRollsBackAtomically()
|
||||
{
|
||||
public void UpdateCardWithUnknownTagRollsBackAtomically() {
|
||||
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.
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
@@ -184,15 +170,12 @@ public class WorkspaceRepositoryTests
|
||||
Assert.AreEqual("C", after.Content);
|
||||
Assert.AreEqual(100L, after.UpdatedAt);
|
||||
Assert.AreEqual(2, after.Tags.Count);
|
||||
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MoveCardRefreshesLastEditedButNotCardTimestamp()
|
||||
{
|
||||
public void MoveCardUpdatesColumnWithoutRefreshingTimestamp() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
long target = fixture.Repository.AddColumn("Target", "").Id;
|
||||
fixture.Clock = 2000;
|
||||
|
||||
Assert.IsTrue(fixture.Repository.MoveCard(fixture.CardId, target));
|
||||
|
||||
@@ -200,25 +183,20 @@ public class WorkspaceRepositoryTests
|
||||
Assert.AreEqual(target, moved.ColumnId);
|
||||
// The move is a write but deliberately leaves the card's updated_at alone.
|
||||
Assert.AreEqual(100L, moved.UpdatedAt);
|
||||
Assert.AreEqual(2000L, fixture.LastEditedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MoveCardToCurrentColumnWritesNothing()
|
||||
{
|
||||
public void MoveCardToCurrentColumnIsNoOp() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
fixture.Clock = 2000;
|
||||
|
||||
Assert.IsFalse(fixture.Repository.MoveCard(fixture.CardId, fixture.ColumnId));
|
||||
|
||||
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
|
||||
Assert.AreEqual(100L, fixture.Repository.GetCard(fixture.CardId)!.UpdatedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddCardCreatesWithEqualTimestampsAndLinkedTags()
|
||||
{
|
||||
public void AddCardCreatesWithEqualTimestampsAndLinkedTags() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
fixture.Clock = 2000;
|
||||
|
||||
CardModel card = fixture.Repository.AddCard(fixture.ColumnId, "N", "body", [fixture.UiTagId]);
|
||||
|
||||
@@ -226,38 +204,51 @@ public class WorkspaceRepositoryTests
|
||||
Assert.AreEqual(card.CreatedAt, card.UpdatedAt);
|
||||
Assert.AreEqual(1, card.Tags.Count);
|
||||
Assert.AreEqual("ui", card.Tags[0].Name);
|
||||
Assert.AreEqual(2000L, fixture.LastEditedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateTagWithoutChangeWritesNothing()
|
||||
{
|
||||
public void UpdateTagWithoutChangeWritesNothing() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
fixture.Clock = 2000;
|
||||
|
||||
TagModel result = fixture.Repository.UpdateTag(fixture.BugTagId, "bug", RgbColor.Parse("#ff0000"), "");
|
||||
TagModel result = fixture.Repository.UpdateTag(
|
||||
fixture.BugTagId, "bug", RgbColor.Parse("#ff0000"), "");
|
||||
|
||||
Assert.AreEqual("bug", result.Name);
|
||||
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
|
||||
Assert.AreEqual(new RgbColor(0xFF, 0x00, 0x00), result.Color);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateTagChangeWritesAndTouchesLastEdited()
|
||||
{
|
||||
public void UpdateTagChangeWrites() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
fixture.Clock = 3000;
|
||||
|
||||
TagModel updated = fixture.Repository.UpdateTag(fixture.BugTagId, "defect", RgbColor.Parse("#ee0a0a"), "desc");
|
||||
TagModel updated = fixture.Repository.UpdateTag(
|
||||
fixture.BugTagId, "defect", RgbColor.Parse("#ee0a0a"), "desc");
|
||||
|
||||
Assert.AreEqual("defect", updated.Name);
|
||||
Assert.AreEqual(new RgbColor(0xEE, 0x0A, 0x0A), updated.Color);
|
||||
Assert.AreEqual("desc", updated.Description);
|
||||
Assert.AreEqual(3000L, fixture.LastEditedAt);
|
||||
Assert.AreEqual("defect", fixture.Repository.GetTags().Single(tag => tag.Id == fixture.BugTagId).Name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GetTagsWithUsageCountsAssignments()
|
||||
{
|
||||
public void AddTagWithDuplicateNameIsRejected() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
fixture.Repository.AddTag("bug", RgbColor.Parse("#123456"), ""));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GetCardIdsMatchingRunsTheCompiledSearch() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("T"));
|
||||
|
||||
IReadOnlyCollection<long> ids = fixture.Repository.GetCardIdsMatching(compiled);
|
||||
|
||||
CollectionAssert.AreEquivalent(new[] { fixture.CardId }, ids.ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GetTagsWithUsageCountsAssignments() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
IReadOnlyList<(TagModel Tag, long UsageCount)> before = fixture.Repository.GetTagsWithUsage();
|
||||
@@ -265,7 +256,6 @@ public class WorkspaceRepositoryTests
|
||||
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.
|
||||
fixture.Clock = 2000;
|
||||
fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.UiTagId]);
|
||||
|
||||
IReadOnlyList<(TagModel Tag, long UsageCount)> after = fixture.Repository.GetTagsWithUsage();
|
||||
|
||||
@@ -1,105 +1,105 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
|
||||
namespace YKanBan.Tests.Storage.Workspace;
|
||||
|
||||
/// <summary>Verifies that the DDL constraints reject invalid data at the door.</summary>
|
||||
/// <summary>
|
||||
/// Verifies that the workspace DDL constraints reject invalid data at the door
|
||||
/// and that the cascading delete chains work as specified.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class WorkspaceSchemaTests
|
||||
{
|
||||
/// <summary>Owns a temp directory plus a fresh workspace-schema database for one test.</summary>
|
||||
private sealed class FreshDatabase : IDisposable
|
||||
{
|
||||
public class WorkspaceSchemaTests {
|
||||
/// <summary>
|
||||
/// Owns a temp directory plus a fresh workspace-schema database for a single test.
|
||||
/// </summary>
|
||||
private sealed class FreshDatabase : IDisposable {
|
||||
public TempDirectory Directory { get; } = new();
|
||||
|
||||
public SqliteConnection Connection { get; }
|
||||
|
||||
public FreshDatabase()
|
||||
{
|
||||
public FreshDatabase() {
|
||||
Connection = SqliteDatabase.Open(
|
||||
Path.Combine(Directory.FullPath, "ws.db"), WorkspaceSchema.Migrations);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
/// <summary>
|
||||
/// Closes the connection before removing the temporary directory.
|
||||
/// </summary>
|
||||
public void Dispose() {
|
||||
Connection.Dispose();
|
||||
Directory.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EmptyColumnTitleIsRejected()
|
||||
{
|
||||
public void EmptyColumnTitleIsRejected() {
|
||||
using var db = new FreshDatabase();
|
||||
using var connection = db.Connection;
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
SqliteTestHelper.Exec(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);"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DuplicateColumnTitleIsRejected()
|
||||
{
|
||||
public void WhitespaceColumnTitleIsAccepted() {
|
||||
using var db = new FreshDatabase();
|
||||
using var connection = db.Connection;
|
||||
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);"));
|
||||
// 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]
|
||||
public void ColumnTitlesCompareCaseSensitively()
|
||||
{
|
||||
public void DuplicateColumnTitleIsRejected() {
|
||||
using var db = new FreshDatabase();
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnTitlesCompareCaseSensitively() {
|
||||
using var db = new FreshDatabase();
|
||||
using var connection = db.Connection;
|
||||
// BINARY collation: 'Foo' and 'foo' are distinct titles.
|
||||
SqliteTestHelper.Exec(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;"));
|
||||
SqliteTestHelper.Exec(db.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);");
|
||||
Assert.AreEqual(2L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM columns;"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EmptyTagNameIsRejected()
|
||||
{
|
||||
public void EmptyTagNameIsRejected() {
|
||||
using var db = new FreshDatabase();
|
||||
using var connection = db.Connection;
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('', '#112233');"));
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('', '#112233');"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagNamesAcceptSpacesEmojiAndReservedWords()
|
||||
{
|
||||
public void TagNamesAcceptSpacesEmojiAndReservedWords() {
|
||||
using var db = new FreshDatabase();
|
||||
using var connection = db.Connection;
|
||||
// Tag names are fully open: no charset or length rules, no trimming.
|
||||
foreach (string name in new[] { " ", "a b", "🏷️", "AND", "tag:with:colons" })
|
||||
{
|
||||
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ($n, '#112233');", ("$n", name));
|
||||
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));
|
||||
}
|
||||
Assert.AreEqual(5L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM tags;"));
|
||||
Assert.AreEqual(5L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DuplicateTagNameIsRejected()
|
||||
{
|
||||
public void DuplicateTagNameIsRejected() {
|
||||
using var db = new FreshDatabase();
|
||||
using var connection = db.Connection;
|
||||
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#445566');"));
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#445566');"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("#000000")]
|
||||
[DataRow("#FFFFFF")]
|
||||
[DataRow("#a1B2c3")]
|
||||
public void ValidTagColorsAreAccepted(string color)
|
||||
{
|
||||
public void ValidTagColorsAreAccepted(string color) {
|
||||
using var db = new FreshDatabase();
|
||||
using var connection = db.Connection;
|
||||
int affected = SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color));
|
||||
int affected = SqliteTestHelper.Exec(
|
||||
db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color));
|
||||
Assert.AreEqual(1, affected);
|
||||
}
|
||||
|
||||
@@ -112,49 +112,93 @@ public class WorkspaceSchemaTests
|
||||
[DataRow(" #112233")]
|
||||
[DataRow("#112233 ")]
|
||||
[DataRow("")]
|
||||
public void InvalidTagColorsAreRejected(string color)
|
||||
{
|
||||
public void InvalidTagColorsAreRejected(string color) {
|
||||
using var db = new FreshDatabase();
|
||||
using var connection = db.Connection;
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color)));
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CardRequiresExistingColumn()
|
||||
{
|
||||
public void CardRequiresExistingColumn() {
|
||||
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.
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (999, 1, 1);"));
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (999, 1, 1);"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CardDefaultsToEmptyTitleAndContent()
|
||||
{
|
||||
public void CardDefaultsToEmptyTitleAndContent() {
|
||||
using var db = new FreshDatabase();
|
||||
using var connection = db.Connection;
|
||||
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(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);");
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
|
||||
|
||||
// No title is represented by the empty string.
|
||||
Assert.AreEqual(string.Empty, SqliteTestHelper.ScalarString(connection, "SELECT title FROM cards WHERE id = 1;"));
|
||||
Assert.AreEqual(string.Empty, SqliteTestHelper.ScalarString(connection, "SELECT content FROM cards WHERE id = 1;"));
|
||||
Assert.AreEqual(string.Empty, SqliteTestHelper.ScalarString(db.Connection, "SELECT title FROM cards WHERE id = 1;"));
|
||||
Assert.AreEqual(string.Empty, SqliteTestHelper.ScalarString(db.Connection, "SELECT content FROM cards WHERE id = 1;"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CardTagDuplicateAssignmentIsRejected()
|
||||
{
|
||||
public void CardTagDuplicateAssignmentIsRejected() {
|
||||
using var db = new FreshDatabase();
|
||||
using var connection = db.Connection;
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);");
|
||||
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 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 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);"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
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 OpenWithoutDatabaseThrowsDatabaseMissing() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
File.Delete(WorkspacePaths.Database(directory.FullPath));
|
||||
|
||||
Assert.ThrowsExactly<WorkspaceDatabaseMissingException>(
|
||||
() => WorkspaceSession.Open(directory.FullPath));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InitializeHoldsLockAndSeedsPreset() {
|
||||
using var directory = new TempDirectory();
|
||||
|
||||
using WorkspaceSession session = WorkspaceSession.Initialize(directory.FullPath);
|
||||
|
||||
// The lock is held for the whole session, so a second initialize cannot interleave.
|
||||
Assert.ThrowsExactly<WorkspaceLockException>(() => WorkspaceSession.Initialize(directory.FullPath));
|
||||
|
||||
// The preset columns and tags were written under the same lock.
|
||||
Assert.AreEqual(3, session.Repository.GetColumns().Count);
|
||||
Assert.AreEqual(8, session.Repository.GetTags().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InitializeExistingWorkspaceThrowsAndReleasesLock() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
Assert.ThrowsExactly<InvalidOperationException>(() => WorkspaceSession.Initialize(directory.FullPath));
|
||||
|
||||
// The failed initialize released the lock, so the workspace can still be opened.
|
||||
using WorkspaceSession session = WorkspaceSession.Open(directory.FullPath);
|
||||
Assert.AreEqual(directory.FullPath, session.FolderPath);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,67 +1,125 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
namespace YKanBan.Tests.TestUtilities;
|
||||
|
||||
/// <summary>Shared helpers for storage tests.</summary>
|
||||
public static class SqliteTestHelper
|
||||
{
|
||||
/// <summary>Executes a non-query SQL statement and returns the affected row count.</summary>
|
||||
public static int Exec(SqliteConnection connection, string sql, params (string Name, object? Value)[] parameters)
|
||||
{
|
||||
/// <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 {
|
||||
/// <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) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = sql;
|
||||
foreach ((string name, object? value) in parameters)
|
||||
{
|
||||
foreach ((string name, object? value) in parameters) {
|
||||
command.Parameters.AddWithValue(name, value);
|
||||
}
|
||||
return command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
/// <summary>Returns the scalar result of a SQL query as a string.</summary>
|
||||
public static string ScalarString(SqliteConnection connection, string sql)
|
||||
{
|
||||
/// <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) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = sql;
|
||||
return (string)command.ExecuteScalar()!;
|
||||
}
|
||||
|
||||
/// <summary>Returns the scalar result of a SQL query as a long.</summary>
|
||||
public static long ScalarLong(SqliteConnection connection, string sql)
|
||||
{
|
||||
/// <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) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = sql;
|
||||
return (long)command.ExecuteScalar()!;
|
||||
}
|
||||
|
||||
/// <summary>Returns true when a table with the given name exists.</summary>
|
||||
public static bool TableExists(SqliteConnection connection, string tableName)
|
||||
{
|
||||
/// <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) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=$name;";
|
||||
command.Parameters.AddWithValue("$name", tableName);
|
||||
return (long)command.ExecuteScalar()! == 1;
|
||||
}
|
||||
|
||||
/// <summary>Returns the titles of all columns, ordered by id.</summary>
|
||||
public static List<string> GetColumnTitles(SqliteConnection connection)
|
||||
{
|
||||
/// <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) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT title FROM columns ORDER BY id ASC;";
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var titles = new List<string>();
|
||||
while (reader.Read())
|
||||
{
|
||||
while (reader.Read()) {
|
||||
titles.Add(reader.GetString(0));
|
||||
}
|
||||
return titles;
|
||||
}
|
||||
|
||||
/// <summary>Opens a workspace database with the real migration list.</summary>
|
||||
public static SqliteConnection OpenWorkspace(string folderPath)
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the descriptions of all columns, ordered by id ascending.
|
||||
/// </summary>
|
||||
/// <param name="connection">An open database connection.</param>
|
||||
/// <returns>The column descriptions in id order.</returns>
|
||||
public static List<string> GetColumnDescriptions(SqliteConnection connection) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT description FROM columns ORDER BY id ASC;";
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var descriptions = new List<string>();
|
||||
while (reader.Read()) {
|
||||
descriptions.Add(reader.GetString(0));
|
||||
}
|
||||
return descriptions;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all tags as name/color/description tuples, ordered by id ascending.
|
||||
/// </summary>
|
||||
/// <param name="connection">An open database connection.</param>
|
||||
/// <returns>The tags in id order.</returns>
|
||||
public static List<(string Name, string Color, string Description)> GetTags(SqliteConnection connection) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT name, color, description FROM tags ORDER BY id ASC;";
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var tags = new List<(string, string, string)>();
|
||||
while (reader.Read()) {
|
||||
tags.Add((reader.GetString(0), reader.GetString(1), reader.GetString(2)));
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
/// <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) {
|
||||
return SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
|
||||
}
|
||||
}
|
||||
@@ -2,30 +2,38 @@ namespace YKanBan.Tests.TestUtilities;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a unique temporary directory per test instance and removes it on
|
||||
/// disposal. Retries the deletion once because SQLite WAL files can linger
|
||||
/// for a moment after connections close.
|
||||
/// disposal. The removal is retried once because SQLite WAL sidecar files can
|
||||
/// linger for a moment after the connections close.
|
||||
/// </summary>
|
||||
public sealed class TempDirectory : IDisposable
|
||||
{
|
||||
/// <summary>Unique directory path managed by this instance.</summary>
|
||||
public sealed class TempDirectory : IDisposable {
|
||||
/// <summary>
|
||||
/// Gets the unique directory path managed by this instance.
|
||||
/// </summary>
|
||||
public string FullPath { get; }
|
||||
|
||||
public TempDirectory()
|
||||
{
|
||||
public TempDirectory() {
|
||||
FullPath = Path.Combine(Path.GetTempPath(), "ykanban-tests-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(FullPath);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
/// <summary>
|
||||
/// Deletes the directory tree, retrying once after a short delay.
|
||||
/// </summary>
|
||||
public void Dispose() {
|
||||
try {
|
||||
// SAFETY: Recursive directory delete is safe: FullPath is the
|
||||
// read-only, GUID-named directory this instance created under the
|
||||
// OS temp folder, so it can never target user data or the temp root.
|
||||
Directory.Delete(FullPath, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
} catch (IOException) {
|
||||
Thread.Sleep(100);
|
||||
try { Directory.Delete(FullPath, recursive: true); } catch (IOException) { }
|
||||
try {
|
||||
// SAFETY: Retry of the same recursive delete, still confined to
|
||||
// this instance's own temp directory.
|
||||
Directory.Delete(FullPath, recursive: true);
|
||||
} catch (IOException) {
|
||||
// Leftovers in the OS temp folder are harmless; never fail a test over cleanup.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Globalization;
|
||||
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.ViewModels.ErrorPages;
|
||||
|
||||
namespace YKanBan.Tests.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the open-failed page's exception-type → localized message mapping
|
||||
/// and its English details. Mutates the global <see cref="Resources.Culture"/>,
|
||||
/// therefore marked do-not-parallelize.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[DoNotParallelize]
|
||||
public class OpenFailedPageViewModelTests {
|
||||
private const string Folder = "/work/repo";
|
||||
|
||||
private static void WithCulture(string language, Action action) {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo(language);
|
||||
action();
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Expected(string pattern, params object[] arguments) =>
|
||||
string.Format(Resources.Culture, pattern, [Folder, .. arguments]);
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("en")]
|
||||
[DataRow("zh-Hans")]
|
||||
public void EachRecognizedExceptionTypeHasItsOwnMessage(string language) {
|
||||
WithCulture(language, () => {
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_SchemaTooNew, 3L, 1),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new SchemaVersionException(3, 1)));
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_DatabaseMissing),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new WorkspaceDatabaseMissingException("/work/repo/.ykanban/ykanban.db")));
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_Database),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new SqliteException("file is not a database", 26)));
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_AccessDenied),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new UnauthorizedAccessException()));
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_Io),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new IOException()));
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_Io),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new DirectoryNotFoundException()));
|
||||
});
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnrecognizedExceptionGetsTheGenericMessage() {
|
||||
WithCulture("en", () => {
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_Generic),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new InvalidOperationException()));
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_Generic),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new WorkspaceDirectoryMissingException(Folder)));
|
||||
});
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DetailsCarryTheEnglishExceptionTextInAnyLanguage() {
|
||||
WithCulture("zh-Hans", () => {
|
||||
var exception = new SchemaVersionException(3, 1);
|
||||
var page = new OpenFailedPageViewModel(Folder, exception);
|
||||
|
||||
Assert.AreEqual(Folder, page.FolderPath);
|
||||
StringAssert.Contains(page.Details, typeof(SchemaVersionException).FullName!);
|
||||
StringAssert.Contains(page.Details, exception.Message);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -13,4 +15,5 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\YKanBan\YKanBan.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+40
-1
@@ -1,9 +1,48 @@
|
||||
<Application xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="YKanBan.App"
|
||||
xmlns:local="using:YKanBan"
|
||||
xmlns:semi="https://irihi.tech/semi"
|
||||
RequestedThemeVariant="Default">
|
||||
|
||||
<Application.DataTemplates>
|
||||
<local:ViewLocator/>
|
||||
</Application.DataTemplates>
|
||||
|
||||
<Application.Styles>
|
||||
<FluentTheme />
|
||||
<!-- Semi.Avalonia provides the light and dark palettes; icons need their own theme. -->
|
||||
<semi:SemiTheme/>
|
||||
<semi:ColorPickerSemiTheme/>
|
||||
<StyleInclude Source="avares://IconPacks.Avalonia.Lucide/Lucide.axaml"/>
|
||||
</Application.Styles>
|
||||
|
||||
<!--
|
||||
Custom colors are declared as Light/Dark pairs and consumed through
|
||||
DynamicResource, so a theme switch restyles every surface. Tag colors are
|
||||
user data and stay as their literal #RRGGBB value.
|
||||
-->
|
||||
<Application.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.ThemeDictionaries>
|
||||
<ResourceDictionary x:Key="Light">
|
||||
<SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#F6F7F9"/>
|
||||
<SolidColorBrush x:Key="TopBarBorderBrush" Color="#E2E4EA"/>
|
||||
<SolidColorBrush x:Key="BoardColumnBackgroundBrush" Color="#F1F2F5"/>
|
||||
<SolidColorBrush x:Key="BoardColumnBorderBrush" Color="#E2E4EA"/>
|
||||
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#FFFFFF"/>
|
||||
<SolidColorBrush x:Key="CardBorderBrush" Color="#E2E4EA"/>
|
||||
<SolidColorBrush x:Key="ErrorTextBrush" Color="#C0392B"/>
|
||||
</ResourceDictionary>
|
||||
<ResourceDictionary x:Key="Dark">
|
||||
<SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#1C1E24"/>
|
||||
<SolidColorBrush x:Key="TopBarBorderBrush" Color="#2C2F37"/>
|
||||
<SolidColorBrush x:Key="BoardColumnBackgroundBrush" Color="#17181C"/>
|
||||
<SolidColorBrush x:Key="BoardColumnBorderBrush" Color="#2C2F37"/>
|
||||
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#23252B"/>
|
||||
<SolidColorBrush x:Key="CardBorderBrush" Color="#33363F"/>
|
||||
<SolidColorBrush x:Key="ErrorTextBrush" Color="#FF6B6B"/>
|
||||
</ResourceDictionary>
|
||||
</ResourceDictionary.ThemeDictionaries>
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
+82
-17
@@ -1,42 +1,107 @@
|
||||
using System.Linq;
|
||||
using System.Globalization;
|
||||
|
||||
using Avalonia;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Data.Core;
|
||||
using Avalonia.Data.Core.Plugins;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Styling;
|
||||
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.ViewModels;
|
||||
using YKanBan.Views;
|
||||
|
||||
using Resx = YKanBan.Resources;
|
||||
|
||||
namespace YKanBan;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
public partial class App : Application {
|
||||
/// <summary>
|
||||
/// Gets the process-wide composition root, created at startup.
|
||||
/// </summary>
|
||||
public static AppServices? Services { get; private set; }
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <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() {
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
public override void OnFrameworkInitializationCompleted() {
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) {
|
||||
DisableAvaloniaDataAnnotationValidation();
|
||||
desktop.MainWindow = new MainWindow
|
||||
{
|
||||
DataContext = new MainWindowViewModel(),
|
||||
|
||||
// Startup order: apply the configured culture, its RTL flow direction
|
||||
// and the theme BEFORE creating the main window.
|
||||
Services = new AppServices();
|
||||
CultureInfo culture = ResolveCulture(Services.Config.Language);
|
||||
StartupLanguage = Services.Config.Language;
|
||||
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);
|
||||
|
||||
var viewModel = new MainWindowViewModel(Services, desktop.Args ?? []);
|
||||
desktop.MainWindow = new MainWindow {
|
||||
DataContext = viewModel,
|
||||
FlowDirection = UiFlowDirection,
|
||||
};
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
|
||||
private void DisableAvaloniaDataAnnotationValidation()
|
||||
{
|
||||
/// <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) {
|
||||
try {
|
||||
return new CultureInfo(language);
|
||||
} catch (CultureNotFoundException) {
|
||||
return new CultureInfo(AppConfig.DefaultLanguage);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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) {
|
||||
if (Current is null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Current.RequestedThemeVariant = option switch {
|
||||
ThemeOption.Light => ThemeVariant.Light,
|
||||
ThemeOption.Dark => ThemeVariant.Dark,
|
||||
_ => ThemeVariant.Default,
|
||||
};
|
||||
}
|
||||
|
||||
private static void DisableAvaloniaDataAnnotationValidation() {
|
||||
var dataValidationPluginsToRemove =
|
||||
BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray();
|
||||
|
||||
foreach (var plugin in dataValidationPluginsToRemove)
|
||||
{
|
||||
foreach (var plugin in dataValidationPluginsToRemove) {
|
||||
BindingPlugins.DataValidators.Remove(plugin);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Japanese (ja) satellite resources.
|
||||
This file is embedded beside the neutral resources; see YKanBan.csproj.
|
||||
-->
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="App_Name" xml:space="preserve">
|
||||
<value>YKanBan</value>
|
||||
</data>
|
||||
<data name="Common_Ok" xml:space="preserve">
|
||||
<value>OK</value>
|
||||
</data>
|
||||
<data name="Common_Cancel" xml:space="preserve">
|
||||
<value>キャンセル</value>
|
||||
</data>
|
||||
<data name="Common_Delete" xml:space="preserve">
|
||||
<value>削除</value>
|
||||
</data>
|
||||
<data name="Common_Edit" 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="Board_SearchPlaceholder" xml:space="preserve">
|
||||
<value>検索…</value>
|
||||
</data>
|
||||
<data name="Board_Search" xml:space="preserve">
|
||||
<value>検索</value>
|
||||
</data>
|
||||
<data name="Board_ClearSearch" xml:space="preserve">
|
||||
<value>クリア</value>
|
||||
</data>
|
||||
<data name="Board_AddColumn" xml:space="preserve">
|
||||
<value>列を追加</value>
|
||||
</data>
|
||||
<data name="Board_ColumnWidth" xml:space="preserve">
|
||||
<value>列の幅</value>
|
||||
</data>
|
||||
<data name="Board_SortCard" xml:space="preserve">
|
||||
<value>カードの並べ替え</value>
|
||||
</data>
|
||||
<data name="Board_SortColumn" xml:space="preserve">
|
||||
<value>列の並べ替え</value>
|
||||
</data>
|
||||
<data name="Board_Display" xml:space="preserve">
|
||||
<value>表示</value>
|
||||
</data>
|
||||
<data name="Board_NoColumns" xml:space="preserve">
|
||||
<value>列がまだありません。</value>
|
||||
</data>
|
||||
<data name="Board_FilterActive" xml:space="preserve">
|
||||
<value>ボードにフィルターが適用されています</value>
|
||||
</data>
|
||||
<data name="Board_FilterInactive" 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="Sort_IdAsc" xml:space="preserve">
|
||||
<value>ID 昇順</value>
|
||||
</data>
|
||||
<data name="Sort_IdDesc" xml:space="preserve">
|
||||
<value>ID 降順</value>
|
||||
</data>
|
||||
<data name="Sort_CreatedAsc" xml:space="preserve">
|
||||
<value>作成日時 昇順</value>
|
||||
</data>
|
||||
<data name="Sort_CreatedDesc" xml:space="preserve">
|
||||
<value>作成日時 降順</value>
|
||||
</data>
|
||||
<data name="Sort_UpdatedAsc" xml:space="preserve">
|
||||
<value>更新日時 昇順</value>
|
||||
</data>
|
||||
<data name="Sort_UpdatedDesc" xml:space="preserve">
|
||||
<value>更新日時 降順</value>
|
||||
</data>
|
||||
<data name="Sort_TitleAsc" xml:space="preserve">
|
||||
<value>タイトル 昇順</value>
|
||||
</data>
|
||||
<data name="Sort_TitleDesc" xml:space="preserve">
|
||||
<value>タイトル 降順</value>
|
||||
</data>
|
||||
<data name="Column_AddCard" xml:space="preserve">
|
||||
<value>カードを追加</value>
|
||||
</data>
|
||||
<data name="Column_Edit" xml:space="preserve">
|
||||
<value>編集</value>
|
||||
</data>
|
||||
<data name="Column_Delete" xml:space="preserve">
|
||||
<value>削除</value>
|
||||
</data>
|
||||
<data name="Card_Delete" xml:space="preserve">
|
||||
<value>削除</value>
|
||||
</data>
|
||||
<data name="Card_Move" xml:space="preserve">
|
||||
<value>列へ移動…</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_AddTitle" xml:space="preserve">
|
||||
<value>新しい列</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_EditTitle" xml:space="preserve">
|
||||
<value>列を編集</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_Title" xml:space="preserve">
|
||||
<value>タイトル</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_Description" xml:space="preserve">
|
||||
<value>説明</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_InvalidTitle" xml:space="preserve">
|
||||
<value>タイトルが空であるか、すでに使用されています。</value>
|
||||
</data>
|
||||
<data name="CardDialog_AddTitle" xml:space="preserve">
|
||||
<value>新しいカード</value>
|
||||
</data>
|
||||
<data name="CardDialog_EditTitle" xml:space="preserve">
|
||||
<value>カードを編集</value>
|
||||
</data>
|
||||
<data name="CardDialog_Title" xml:space="preserve">
|
||||
<value>タイトル</value>
|
||||
</data>
|
||||
<data name="CardDialog_Content" xml:space="preserve">
|
||||
<value>内容</value>
|
||||
</data>
|
||||
<data name="CardDialog_Tags" xml:space="preserve">
|
||||
<value>タグ</value>
|
||||
</data>
|
||||
<data name="CardDialog_AddTag" xml:space="preserve">
|
||||
<value>タグを追加</value>
|
||||
</data>
|
||||
<data name="CardDialog_Id" xml:space="preserve">
|
||||
<value>ID: {0}</value>
|
||||
</data>
|
||||
<data name="CardDialog_Created" xml:space="preserve">
|
||||
<value>作成日時: {0}</value>
|
||||
</data>
|
||||
<data name="CardDialog_Modified" xml:space="preserve">
|
||||
<value>更新日時: {0}</value>
|
||||
</data>
|
||||
<data name="CardDialog_TimePattern" xml:space="preserve">
|
||||
<value>yyyy年M月d日 HH:mm</value>
|
||||
</data>
|
||||
<data name="CardDialog_Error" xml:space="preserve">
|
||||
<value>カードを保存できませんでした。</value>
|
||||
</data>
|
||||
<data name="TagDialog_Title" xml:space="preserve">
|
||||
<value>タグの追加</value>
|
||||
</data>
|
||||
<data name="TagDialog_Target" xml:space="preserve">
|
||||
<value>タグ</value>
|
||||
</data>
|
||||
<data name="TagDialog_NoTargets" xml:space="preserve">
|
||||
<value>追加できるタグがありません。</value>
|
||||
</data>
|
||||
<data name="Tags_AddTag" xml:space="preserve">
|
||||
<value>タグを追加</value>
|
||||
</data>
|
||||
<data name="Tags_Count" xml:space="preserve">
|
||||
<value>{0} 個のタグ</value>
|
||||
</data>
|
||||
<data name="Tags_Empty" xml:space="preserve">
|
||||
<value>タグがまだありません。</value>
|
||||
</data>
|
||||
<data name="Tags_Usage" xml:space="preserve">
|
||||
<value>{0} 枚のカード</value>
|
||||
</data>
|
||||
<data name="TagEditor_AddTitle" xml:space="preserve">
|
||||
<value>新しいタグ</value>
|
||||
</data>
|
||||
<data name="TagEditor_EditTitle" xml:space="preserve">
|
||||
<value>タグを編集</value>
|
||||
</data>
|
||||
<data name="TagEditor_Name" xml:space="preserve">
|
||||
<value>名前</value>
|
||||
</data>
|
||||
<data name="TagEditor_Color" xml:space="preserve">
|
||||
<value>色</value>
|
||||
</data>
|
||||
<data name="TagEditor_Description" xml:space="preserve">
|
||||
<value>説明</value>
|
||||
</data>
|
||||
<data name="TagEditor_InvalidName" xml:space="preserve">
|
||||
<value>名前が空であるか、すでに使用されています。</value>
|
||||
</data>
|
||||
<data name="DeleteTag_Confirm_Title" xml:space="preserve">
|
||||
<value>タグの削除</value>
|
||||
</data>
|
||||
<data name="DeleteTag_Confirm_Message" xml:space="preserve">
|
||||
<value>タグ「{0}」を削除しますか?{1} 枚のカードから削除されます。</value>
|
||||
</data>
|
||||
<data name="MoveDialog_Title" xml:space="preserve">
|
||||
<value>カードの移動</value>
|
||||
</data>
|
||||
<data name="MoveDialog_Target" xml:space="preserve">
|
||||
<value>移動先の列</value>
|
||||
</data>
|
||||
<data name="MoveDialog_NoTargets" xml:space="preserve">
|
||||
<value>カードの移動先がありません。</value>
|
||||
</data>
|
||||
<data name="WidthPreset_Narrow" xml:space="preserve">
|
||||
<value>狭い</value>
|
||||
</data>
|
||||
<data name="WidthPreset_Standard" xml:space="preserve">
|
||||
<value>標準</value>
|
||||
</data>
|
||||
<data name="WidthPreset_Wide" xml:space="preserve">
|
||||
<value>広い</value>
|
||||
</data>
|
||||
<data name="WidthPreset_Custom" xml:space="preserve">
|
||||
<value>カスタム</value>
|
||||
</data>
|
||||
<data name="WidthDialog_Pixels" xml:space="preserve">
|
||||
<value>ピクセル(160–720)</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteColumn_Title" xml:space="preserve">
|
||||
<value>列の削除</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteColumn_Message" xml:space="preserve">
|
||||
<value>列「{0}」とその {1} 枚のカードを削除しますか?</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteCard_Title" xml:space="preserve">
|
||||
<value>カードの削除</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteCard_Message" xml:space="preserve">
|
||||
<value>カード #{0} を削除しますか?</value>
|
||||
</data>
|
||||
<data name="Confirm_Discard_Title" xml:space="preserve">
|
||||
<value>変更の破棄</value>
|
||||
</data>
|
||||
<data name="Confirm_Discard_Message" 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 <パス></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="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_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">
|
||||
<value>未着手</value>
|
||||
</data>
|
||||
<data name="PresetColumn_Todo_Description" xml:space="preserve">
|
||||
<value>計画済みで、まだ開始していないタスクです。</value>
|
||||
</data>
|
||||
<data name="PresetColumn_InProgress" xml:space="preserve">
|
||||
<value>進行中</value>
|
||||
</data>
|
||||
<data name="PresetColumn_InProgress_Description" xml:space="preserve">
|
||||
<value>現在取り組んでいるタスクです。</value>
|
||||
</data>
|
||||
<data name="PresetColumn_Done" xml:space="preserve">
|
||||
<value>完了</value>
|
||||
</data>
|
||||
<data name="PresetColumn_Done_Description" xml:space="preserve">
|
||||
<value>完了したタスクです。</value>
|
||||
</data>
|
||||
<data name="PresetTag_Bug_Name" xml:space="preserve">
|
||||
<value>バグ</value>
|
||||
</data>
|
||||
<data name="PresetTag_Bug_Description" xml:space="preserve">
|
||||
<value>機能が正しく動作していません。</value>
|
||||
</data>
|
||||
<data name="PresetTag_Documentation_Name" xml:space="preserve">
|
||||
<value>ドキュメント</value>
|
||||
</data>
|
||||
<data name="PresetTag_Documentation_Description" xml:space="preserve">
|
||||
<value>ドキュメントの改善または追加。</value>
|
||||
</data>
|
||||
<data name="PresetTag_Duplicate_Name" xml:space="preserve">
|
||||
<value>重複</value>
|
||||
</data>
|
||||
<data name="PresetTag_Duplicate_Description" xml:space="preserve">
|
||||
<value>この課題またはプルリクエストはすでに存在します。</value>
|
||||
</data>
|
||||
<data name="PresetTag_Enhancement_Name" xml:space="preserve">
|
||||
<value>機能追加</value>
|
||||
</data>
|
||||
<data name="PresetTag_Enhancement_Description" xml:space="preserve">
|
||||
<value>新しい機能やリクエスト。</value>
|
||||
</data>
|
||||
<data name="PresetTag_HelpWanted_Name" xml:space="preserve">
|
||||
<value>ヘルプ募集</value>
|
||||
</data>
|
||||
<data name="PresetTag_HelpWanted_Description" xml:space="preserve">
|
||||
<value>特別な注意が必要です。</value>
|
||||
</data>
|
||||
<data name="PresetTag_Invalid_Name" xml:space="preserve">
|
||||
<value>無効</value>
|
||||
</data>
|
||||
<data name="PresetTag_Invalid_Description" xml:space="preserve">
|
||||
<value>正しくないようです。</value>
|
||||
</data>
|
||||
<data name="PresetTag_Question_Name" xml:space="preserve">
|
||||
<value>質問</value>
|
||||
</data>
|
||||
<data name="PresetTag_Question_Description" xml:space="preserve">
|
||||
<value>さらなる情報が必要です。</value>
|
||||
</data>
|
||||
<data name="PresetTag_Wontfix_Name" xml:space="preserve">
|
||||
<value>対応予定なし</value>
|
||||
</data>
|
||||
<data name="PresetTag_Wontfix_Description" xml:space="preserve">
|
||||
<value>対応する予定はありません。</value>
|
||||
</data>
|
||||
<data name="Export_FileNamePattern" xml:space="preserve">
|
||||
<value>{0}-エクスポート-{1:yyyyMMdd-HHmmss}.md</value>
|
||||
</data>
|
||||
<data name="Export_TimePattern" xml:space="preserve">
|
||||
<value>yyyy年M月d日 HH:mm:ss</value>
|
||||
</data>
|
||||
<data name="Export_WorkspaceHeading" xml:space="preserve">
|
||||
<value># {0}</value>
|
||||
</data>
|
||||
<data name="Export_ExportedAtLine" xml:space="preserve">
|
||||
<value>> エクスポート日時:{0}</value>
|
||||
</data>
|
||||
<data name="Export_ColumnHeading" xml:space="preserve">
|
||||
<value>## 列:{0}({1})</value>
|
||||
</data>
|
||||
<data name="Export_TagsLine" xml:space="preserve">
|
||||
<value>- タグ:{0}</value>
|
||||
</data>
|
||||
<data name="Export_CreatedModifiedLine" xml:space="preserve">
|
||||
<value>- 作成日時:{0} 更新日時:{1}</value>
|
||||
</data>
|
||||
<data name="Export_TagsSummaryHeading" xml:space="preserve">
|
||||
<value>## タグ一覧</value>
|
||||
</data>
|
||||
<data name="Export_TagsTableHeader" xml:space="preserve">
|
||||
<value>| 名前 | 色 | 説明 | 使用数 |</value>
|
||||
</data>
|
||||
<data name="Export_Done_Title" xml:space="preserve">
|
||||
<value>エクスポート完了</value>
|
||||
</data>
|
||||
<data name="Export_Done_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>
|
||||
</root>
|
||||
@@ -1,5 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<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">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
@@ -12,29 +16,401 @@
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="App_Name" xml:space="preserve">
|
||||
<value>YKanBan</value>
|
||||
</data>
|
||||
<data name="Common_Ok" xml:space="preserve">
|
||||
<value>OK</value>
|
||||
</data>
|
||||
<data name="Common_Cancel" xml:space="preserve">
|
||||
<value>Cancel</value>
|
||||
</data>
|
||||
<data name="Common_Delete" xml:space="preserve">
|
||||
<value>Delete</value>
|
||||
</data>
|
||||
<data name="Common_Edit" xml:space="preserve">
|
||||
<value>Edit</value>
|
||||
</data>
|
||||
<data name="Main_Export" xml:space="preserve">
|
||||
<value>Export</value>
|
||||
</data>
|
||||
<data name="Main_Settings" xml:space="preserve">
|
||||
<value>Settings</value>
|
||||
</data>
|
||||
<data name="Main_About" xml:space="preserve">
|
||||
<value>About</value>
|
||||
</data>
|
||||
<data name="Tab_Tags" xml:space="preserve">
|
||||
<value>Tags</value>
|
||||
</data>
|
||||
<data name="Tab_Board" xml:space="preserve">
|
||||
<value>Board</value>
|
||||
</data>
|
||||
<data name="Board_SearchPlaceholder" xml:space="preserve">
|
||||
<value>Search…</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="Board_AddColumn" xml:space="preserve">
|
||||
<value>Add Column</value>
|
||||
</data>
|
||||
<data name="Board_ColumnWidth" xml:space="preserve">
|
||||
<value>Column Width</value>
|
||||
</data>
|
||||
<data name="Board_SortCard" xml:space="preserve">
|
||||
<value>Card Sort</value>
|
||||
</data>
|
||||
<data name="Board_SortColumn" xml:space="preserve">
|
||||
<value>Column Sort</value>
|
||||
</data>
|
||||
<data name="Board_Display" xml:space="preserve">
|
||||
<value>Display</value>
|
||||
</data>
|
||||
<data name="Board_NoColumns" xml:space="preserve">
|
||||
<value>No columns yet.</value>
|
||||
</data>
|
||||
<data name="Board_FilterActive" xml:space="preserve">
|
||||
<value>Board is filtered</value>
|
||||
</data>
|
||||
<data name="Board_FilterInactive" xml:space="preserve">
|
||||
<value>Board is not filtered</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="Sort_IdAsc" xml:space="preserve">
|
||||
<value>ID Ascending</value>
|
||||
</data>
|
||||
<data name="Sort_IdDesc" xml:space="preserve">
|
||||
<value>ID Descending</value>
|
||||
</data>
|
||||
<data name="Sort_CreatedAsc" xml:space="preserve">
|
||||
<value>Created Ascending</value>
|
||||
</data>
|
||||
<data name="Sort_CreatedDesc" xml:space="preserve">
|
||||
<value>Created Descending</value>
|
||||
</data>
|
||||
<data name="Sort_UpdatedAsc" xml:space="preserve">
|
||||
<value>Modified Ascending</value>
|
||||
</data>
|
||||
<data name="Sort_UpdatedDesc" xml:space="preserve">
|
||||
<value>Modified Descending</value>
|
||||
</data>
|
||||
<data name="Sort_TitleAsc" xml:space="preserve">
|
||||
<value>Title Ascending</value>
|
||||
</data>
|
||||
<data name="Sort_TitleDesc" xml:space="preserve">
|
||||
<value>Title Descending</value>
|
||||
</data>
|
||||
<data name="Column_AddCard" xml:space="preserve">
|
||||
<value>New Card</value>
|
||||
</data>
|
||||
<data name="Column_Edit" xml:space="preserve">
|
||||
<value>Edit</value>
|
||||
</data>
|
||||
<data name="Column_Delete" xml:space="preserve">
|
||||
<value>Delete</value>
|
||||
</data>
|
||||
<data name="Card_Delete" xml:space="preserve">
|
||||
<value>Delete</value>
|
||||
</data>
|
||||
<data name="Card_Move" xml:space="preserve">
|
||||
<value>Move to Column…</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_AddTitle" xml:space="preserve">
|
||||
<value>New Column</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_EditTitle" xml:space="preserve">
|
||||
<value>Edit Column</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_Title" xml:space="preserve">
|
||||
<value>Title</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_Description" xml:space="preserve">
|
||||
<value>Description</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_InvalidTitle" xml:space="preserve">
|
||||
<value>The title is empty or already used.</value>
|
||||
</data>
|
||||
<data name="CardDialog_AddTitle" xml:space="preserve">
|
||||
<value>New Card</value>
|
||||
</data>
|
||||
<data name="CardDialog_EditTitle" xml:space="preserve">
|
||||
<value>Edit Card</value>
|
||||
</data>
|
||||
<data name="CardDialog_Title" xml:space="preserve">
|
||||
<value>Title</value>
|
||||
</data>
|
||||
<data name="CardDialog_Content" xml:space="preserve">
|
||||
<value>Content</value>
|
||||
</data>
|
||||
<data name="CardDialog_Tags" xml:space="preserve">
|
||||
<value>Tags</value>
|
||||
</data>
|
||||
<data name="CardDialog_AddTag" xml:space="preserve">
|
||||
<value>Add Tag</value>
|
||||
</data>
|
||||
<data name="CardDialog_Id" xml:space="preserve">
|
||||
<value>ID: {0}</value>
|
||||
</data>
|
||||
<data name="CardDialog_Created" xml:space="preserve">
|
||||
<value>Created: {0}</value>
|
||||
</data>
|
||||
<data name="CardDialog_Modified" xml:space="preserve">
|
||||
<value>Modified: {0}</value>
|
||||
</data>
|
||||
<data name="CardDialog_TimePattern" xml:space="preserve">
|
||||
<value>yyyy-MM-dd HH:mm</value>
|
||||
</data>
|
||||
<data name="CardDialog_Error" xml:space="preserve">
|
||||
<value>Could not save the card.</value>
|
||||
</data>
|
||||
<data name="TagDialog_Title" xml:space="preserve">
|
||||
<value>Add Tag</value>
|
||||
</data>
|
||||
<data name="TagDialog_Target" xml:space="preserve">
|
||||
<value>Tag</value>
|
||||
</data>
|
||||
<data name="TagDialog_NoTargets" xml:space="preserve">
|
||||
<value>There are no more tags to add.</value>
|
||||
</data>
|
||||
<data name="Tags_AddTag" xml:space="preserve">
|
||||
<value>Add Tag</value>
|
||||
</data>
|
||||
<data name="Tags_Count" xml:space="preserve">
|
||||
<value>{0} tags</value>
|
||||
</data>
|
||||
<data name="Tags_Empty" xml:space="preserve">
|
||||
<value>No tags yet.</value>
|
||||
</data>
|
||||
<data name="Tags_Usage" xml:space="preserve">
|
||||
<value>{0} cards</value>
|
||||
</data>
|
||||
<data name="TagEditor_AddTitle" xml:space="preserve">
|
||||
<value>New Tag</value>
|
||||
</data>
|
||||
<data name="TagEditor_EditTitle" xml:space="preserve">
|
||||
<value>Edit Tag</value>
|
||||
</data>
|
||||
<data name="TagEditor_Name" xml:space="preserve">
|
||||
<value>Name</value>
|
||||
</data>
|
||||
<data name="TagEditor_Color" xml:space="preserve">
|
||||
<value>Color</value>
|
||||
</data>
|
||||
<data name="TagEditor_Description" xml:space="preserve">
|
||||
<value>Description</value>
|
||||
</data>
|
||||
<data name="TagEditor_InvalidName" xml:space="preserve">
|
||||
<value>The name is empty or already used.</value>
|
||||
</data>
|
||||
<data name="DeleteTag_Confirm_Title" xml:space="preserve">
|
||||
<value>Delete Tag</value>
|
||||
</data>
|
||||
<data name="DeleteTag_Confirm_Message" xml:space="preserve">
|
||||
<value>Delete tag "{0}"? It will be removed from {1} card(s).</value>
|
||||
</data>
|
||||
<data name="MoveDialog_Title" xml:space="preserve">
|
||||
<value>Move Card</value>
|
||||
</data>
|
||||
<data name="MoveDialog_Target" xml:space="preserve">
|
||||
<value>Target Column</value>
|
||||
</data>
|
||||
<data name="MoveDialog_NoTargets" xml:space="preserve">
|
||||
<value>There is nowhere to move this card.</value>
|
||||
</data>
|
||||
<data name="WidthPreset_Narrow" xml:space="preserve">
|
||||
<value>Narrow</value>
|
||||
</data>
|
||||
<data name="WidthPreset_Standard" xml:space="preserve">
|
||||
<value>Standard</value>
|
||||
</data>
|
||||
<data name="WidthPreset_Wide" xml:space="preserve">
|
||||
<value>Wide</value>
|
||||
</data>
|
||||
<data name="WidthPreset_Custom" xml:space="preserve">
|
||||
<value>Custom</value>
|
||||
</data>
|
||||
<data name="WidthDialog_Pixels" xml:space="preserve">
|
||||
<value>Pixels (160–720)</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteColumn_Title" xml:space="preserve">
|
||||
<value>Delete Column</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteColumn_Message" xml:space="preserve">
|
||||
<value>Delete column "{0}" and its {1} card(s)?</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteCard_Title" xml:space="preserve">
|
||||
<value>Delete Card</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteCard_Message" xml:space="preserve">
|
||||
<value>Delete card #{0}?</value>
|
||||
</data>
|
||||
<data name="Confirm_Discard_Title" xml:space="preserve">
|
||||
<value>Discard Changes</value>
|
||||
</data>
|
||||
<data name="Confirm_Discard_Message" xml:space="preserve">
|
||||
<value>Discard the unsaved changes?</value>
|
||||
</data>
|
||||
<data name="Error_Argument_Title" xml:space="preserve">
|
||||
<value>Invalid arguments</value>
|
||||
</data>
|
||||
<data name="Error_Argument_Message" xml:space="preserve">
|
||||
<value>YKanBan was started with invalid command-line arguments.</value>
|
||||
</data>
|
||||
<data name="Error_Argument_Usage" xml:space="preserve">
|
||||
<value>Usage: ykanban <path></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="Settings_Title" xml:space="preserve">
|
||||
<value>Settings</value>
|
||||
</data>
|
||||
<data name="Settings_Language" xml:space="preserve">
|
||||
<value>Language</value>
|
||||
</data>
|
||||
<data name="Settings_Language_RestartNotice" xml:space="preserve">
|
||||
<value>Takes effect after restart</value>
|
||||
</data>
|
||||
<data name="Settings_Theme" xml:space="preserve">
|
||||
<value>Theme</value>
|
||||
</data>
|
||||
<data name="Settings_ThemeLight" xml:space="preserve">
|
||||
<value>Light</value>
|
||||
</data>
|
||||
<data name="Settings_ThemeDark" xml:space="preserve">
|
||||
<value>Dark</value>
|
||||
</data>
|
||||
<data name="Settings_ThemeFollowSystem" xml:space="preserve">
|
||||
<value>Follow System</value>
|
||||
</data>
|
||||
<data name="Settings_Confirmations" xml:space="preserve">
|
||||
<value>Confirmations</value>
|
||||
</data>
|
||||
<data name="Settings_ConfirmDeleteCard" xml:space="preserve">
|
||||
<value>Ask before deleting a card</value>
|
||||
</data>
|
||||
<data name="Settings_ConfirmDeleteColumn" xml:space="preserve">
|
||||
<value>Ask before deleting a column</value>
|
||||
</data>
|
||||
<data name="Settings_ConfirmDeleteTag" xml:space="preserve">
|
||||
<value>Ask before deleting a tag</value>
|
||||
</data>
|
||||
<data name="Settings_ConfirmDiscardEdit" xml:space="preserve">
|
||||
<value>Ask before discarding card edits</value>
|
||||
</data>
|
||||
<data name="About_Title" xml:space="preserve">
|
||||
<value>About</value>
|
||||
</data>
|
||||
<data name="About_Version" xml:space="preserve">
|
||||
<value>Version {0}</value>
|
||||
</data>
|
||||
<data name="About_Repository" xml:space="preserve">
|
||||
<value>Repository</value>
|
||||
</data>
|
||||
<data name="About_License" xml:space="preserve">
|
||||
<value>License</value>
|
||||
</data>
|
||||
<data name="About_LicenseValue" xml:space="preserve">
|
||||
<value>MIT</value>
|
||||
</data>
|
||||
<data name="PresetColumn_Todo" xml:space="preserve">
|
||||
<value>To Do</value>
|
||||
</data>
|
||||
<data name="PresetColumn_Todo_Description" xml:space="preserve">
|
||||
<value>Tasks that are planned but not started.</value>
|
||||
</data>
|
||||
<data name="PresetColumn_InProgress" xml:space="preserve">
|
||||
<value>In Progress</value>
|
||||
</data>
|
||||
<data name="PresetColumn_InProgress_Description" xml:space="preserve">
|
||||
<value>Tasks that are currently being worked on.</value>
|
||||
</data>
|
||||
<data name="PresetColumn_Done" xml:space="preserve">
|
||||
<value>Done</value>
|
||||
</data>
|
||||
<data name="PresetColumn_Done_Description" xml:space="preserve">
|
||||
<value>Tasks that have been completed.</value>
|
||||
</data>
|
||||
<data name="PresetTag_Bug_Name" xml:space="preserve">
|
||||
<value>bug</value>
|
||||
</data>
|
||||
<data name="PresetTag_Bug_Description" xml:space="preserve">
|
||||
<value>Something isn't working</value>
|
||||
</data>
|
||||
<data name="PresetTag_Documentation_Name" xml:space="preserve">
|
||||
<value>documentation</value>
|
||||
</data>
|
||||
<data name="PresetTag_Documentation_Description" xml:space="preserve">
|
||||
<value>Improvements or additions to documentation</value>
|
||||
</data>
|
||||
<data name="PresetTag_Duplicate_Name" xml:space="preserve">
|
||||
<value>duplicate</value>
|
||||
</data>
|
||||
<data name="PresetTag_Duplicate_Description" xml:space="preserve">
|
||||
<value>This issue or pull request already exists</value>
|
||||
</data>
|
||||
<data name="PresetTag_Enhancement_Name" xml:space="preserve">
|
||||
<value>enhancement</value>
|
||||
</data>
|
||||
<data name="PresetTag_Enhancement_Description" xml:space="preserve">
|
||||
<value>New feature or request</value>
|
||||
</data>
|
||||
<data name="PresetTag_HelpWanted_Name" xml:space="preserve">
|
||||
<value>help-wanted</value>
|
||||
</data>
|
||||
<data name="PresetTag_HelpWanted_Description" xml:space="preserve">
|
||||
<value>Extra attention is needed</value>
|
||||
</data>
|
||||
<data name="PresetTag_Invalid_Name" xml:space="preserve">
|
||||
<value>invalid</value>
|
||||
</data>
|
||||
<data name="PresetTag_Invalid_Description" xml:space="preserve">
|
||||
<value>This doesn't seem right</value>
|
||||
</data>
|
||||
<data name="PresetTag_Question_Name" xml:space="preserve">
|
||||
<value>question</value>
|
||||
</data>
|
||||
<data name="PresetTag_Question_Description" xml:space="preserve">
|
||||
<value>Further information is requested</value>
|
||||
</data>
|
||||
<data name="PresetTag_Wontfix_Name" xml:space="preserve">
|
||||
<value>wontfix</value>
|
||||
</data>
|
||||
<data name="PresetTag_Wontfix_Description" xml:space="preserve">
|
||||
<value>This will not be worked on</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>
|
||||
<value>> Exported at: {0}</value>
|
||||
</data>
|
||||
<data name="Export_ColumnHeading" xml:space="preserve">
|
||||
<value>## Column: {0} ({1})</value>
|
||||
@@ -51,4 +427,34 @@
|
||||
<data name="Export_TagsTableHeader" xml:space="preserve">
|
||||
<value>| Name | Color | Description | Usage |</value>
|
||||
</data>
|
||||
<data name="Export_Done_Title" xml:space="preserve">
|
||||
<value>Export Complete</value>
|
||||
</data>
|
||||
<data name="Export_Done_Message" xml:space="preserve">
|
||||
<value>Exported to: {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>
|
||||
</root>
|
||||
@@ -1,5 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Simplified Chinese (zh-Hans) satellite resources.
|
||||
This file is embedded beside the neutral resources; see YKanBan.csproj.
|
||||
-->
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
@@ -12,24 +16,396 @@
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</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="Common_Delete" xml:space="preserve">
|
||||
<value>删除</value>
|
||||
</data>
|
||||
<data name="Common_Edit" 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="Board_SearchPlaceholder" xml:space="preserve">
|
||||
<value>搜索…</value>
|
||||
</data>
|
||||
<data name="Board_Search" xml:space="preserve">
|
||||
<value>搜索</value>
|
||||
</data>
|
||||
<data name="Board_ClearSearch" xml:space="preserve">
|
||||
<value>清空</value>
|
||||
</data>
|
||||
<data name="Board_AddColumn" xml:space="preserve">
|
||||
<value>新增列</value>
|
||||
</data>
|
||||
<data name="Board_ColumnWidth" xml:space="preserve">
|
||||
<value>列宽</value>
|
||||
</data>
|
||||
<data name="Board_SortCard" xml:space="preserve">
|
||||
<value>卡片排序</value>
|
||||
</data>
|
||||
<data name="Board_SortColumn" xml:space="preserve">
|
||||
<value>列排序</value>
|
||||
</data>
|
||||
<data name="Board_Display" xml:space="preserve">
|
||||
<value>显示</value>
|
||||
</data>
|
||||
<data name="Board_NoColumns" xml:space="preserve">
|
||||
<value>还没有列。</value>
|
||||
</data>
|
||||
<data name="Board_FilterActive" xml:space="preserve">
|
||||
<value>看板处于过滤状态</value>
|
||||
</data>
|
||||
<data name="Board_FilterInactive" 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="Sort_IdAsc" xml:space="preserve">
|
||||
<value>ID 正序</value>
|
||||
</data>
|
||||
<data name="Sort_IdDesc" xml:space="preserve">
|
||||
<value>ID 倒序</value>
|
||||
</data>
|
||||
<data name="Sort_CreatedAsc" xml:space="preserve">
|
||||
<value>创建时间正序</value>
|
||||
</data>
|
||||
<data name="Sort_CreatedDesc" xml:space="preserve">
|
||||
<value>创建时间倒序</value>
|
||||
</data>
|
||||
<data name="Sort_UpdatedAsc" xml:space="preserve">
|
||||
<value>修改时间正序</value>
|
||||
</data>
|
||||
<data name="Sort_UpdatedDesc" xml:space="preserve">
|
||||
<value>修改时间倒序</value>
|
||||
</data>
|
||||
<data name="Sort_TitleAsc" xml:space="preserve">
|
||||
<value>标题正序</value>
|
||||
</data>
|
||||
<data name="Sort_TitleDesc" xml:space="preserve">
|
||||
<value>标题倒序</value>
|
||||
</data>
|
||||
<data name="Column_AddCard" xml:space="preserve">
|
||||
<value>新建卡片</value>
|
||||
</data>
|
||||
<data name="Column_Edit" xml:space="preserve">
|
||||
<value>编辑</value>
|
||||
</data>
|
||||
<data name="Column_Delete" xml:space="preserve">
|
||||
<value>删除</value>
|
||||
</data>
|
||||
<data name="Card_Delete" xml:space="preserve">
|
||||
<value>删除</value>
|
||||
</data>
|
||||
<data name="Card_Move" xml:space="preserve">
|
||||
<value>移动到列…</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_AddTitle" xml:space="preserve">
|
||||
<value>新增列</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_EditTitle" xml:space="preserve">
|
||||
<value>编辑列</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_Title" xml:space="preserve">
|
||||
<value>标题</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_Description" xml:space="preserve">
|
||||
<value>描述</value>
|
||||
</data>
|
||||
<data name="ColumnDialog_InvalidTitle" xml:space="preserve">
|
||||
<value>标题为空或已被使用。</value>
|
||||
</data>
|
||||
<data name="CardDialog_AddTitle" xml:space="preserve">
|
||||
<value>新增卡片</value>
|
||||
</data>
|
||||
<data name="CardDialog_EditTitle" xml:space="preserve">
|
||||
<value>编辑卡片</value>
|
||||
</data>
|
||||
<data name="CardDialog_Title" xml:space="preserve">
|
||||
<value>标题</value>
|
||||
</data>
|
||||
<data name="CardDialog_Content" xml:space="preserve">
|
||||
<value>内容</value>
|
||||
</data>
|
||||
<data name="CardDialog_Tags" xml:space="preserve">
|
||||
<value>标签</value>
|
||||
</data>
|
||||
<data name="CardDialog_AddTag" xml:space="preserve">
|
||||
<value>添加标签</value>
|
||||
</data>
|
||||
<data name="CardDialog_Id" xml:space="preserve">
|
||||
<value>编号:{0}</value>
|
||||
</data>
|
||||
<data name="CardDialog_Created" xml:space="preserve">
|
||||
<value>创建:{0}</value>
|
||||
</data>
|
||||
<data name="CardDialog_Modified" xml:space="preserve">
|
||||
<value>修改:{0}</value>
|
||||
</data>
|
||||
<data name="CardDialog_TimePattern" xml:space="preserve">
|
||||
<value>yyyy年M月d日 HH:mm</value>
|
||||
</data>
|
||||
<data name="CardDialog_Error" xml:space="preserve">
|
||||
<value>无法保存卡片。</value>
|
||||
</data>
|
||||
<data name="TagDialog_Title" xml:space="preserve">
|
||||
<value>添加标签</value>
|
||||
</data>
|
||||
<data name="TagDialog_Target" xml:space="preserve">
|
||||
<value>标签</value>
|
||||
</data>
|
||||
<data name="TagDialog_NoTargets" xml:space="preserve">
|
||||
<value>没有可添加的标签。</value>
|
||||
</data>
|
||||
<data name="Tags_AddTag" xml:space="preserve">
|
||||
<value>添加标签</value>
|
||||
</data>
|
||||
<data name="Tags_Count" xml:space="preserve">
|
||||
<value>{0} 个标签</value>
|
||||
</data>
|
||||
<data name="Tags_Empty" xml:space="preserve">
|
||||
<value>还没有标签。</value>
|
||||
</data>
|
||||
<data name="Tags_Usage" xml:space="preserve">
|
||||
<value>{0} 张卡片</value>
|
||||
</data>
|
||||
<data name="TagEditor_AddTitle" xml:space="preserve">
|
||||
<value>新建标签</value>
|
||||
</data>
|
||||
<data name="TagEditor_EditTitle" xml:space="preserve">
|
||||
<value>编辑标签</value>
|
||||
</data>
|
||||
<data name="TagEditor_Name" xml:space="preserve">
|
||||
<value>名称</value>
|
||||
</data>
|
||||
<data name="TagEditor_Color" xml:space="preserve">
|
||||
<value>颜色</value>
|
||||
</data>
|
||||
<data name="TagEditor_Description" xml:space="preserve">
|
||||
<value>描述</value>
|
||||
</data>
|
||||
<data name="TagEditor_InvalidName" xml:space="preserve">
|
||||
<value>名称为空或已被使用。</value>
|
||||
</data>
|
||||
<data name="DeleteTag_Confirm_Title" xml:space="preserve">
|
||||
<value>删除标签</value>
|
||||
</data>
|
||||
<data name="DeleteTag_Confirm_Message" xml:space="preserve">
|
||||
<value>删除标签“{0}”?将从 {1} 张卡片中移除。</value>
|
||||
</data>
|
||||
<data name="MoveDialog_Title" xml:space="preserve">
|
||||
<value>移动卡片</value>
|
||||
</data>
|
||||
<data name="MoveDialog_Target" xml:space="preserve">
|
||||
<value>目标列</value>
|
||||
</data>
|
||||
<data name="MoveDialog_NoTargets" xml:space="preserve">
|
||||
<value>没有可移动到的目标列。</value>
|
||||
</data>
|
||||
<data name="WidthPreset_Narrow" xml:space="preserve">
|
||||
<value>窄</value>
|
||||
</data>
|
||||
<data name="WidthPreset_Standard" xml:space="preserve">
|
||||
<value>标准</value>
|
||||
</data>
|
||||
<data name="WidthPreset_Wide" xml:space="preserve">
|
||||
<value>宽</value>
|
||||
</data>
|
||||
<data name="WidthPreset_Custom" xml:space="preserve">
|
||||
<value>自定义</value>
|
||||
</data>
|
||||
<data name="WidthDialog_Pixels" xml:space="preserve">
|
||||
<value>像素(160–720)</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteColumn_Title" xml:space="preserve">
|
||||
<value>删除列</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteColumn_Message" xml:space="preserve">
|
||||
<value>删除列“{0}”及其 {1} 张卡片?</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteCard_Title" xml:space="preserve">
|
||||
<value>删除卡片</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteCard_Message" xml:space="preserve">
|
||||
<value>删除卡片 #{0}?</value>
|
||||
</data>
|
||||
<data name="Confirm_Discard_Title" xml:space="preserve">
|
||||
<value>放弃修改</value>
|
||||
</data>
|
||||
<data name="Confirm_Discard_Message" 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 <路径></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="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_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">
|
||||
<value>待办</value>
|
||||
</data>
|
||||
<data name="PresetColumn_Todo_Description" xml:space="preserve">
|
||||
<value>已计划但尚未开始的任务。</value>
|
||||
</data>
|
||||
<data name="PresetColumn_InProgress" xml:space="preserve">
|
||||
<value>进行中</value>
|
||||
</data>
|
||||
<data name="PresetColumn_InProgress_Description" xml:space="preserve">
|
||||
<value>正在处理中的任务。</value>
|
||||
</data>
|
||||
<data name="PresetColumn_Done" xml:space="preserve">
|
||||
<value>已完成</value>
|
||||
</data>
|
||||
<data name="PresetColumn_Done_Description" xml:space="preserve">
|
||||
<value>已完成的任务。</value>
|
||||
</data>
|
||||
<data name="PresetTag_Bug_Name" xml:space="preserve">
|
||||
<value>缺陷</value>
|
||||
</data>
|
||||
<data name="PresetTag_Bug_Description" xml:space="preserve">
|
||||
<value>功能没有正常工作</value>
|
||||
</data>
|
||||
<data name="PresetTag_Documentation_Name" xml:space="preserve">
|
||||
<value>文档</value>
|
||||
</data>
|
||||
<data name="PresetTag_Documentation_Description" xml:space="preserve">
|
||||
<value>文档的改进或补充</value>
|
||||
</data>
|
||||
<data name="PresetTag_Duplicate_Name" xml:space="preserve">
|
||||
<value>重复</value>
|
||||
</data>
|
||||
<data name="PresetTag_Duplicate_Description" xml:space="preserve">
|
||||
<value>该问题或请求已存在</value>
|
||||
</data>
|
||||
<data name="PresetTag_Enhancement_Name" xml:space="preserve">
|
||||
<value>增强</value>
|
||||
</data>
|
||||
<data name="PresetTag_Enhancement_Description" xml:space="preserve">
|
||||
<value>新功能或请求</value>
|
||||
</data>
|
||||
<data name="PresetTag_HelpWanted_Name" xml:space="preserve">
|
||||
<value>需要帮助</value>
|
||||
</data>
|
||||
<data name="PresetTag_HelpWanted_Description" xml:space="preserve">
|
||||
<value>需要额外关注</value>
|
||||
</data>
|
||||
<data name="PresetTag_Invalid_Name" xml:space="preserve">
|
||||
<value>无效</value>
|
||||
</data>
|
||||
<data name="PresetTag_Invalid_Description" xml:space="preserve">
|
||||
<value>似乎不正确</value>
|
||||
</data>
|
||||
<data name="PresetTag_Question_Name" xml:space="preserve">
|
||||
<value>疑问</value>
|
||||
</data>
|
||||
<data name="PresetTag_Question_Description" xml:space="preserve">
|
||||
<value>需要进一步信息</value>
|
||||
</data>
|
||||
<data name="PresetTag_Wontfix_Name" xml:space="preserve">
|
||||
<value>不予处理</value>
|
||||
</data>
|
||||
<data name="PresetTag_Wontfix_Description" xml:space="preserve">
|
||||
<value>不会被处理</value>
|
||||
</data>
|
||||
<data name="Export_FileNamePattern" xml:space="preserve">
|
||||
<value>{0}-导出-{1:yyyyMMdd-HHmmss}.md</value>
|
||||
</data>
|
||||
<data name="Export_TimePattern" xml:space="preserve">
|
||||
<value>yyyy年M月d日 HH:mm</value>
|
||||
</data>
|
||||
<data name="Export_CardTimePattern" xml:space="preserve">
|
||||
<value>yyyy年M月d日 HH:mm</value>
|
||||
</data>
|
||||
<data name="Export_WorkspaceHeading" xml:space="preserve">
|
||||
<value># {0}</value>
|
||||
</data>
|
||||
@@ -51,4 +427,34 @@
|
||||
<data name="Export_TagsTableHeader" xml:space="preserve">
|
||||
<value>| 名称 | 颜色 | 描述 | 使用数 |</value>
|
||||
</data>
|
||||
<data name="Export_Done_Title" xml:space="preserve">
|
||||
<value>导出完成</value>
|
||||
</data>
|
||||
<data name="Export_Done_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>
|
||||
</root>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 172 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 48 KiB |
@@ -1,54 +1,59 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.Export;
|
||||
|
||||
/// <summary>
|
||||
/// Generates the human-readable Markdown snapshot of a whole board. All
|
||||
/// template text and time formats come from the ResX resources in the
|
||||
/// current UI language; the export timestamp uses the per-language pattern,
|
||||
/// card timestamps use the shared minute-precision pattern. The output is
|
||||
/// meant for reading only — there is no re-import.
|
||||
/// template text and the one time format come from the ResX resources in the
|
||||
/// current UI language; every timestamp (export time and card created/modified
|
||||
/// times) uses that per-language pattern. The document uses the platform's
|
||||
/// newline. Card bodies and column descriptions are emitted verbatim; column and
|
||||
/// card titles are collapsed to one line; tag names become inline code with a
|
||||
/// long enough backtick fence; tag table cells escape '\' and '|' and turn line
|
||||
/// breaks into <br>. The output is meant for reading only — there is no
|
||||
/// re-import.
|
||||
/// </summary>
|
||||
public static class MarkdownExporter
|
||||
{
|
||||
/// <summary>Renders the whole board to Markdown.</summary>
|
||||
public static class MarkdownExporter {
|
||||
/// <summary>
|
||||
/// Renders the whole board to Markdown.
|
||||
/// </summary>
|
||||
/// <param name="workspaceName">Workspace display name (the folder name).</param>
|
||||
/// <param name="columns">All columns, in id order; empty columns are kept.</param>
|
||||
/// <param name="cards">All cards; grouped by column, id order within a column.</param>
|
||||
/// <param name="tags">All tags with usage counts, in id order.</param>
|
||||
/// <param name="exportedAt">Export moment in local time.</param>
|
||||
/// <returns>The Markdown document.</returns>
|
||||
public static string Export(
|
||||
string workspaceName,
|
||||
IReadOnlyList<ColumnModel> columns,
|
||||
IReadOnlyList<CardModel> cards,
|
||||
IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
|
||||
DateTimeOffset exportedAt)
|
||||
{
|
||||
DateTimeOffset exportedAt) {
|
||||
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
|
||||
|
||||
var builder = new StringBuilder();
|
||||
|
||||
// Header: workspace name and the export timestamp in the UI language's format.
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_WorkspaceHeading, workspaceName));
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_WorkspaceHeading, SingleLine(workspaceName)));
|
||||
builder.AppendLine(string.Format(
|
||||
culture, Resources.Export_ExportedAtLine, exportedAt.ToString(Resources.Export_TimePattern, culture)));
|
||||
builder.AppendLine();
|
||||
|
||||
// Board body: every column in id order, empty ones included.
|
||||
foreach (ColumnModel column in columns)
|
||||
{
|
||||
IReadOnlyList<CardModel> cardsInColumn = cards.Where(card => card.ColumnId == column.Id).ToArray();
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, column.Title, cardsInColumn.Count));
|
||||
if (column.Description.Length > 0)
|
||||
{
|
||||
builder.AppendLine(SingleLine(column.Description));
|
||||
// Board body: every column in id order, empty ones included; independent of
|
||||
// the board's search filter and card sort option.
|
||||
foreach (ColumnModel column in columns.OrderBy(column => column.Id)) {
|
||||
IReadOnlyList<CardModel> cardsInColumn =
|
||||
cards.Where(card => card.ColumnId == column.Id).OrderBy(card => card.Id).ToArray();
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, SingleLine(column.Title), cardsInColumn.Count));
|
||||
if (column.Description.Length > 0) {
|
||||
builder.AppendLine(column.Description);
|
||||
}
|
||||
builder.AppendLine();
|
||||
|
||||
foreach (CardModel card in cardsInColumn)
|
||||
{
|
||||
foreach (CardModel card in cardsInColumn) {
|
||||
AppendCard(builder, card, culture);
|
||||
}
|
||||
}
|
||||
@@ -57,61 +62,122 @@ public static class MarkdownExporter
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Builds the default export file name in the UI language, e.g. "MyRepo-export-20260930-142537.md".</summary>
|
||||
public static string BuildFileName(string workspaceName, DateTimeOffset exportedAt)
|
||||
{
|
||||
/// <summary>
|
||||
/// Builds the default export file name in the UI language, for example
|
||||
/// "MyRepo-export-20260930-142537.md". Characters that are not allowed in a
|
||||
/// file name on any supported platform are dropped from the workspace name
|
||||
/// (a workspace at a drive root is named "D:\"); a name left empty falls
|
||||
/// back to the application name.
|
||||
/// </summary>
|
||||
/// <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) {
|
||||
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
|
||||
return string.Format(culture, Resources.Export_FileNamePattern, workspaceName, exportedAt);
|
||||
string safeName = new(workspaceName.Where(character => !IsInvalidFileNameCharacter(character)).ToArray());
|
||||
if (safeName.Length == 0) {
|
||||
safeName = Resources.App_Name;
|
||||
}
|
||||
return string.Format(culture, Resources.Export_FileNamePattern, safeName, exportedAt);
|
||||
}
|
||||
|
||||
/// <summary>Appends one card block: heading, body, tags line, timestamps line.</summary>
|
||||
private static void AppendCard(StringBuilder builder, CardModel card, CultureInfo culture)
|
||||
{
|
||||
/// <summary>
|
||||
/// Tells whether a character is invalid in a file name on Windows, Linux or
|
||||
/// macOS; the Windows set is the widest, so the result is the same on every platform.
|
||||
/// </summary>
|
||||
/// <param name="character">The character to test.</param>
|
||||
/// <returns><see langword="true"/> when the character must not appear in a file name.</returns>
|
||||
private static bool IsInvalidFileNameCharacter(char character) =>
|
||||
character < ' ' || character is '<' or '>' or ':' or '"' or '/' or '\\' or '|' or '?' or '*';
|
||||
|
||||
/// <summary>
|
||||
/// 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) {
|
||||
// Heading: "#id title"; an untitled card shows only the id.
|
||||
builder.AppendLine(card.Title.Length == 0
|
||||
? $"### #{card.Id}"
|
||||
: $"### #{card.Id} {SingleLine(card.Title)}");
|
||||
|
||||
if (card.Content.Length > 0)
|
||||
{
|
||||
if (card.Content.Length > 0) {
|
||||
builder.AppendLine(card.Content);
|
||||
}
|
||||
|
||||
if (card.Tags.Count > 0)
|
||||
{
|
||||
string names = string.Join(" ", card.Tags.Select(tag => $"`{tag.Name}`"));
|
||||
if (card.Tags.Count > 0) {
|
||||
string names = string.Join(" ", card.Tags.Select(tag => InlineCode(tag.Name)));
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_TagsLine, names));
|
||||
}
|
||||
|
||||
string created = ToLocalTime(card.CreatedAt).ToString(Resources.Export_CardTimePattern, culture);
|
||||
string updated = ToLocalTime(card.UpdatedAt).ToString(Resources.Export_CardTimePattern, culture);
|
||||
string created = ToLocalTime(card.CreatedAt).ToString(Resources.Export_TimePattern, culture);
|
||||
string updated = ToLocalTime(card.UpdatedAt).ToString(Resources.Export_TimePattern, culture);
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_CreatedModifiedLine, created, updated));
|
||||
builder.AppendLine();
|
||||
}
|
||||
|
||||
/// <summary>Appends the tag summary table with usage counts; tags with zero usage are included.</summary>
|
||||
/// <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(
|
||||
StringBuilder builder,
|
||||
IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
|
||||
CultureInfo culture)
|
||||
{
|
||||
CultureInfo culture) {
|
||||
builder.AppendLine(Resources.Export_TagsSummaryHeading);
|
||||
builder.AppendLine(Resources.Export_TagsTableHeader);
|
||||
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.
|
||||
builder.AppendLine($"| {Cell(tag.Name)} | {tag.Color} | {Cell(tag.Description)} | {usage} |");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Formats a table cell: single line with escaped pipe characters.</summary>
|
||||
private static string Cell(string text) => SingleLine(text).Replace("|", "\\|");
|
||||
/// <summary>
|
||||
/// Formats a table cell: escaped backslashes and pipe characters, line breaks as <br>.
|
||||
/// </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>Collapses line breaks so the text stays on one Markdown line.</summary>
|
||||
/// <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>
|
||||
/// 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", " ");
|
||||
|
||||
/// <summary>Converts stored Unix seconds to a local-time DateTimeOffset.</summary>
|
||||
/// <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) =>
|
||||
DateTimeOffset.FromUnixTimeSeconds(unixSeconds).ToLocalTime();
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace YKanBan.Launching;
|
||||
|
||||
/// <summary>
|
||||
/// Parses raw command-line arguments. The only accepted form is a single,
|
||||
/// non-blank, existing workspace folder (<c>ykanban <path></c>); zero
|
||||
/// arguments, more than one argument, a blank argument, an argument starting
|
||||
/// with <c>-</c> (any option form, <c>--help</c> included), a malformed path or
|
||||
/// a path that is not an existing folder is rejected as an argument error. A
|
||||
/// relative path is resolved against the process's current directory.
|
||||
/// </summary>
|
||||
public static class LaunchArguments {
|
||||
/// <summary>
|
||||
/// Tries to parse command-line arguments following the
|
||||
/// <c>ykanban <path></c> contract.
|
||||
/// </summary>
|
||||
/// <param name="arguments">The raw arguments, excluding the executable name.</param>
|
||||
/// <param name="folderPath">The absolute, existing workspace folder 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;
|
||||
}
|
||||
|
||||
string fullPath;
|
||||
try {
|
||||
fullPath = Path.GetFullPath(arguments[0]);
|
||||
} catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) {
|
||||
// A path the OS cannot even represent is a bad argument, not a missing folder.
|
||||
return false;
|
||||
}
|
||||
|
||||
// Existence is checked here so every caller gets an already validated folder.
|
||||
if (!Directory.Exists(fullPath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
folderPath = fullPath;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
namespace YKanBan.Models;
|
||||
|
||||
/// <summary>A card with its assigned tags loaded.</summary>
|
||||
/// <summary>
|
||||
/// A card with its assigned tags loaded.
|
||||
/// </summary>
|
||||
/// <param name="Id">Row id.</param>
|
||||
/// <param name="ColumnId">Owning column.</param>
|
||||
/// <param name="Title">Possibly empty; the empty string is the canonical "no title".</param>
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
namespace YKanBan.Models;
|
||||
|
||||
/// <summary>A board column as stored in the workspace database.</summary>
|
||||
/// <summary>
|
||||
/// A board column as stored in the workspace database.
|
||||
/// </summary>
|
||||
/// <param name="Id">Row id.</param>
|
||||
/// <param name="Title">Non-empty unique title.</param>
|
||||
/// <param name="Title">Non-empty, table-unique title.</param>
|
||||
/// <param name="Description">Free-form description, possibly empty.</param>
|
||||
/// <param name="CreatedAt">Unix seconds of creation.</param>
|
||||
/// <param name="UpdatedAt">Unix seconds of the last title/description change.</param>
|
||||
|
||||
+42
-25
@@ -1,60 +1,77 @@
|
||||
namespace YKanBan.Models;
|
||||
|
||||
/// <summary>
|
||||
/// An RGB color without an alpha channel, stored as one byte per component
|
||||
/// — mirroring the color structures of WinForms, WPF and Avalonia minus
|
||||
/// the alpha byte. The type is total: every combination of components is
|
||||
/// valid, and all validation happens at the text boundary. Converts to and
|
||||
/// from the persisted "#RRGGBB" text form; ToString always produces the
|
||||
/// canonical lowercase form (e.g. "#ff0a00").
|
||||
/// An RGB color without an alpha channel, stored as one byte per component —
|
||||
/// mirroring the color structures of WinForms, WPF and Avalonia minus the
|
||||
/// alpha byte. The type is total: every combination of components is valid,
|
||||
/// and all validation happens at the text boundary.
|
||||
///
|
||||
/// It converts to and from the persisted "#RRGGBB" text form; <see cref="ToString"/>
|
||||
/// 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>
|
||||
public readonly record struct RgbColor(byte R, byte G, byte B)
|
||||
{
|
||||
/// <summary>Parses a "#RRGGBB" text with case-insensitive hex digits.</summary>
|
||||
public readonly record struct RgbColor(byte R, byte G, byte B) {
|
||||
/// <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>
|
||||
public static RgbColor Parse(string text) =>
|
||||
TryParse(text, out RgbColor color)
|
||||
? color
|
||||
: throw new FormatException($"Not a valid #RRGGBB color: '{text}'.");
|
||||
|
||||
/// <summary>Attempts to parse a "#RRGGBB" text; no whitespace tolerance.</summary>
|
||||
public static bool TryParse(string? text, out RgbColor color)
|
||||
{
|
||||
/// <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) {
|
||||
color = default;
|
||||
if (text is not { Length: 7 } || text[0] != '#')
|
||||
{
|
||||
if (text is not { Length: 7 } || text[0] != '#') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Two hex digits per component: R, G, B.
|
||||
if (TryHexPair(text, 1, out byte r) && TryHexPair(text, 3, out byte g) && TryHexPair(text, 5, out byte b))
|
||||
{
|
||||
if (TryHexPair(text, 1, out byte r) && TryHexPair(text, 3, out byte g) && TryHexPair(text, 5, out byte b)) {
|
||||
color = new RgbColor(r, g, b);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Returns the canonical lowercase "#RRGGBB" form used by the database and exports.</summary>
|
||||
/// <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}";
|
||||
|
||||
/// <summary>Parses exactly two hex digits into a byte value.</summary>
|
||||
private static bool TryHexPair(string text, int start, out 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) {
|
||||
value = 0;
|
||||
int high = HexDigit(text[start]);
|
||||
int low = HexDigit(text[start + 1]);
|
||||
if (high < 0 || low < 0)
|
||||
{
|
||||
if (high < 0 || low < 0) {
|
||||
return false;
|
||||
}
|
||||
value = (byte)((high << 4) | low);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Converts one hex digit to its value; -1 for any other character.</summary>
|
||||
private static int HexDigit(char character) => character switch
|
||||
{
|
||||
/// <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 {
|
||||
>= '0' and <= '9' => character - '0',
|
||||
>= 'a' and <= 'f' => character - 'a' + 10,
|
||||
>= 'A' and <= 'F' => character - 'A' + 10,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
namespace YKanBan.Models;
|
||||
|
||||
/// <summary>A tag assignable to cards. Tags are never garbage-collected: unreferenced tags stay until deleted explicitly.</summary>
|
||||
/// <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="Name">Arbitrary non-empty text; no charset or length rules.</param>
|
||||
/// <param name="Color">The tag color; persisted as #RRGGBB text.</param>
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
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 '\\';
|
||||
}
|
||||
+13
-6
@@ -1,14 +1,21 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using Avalonia;
|
||||
|
||||
namespace YKanBan;
|
||||
|
||||
sealed class Program
|
||||
{
|
||||
sealed class Program {
|
||||
// Initialization code. Don't use any Avalonia, third-party APIs or any
|
||||
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
|
||||
// yet and stuff might break.
|
||||
[STAThread]
|
||||
public static void Main(string[] args) => BuildAvaloniaApp()
|
||||
.StartWithClassicDesktopLifetime(args);
|
||||
public static void Main(string[] args) {
|
||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
|
||||
// The lifetime has ended: persist the configuration once, then release services.
|
||||
App.Services?.SaveConfiguration();
|
||||
App.Services?.Dispose();
|
||||
}
|
||||
|
||||
// Avalonia configuration, don't remove; also used by visual designer.
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
=> AppBuilder.Configure<App>()
|
||||
.UsePlatformDetect()
|
||||
|
||||
+118
-30
@@ -2,35 +2,54 @@ using Pidgin;
|
||||
|
||||
namespace YKanBan.Search;
|
||||
|
||||
/// <summary>Lexical tokens of the search syntax.</summary>
|
||||
public abstract record SearchToken
|
||||
{
|
||||
/// <summary>A bare word; qualifier detection happens later from the text.</summary>
|
||||
/// <summary>
|
||||
/// Lexical tokens of the search syntax.
|
||||
/// </summary>
|
||||
public abstract record SearchToken {
|
||||
/// <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;
|
||||
|
||||
/// <summary>A quoted phrase with escapes already resolved.</summary>
|
||||
/// <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;
|
||||
|
||||
/// <summary>An opening parenthesis.</summary>
|
||||
/// <summary>
|
||||
/// An opening parenthesis.
|
||||
/// </summary>
|
||||
public sealed record OpenParen : SearchToken;
|
||||
|
||||
/// <summary>A closing parenthesis.</summary>
|
||||
/// <summary>
|
||||
/// A closing parenthesis.
|
||||
/// </summary>
|
||||
public sealed record CloseParen : SearchToken;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pidgin-based lexer for the search syntax. Splits the input into words,
|
||||
/// quoted phrases (with \" and \\ escapes) and parentheses; whitespace only
|
||||
/// separates tokens. The lexer is total: it never rejects input — anything
|
||||
/// the dedicated rules do not cover falls through to the word rule, and an
|
||||
/// unterminated phrase simply extends to the end of the input.
|
||||
/// quoted phrases and parentheses; whitespace only separates tokens.
|
||||
///
|
||||
/// The lexer is strict: inside a phrase only <c>\"</c> and <c>\\</c> are valid
|
||||
/// escapes, a bare backslash or an unknown escape is rejected, a backslash in a
|
||||
/// 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>
|
||||
public static class SearchLexer
|
||||
{
|
||||
private static readonly Parser<char, char> PhraseCharacter =
|
||||
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.Try(Parser.String("\\\\").Select(_ => '\\')))
|
||||
.Or(Parser.AnyCharExcept('"'));
|
||||
.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 =
|
||||
PhraseEscape.Or(Parser<char>.Token(character => character != '"' && character != '\\'));
|
||||
|
||||
private static readonly Parser<char, SearchToken> PhraseParser =
|
||||
from openingQuote in Parser.Char('"')
|
||||
@@ -44,30 +63,99 @@ public static class SearchLexer
|
||||
private static readonly Parser<char, SearchToken> CloseParenParser =
|
||||
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 =
|
||||
Parser<char>.Token(c => !char.IsWhiteSpace(c) && c != '(' && c != ')' && c != '"')
|
||||
Parser<char>.Token(character =>
|
||||
!char.IsWhiteSpace(character) && character != '(' && character != ')' && character != '"' && character != '\\')
|
||||
.AtLeastOnce()
|
||||
.Select(chars => (SearchToken)new SearchToken.Word(new string(chars.ToArray())));
|
||||
|
||||
private static readonly Parser<char, SearchToken> AnyCharacterAsWord =
|
||||
Parser<char>.Any.Select(c => (SearchToken)new SearchToken.Word(c.ToString()));
|
||||
|
||||
private static readonly Parser<char, SearchToken> TokenParser =
|
||||
// Each token with its source span, so adjacency can be checked afterwards.
|
||||
private static readonly Parser<char, PositionedToken> TokenParser =
|
||||
Parser.SkipWhitespaces.Then(
|
||||
PhraseParser
|
||||
from start in Parser<char>.CurrentOffset
|
||||
from token in PhraseParser
|
||||
.Or(OpenParenParser)
|
||||
.Or(CloseParenParser)
|
||||
.Or(WordParser)
|
||||
.Or(AnyCharacterAsWord));
|
||||
from end in Parser<char>.CurrentOffset
|
||||
select new PositionedToken(token, start, end));
|
||||
|
||||
private static readonly Parser<char, IReadOnlyList<SearchToken>> Lexer =
|
||||
// Try(...) keeps a trailing-whitespace failure non-consuming so Many stops
|
||||
// gracefully; the trailing Before(...) then swallows the leftover whitespace.
|
||||
// Try(...) keeps a failed token non-consuming so Many stops gracefully; End
|
||||
// then rejects any leftover input, which turns dangling quotes or invalid
|
||||
// escapes into hard failures instead of silently dropped text.
|
||||
private static readonly Parser<char, IReadOnlyList<PositionedToken>> Lexer =
|
||||
Parser.Try(TokenParser).Many()
|
||||
.Before(Parser.SkipWhitespaces)
|
||||
.Select(tokens => (IReadOnlyList<SearchToken>)tokens.ToList());
|
||||
.Before(Parser<char>.End)
|
||||
.Select(tokens => (IReadOnlyList<PositionedToken>)tokens.ToList());
|
||||
|
||||
/// <summary>Tokenizes the search text; total over any input.</summary>
|
||||
public static IReadOnlyList<SearchToken> Tokenize(string input) =>
|
||||
Lexer.ParseOrThrow(input);
|
||||
/// <summary>
|
||||
/// Tokenizes the search text.
|
||||
/// </summary>
|
||||
/// <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);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
// YYC MARK: C# records synthesize equality by running EqualityComparer<T>.Default
|
||||
// on each positional property. For collection properties (IReadOnlyList<>,
|
||||
// ImmutableArray<>, arrays, ...) that comparer falls back to REFERENCE equality,
|
||||
// so the And/Or nodes below deliberately do NOT compare structurally. The only
|
||||
// so the Or/And nodes below deliberately do NOT compare structurally. The only
|
||||
// structural comparison lives in the test helper (SearchNodeComparer); production
|
||||
// code never compares AST nodes.
|
||||
namespace YKanBan.Search;
|
||||
@@ -10,36 +10,62 @@ namespace YKanBan.Search;
|
||||
/// Root of the search query AST. Search keywords are fixed English grammar
|
||||
/// and are never localized.
|
||||
/// </summary>
|
||||
public abstract record SearchNode
|
||||
{
|
||||
/// <summary>Disjunction: matches when any term matches (OR).</summary>
|
||||
public abstract record SearchNode {
|
||||
/// <summary>
|
||||
/// Disjunction: matches when any term matches (OR).
|
||||
/// </summary>
|
||||
/// <param name="Terms">The alternative terms.</param>
|
||||
public sealed record Or(IReadOnlyList<SearchNode> Terms) : SearchNode;
|
||||
|
||||
/// <summary>Conjunction: matches when all terms match (explicit AND or adjacency).</summary>
|
||||
/// <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;
|
||||
|
||||
/// <summary>A bare word or phrase matched as a substring of the title OR content.</summary>
|
||||
/// <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;
|
||||
|
||||
/// <summary>A substring match scoped to one card field.</summary>
|
||||
/// <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;
|
||||
|
||||
/// <summary>An exact, case-insensitive tag name match.</summary>
|
||||
/// <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;
|
||||
|
||||
/// <summary>An exact, case-insensitive column title match.</summary>
|
||||
/// <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;
|
||||
|
||||
/// <summary>An exact card id match.</summary>
|
||||
/// <summary>
|
||||
/// An exact card id match.
|
||||
/// </summary>
|
||||
/// <param name="Id">The card id to match.</param>
|
||||
public sealed record CardId(long Id) : SearchNode;
|
||||
}
|
||||
|
||||
/// <summary>The card fields a <see cref="SearchNode.FieldText"/> atom can scope to.</summary>
|
||||
public enum SearchField
|
||||
{
|
||||
/// <summary>The card title.</summary>
|
||||
/// <summary>
|
||||
/// The card fields a <see cref="SearchNode.FieldText"/> atom can scope to.
|
||||
/// </summary>
|
||||
public enum SearchField {
|
||||
/// <summary>
|
||||
/// The card title.
|
||||
/// </summary>
|
||||
Title,
|
||||
|
||||
/// <summary>The card content body.</summary>
|
||||
/// <summary>
|
||||
/// The card content body.
|
||||
/// </summary>
|
||||
Content,
|
||||
}
|
||||
@@ -1,45 +1,25 @@
|
||||
using System.Globalization;
|
||||
|
||||
using Pidgin;
|
||||
|
||||
namespace YKanBan.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Thrown when the search text violates the search grammar. Carries the
|
||||
/// underlying parser's descriptive message (including the error position);
|
||||
/// the UI surfaces it as a search error instead of coupling to Pidgin types.
|
||||
/// </summary>
|
||||
public sealed class SearchSyntaxException : Exception
|
||||
{
|
||||
/// <summary>Creates an exception wrapping the original parse failure.</summary>
|
||||
public SearchSyntaxException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the search grammar with Pidgin, strictly: any malformed input
|
||||
/// (unbalanced parentheses, dangling operators, unterminated phrases,
|
||||
/// qualifier keys without a value, non-numeric id values) raises
|
||||
/// <see cref="SearchSyntaxException"/>. Only uppercase AND/OR are operators
|
||||
/// (lowercase ones are plain words); AND — explicit or by adjacency — binds
|
||||
/// tighter than OR; parentheses group. Blank input returns null and means
|
||||
/// "show everything".
|
||||
/// (unbalanced parentheses, dangling or consecutive operators, unterminated
|
||||
/// phrases, invalid escapes, a backslash in a bare word, unknown qualifier
|
||||
/// keys, qualifiers without a value, unquoted values containing ':' or equal
|
||||
/// to AND/OR, and id values that are not an unquoted positive integer with an
|
||||
/// optional '#') raises <see cref="SearchSyntaxException"/>.
|
||||
///
|
||||
/// Only uppercase AND/OR are operators (lowercase ones are plain words); AND —
|
||||
/// 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>
|
||||
public static class SearchQueryParser
|
||||
{
|
||||
/// <summary>Recognized qualifier kinds; extend <see cref="Qualifiers"/> to add new keys.</summary>
|
||||
private enum QualifierKind
|
||||
{
|
||||
Tag,
|
||||
Title,
|
||||
Content,
|
||||
Id,
|
||||
Column,
|
||||
}
|
||||
|
||||
/// <summary>The qualifier key table ("key:" prefixes); reserved for future keys like created:.</summary>
|
||||
private static readonly (string Key, QualifierKind Kind)[] Qualifiers =
|
||||
public static class SearchQueryParser {
|
||||
/// <summary>The recognized qualifier keys; add new entries here to extend the grammar.</summary>
|
||||
private static readonly (string Key, QualifierKind Kind)[] QualifierTable =
|
||||
[
|
||||
("tag", QualifierKind.Tag),
|
||||
("title", QualifierKind.Title),
|
||||
@@ -51,26 +31,26 @@ public static class SearchQueryParser
|
||||
#region Token primitives
|
||||
|
||||
private static readonly Parser<SearchToken, SearchToken> AndKeyword =
|
||||
Parser<SearchToken>.Token(new SearchToken.Word("AND"));
|
||||
Parser<SearchToken>.Token(token => token is SearchToken.Word { Text: "AND" });
|
||||
|
||||
private static readonly Parser<SearchToken, SearchToken> OrKeyword =
|
||||
Parser<SearchToken>.Token(new SearchToken.Word("OR"));
|
||||
Parser<SearchToken>.Token(token => token is SearchToken.Word { Text: "OR" });
|
||||
|
||||
private static readonly Parser<SearchToken, SearchToken> OpenParen =
|
||||
Parser<SearchToken>.Token((SearchToken)new SearchToken.OpenParen());
|
||||
Parser<SearchToken>.Token(token => token is SearchToken.OpenParen);
|
||||
|
||||
private static readonly Parser<SearchToken, SearchToken> CloseParen =
|
||||
Parser<SearchToken>.Token((SearchToken)new SearchToken.CloseParen());
|
||||
Parser<SearchToken>.Token(token => token is SearchToken.CloseParen);
|
||||
|
||||
/// <summary>The text of a phrase token.</summary>
|
||||
private static readonly Parser<SearchToken, string> PhraseText =
|
||||
Parser<SearchToken>.Token(t => t is SearchToken.Phrase)
|
||||
.Select(t => ((SearchToken.Phrase)t).Text);
|
||||
Parser<SearchToken>.Token(token => token is SearchToken.Phrase)
|
||||
.Select(token => ((SearchToken.Phrase)token).Text);
|
||||
|
||||
/// <summary>The text of a word token, operator keywords excluded (they never start an operand).</summary>
|
||||
private static readonly Parser<SearchToken, string> NonKeywordWord =
|
||||
Parser<SearchToken>.Token(t => t is SearchToken.Word w && w.Text != "AND" && w.Text != "OR")
|
||||
.Select(t => ((SearchToken.Word)t).Text);
|
||||
Parser<SearchToken>.Token(token => token is SearchToken.Word word && word.Text != "AND" && word.Text != "OR")
|
||||
.Select(token => ((SearchToken.Word)token).Text);
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -113,82 +93,163 @@ public static class SearchQueryParser
|
||||
OrExpr.Before(Parser<SearchToken>.End);
|
||||
|
||||
/// <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;
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>Parses a search box text; returns null for blank input (meaning: show everything).</summary>
|
||||
/// <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>
|
||||
public static SearchNode? Parse(string text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
public static SearchNode? Parse(string text) {
|
||||
if (string.IsNullOrWhiteSpace(text)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// YYC MARK: the expression is deliberately not capped by parenthesis
|
||||
// depth or atom count. The app is local-only with no untrusted search
|
||||
// input, so there is no attack surface; a pathologically deep or long
|
||||
// expression can still overflow the parser stack or exceed SQLite's
|
||||
// expression nesting limit, which is accepted here.
|
||||
try {
|
||||
List<SearchToken> tokens = SearchLexer.Tokenize(text).ToList();
|
||||
return Query.ParseOrThrow(tokens);
|
||||
}
|
||||
catch (ParseException ex)
|
||||
{
|
||||
throw new SearchSyntaxException(ex.Message, ex);
|
||||
} catch (ParseException exception) {
|
||||
throw new SearchSyntaxException(exception.Message, exception);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Builds the parser for one word operand: qualifier atom or free text.</summary>
|
||||
private static Parser<SearchToken, SearchNode> QualifierFrom(string word)
|
||||
{
|
||||
foreach ((string key, QualifierKind kind) in Qualifiers)
|
||||
{
|
||||
// Qualifier keys are case-sensitive lowercase grammar tokens.
|
||||
if (!word.StartsWith(key + ":", StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
string value = word[(key.Length + 1)..];
|
||||
#region Atom construction
|
||||
|
||||
// "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.
|
||||
/// <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) {
|
||||
int colonIndex = word.IndexOf(':');
|
||||
if (colonIndex < 0) {
|
||||
return Parser<SearchToken>.Return<SearchNode>(new SearchNode.FreeText(word));
|
||||
}
|
||||
|
||||
/// <summary>Builds the atom parser for a qualifier value, failing strictly on a non-numeric id.</summary>
|
||||
private static Parser<SearchToken, SearchNode> AtomParser(QualifierKind kind, string value)
|
||||
{
|
||||
return AtomFrom(kind, value) is { } atom
|
||||
? Parser<SearchToken>.Return(atom)
|
||||
: Parser<SearchToken>.Fail<SearchNode>($"id: expects an integer, got '{value}'.");
|
||||
// Any ':' in a bare word makes it a qualifier, so the text before it must be a known key.
|
||||
string key = word[..colonIndex];
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>Builds the atom for a qualifier value; null when an id value is not an integer.</summary>
|
||||
private static SearchNode? AtomFrom(QualifierKind kind, string value) => kind switch
|
||||
{
|
||||
// "key:" without an inline value takes the value from the following phrase, e.g. tag:"a b".
|
||||
if (value.Length == 0) {
|
||||
return kind == QualifierKind.Id
|
||||
? Parser<SearchToken>.Fail<SearchNode>("The id qualifier expects an unquoted positive integer.")
|
||||
: PhraseText.Select(phrase => TextAtom(kind, phrase));
|
||||
}
|
||||
|
||||
if (value.Contains(':')) {
|
||||
return Parser<SearchToken>.Fail<SearchNode>($"Unquoted value '{value}' of qualifier '{key}' contains ':'; quote the value.");
|
||||
}
|
||||
|
||||
if (value is "AND" or "OR") {
|
||||
return Parser<SearchToken>.Fail<SearchNode>($"Operator {value} cannot be a qualifier value; quote it to search for it literally.");
|
||||
}
|
||||
|
||||
if (kind == QualifierKind.Id) {
|
||||
return TryParseCardId(value, out long id)
|
||||
? Parser<SearchToken>.Return<SearchNode>(new SearchNode.CardId(id))
|
||||
: Parser<SearchToken>.Fail<SearchNode>($"The id qualifier expects a positive integer, got '{value}'.");
|
||||
}
|
||||
|
||||
return Parser<SearchToken>.Return(TextAtom(kind, value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.Title => new SearchNode.FieldText(SearchField.Title, value),
|
||||
QualifierKind.Content => new SearchNode.FieldText(SearchField.Content, value),
|
||||
QualifierKind.Column => new SearchNode.ColumnTitle(value),
|
||||
QualifierKind.Id when long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out long id) => new SearchNode.CardId(id),
|
||||
_ => null,
|
||||
_ => throw new InvalidOperationException($"Qualifier kind {kind} has no textual value."),
|
||||
};
|
||||
|
||||
/// <summary>Collapses an AND chain into a single node.</summary>
|
||||
private static SearchNode FoldAnd(SearchNode first, IEnumerable<SearchNode> rest)
|
||||
{
|
||||
/// <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) {
|
||||
List<SearchNode> terms = [first, .. rest];
|
||||
return terms.Count == 1 ? terms[0] : new SearchNode.And(terms);
|
||||
}
|
||||
|
||||
/// <summary>Collapses an OR chain into a single node.</summary>
|
||||
private static SearchNode FoldOr(IEnumerable<SearchNode> terms)
|
||||
{
|
||||
/// <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) {
|
||||
List<SearchNode> list = terms.ToList();
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -1,68 +1,73 @@
|
||||
using YKanBan.Storage;
|
||||
|
||||
namespace YKanBan.Search;
|
||||
|
||||
/// <summary>A compiled search predicate: a SQL fragment over the "c" (cards) alias plus its bound parameters.</summary>
|
||||
/// <param name="Predicate">SQL boolean expression; intended for "SELECT ... FROM cards c WHERE {Predicate}".</param>
|
||||
/// <summary>
|
||||
/// A compiled search predicate: a SQL fragment over the "c" (cards) alias plus
|
||||
/// 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>
|
||||
public sealed record CompiledSearch(string Predicate, IReadOnlyList<(string Name, object Value)> Parameters);
|
||||
|
||||
/// <summary>
|
||||
/// Compiles a parsed search AST into a parameterized SQL predicate.
|
||||
/// Matching is case-insensitive with SQLite's built-in ASCII semantics:
|
||||
/// LIKE's default case folding plus COLLATE NOCASE for exact matches.
|
||||
/// LIKE wildcards and the escape character in user text are escaped so they
|
||||
/// match literally.
|
||||
/// Compiles a parsed search AST into a parameterized SQL predicate. Matching is
|
||||
/// Unicode case-insensitive: both sides are folded with
|
||||
/// <see cref="SqliteDatabase.Fold"/> (the column side through the per-connection
|
||||
/// <see cref="SqliteDatabase.FoldFunctionName"/> function) and then compared
|
||||
/// ordinally — <c>instr</c> for substrings, <c>=</c> for exact matches. LIKE is
|
||||
/// deliberately not used, so <c>%</c> and <c>_</c> carry no wildcard meaning.
|
||||
/// </summary>
|
||||
public static class SearchSqlCompiler
|
||||
{
|
||||
/// <summary>Compiles the query into a SQL predicate.</summary>
|
||||
public static CompiledSearch Compile(SearchNode query)
|
||||
{
|
||||
public static class SearchSqlCompiler {
|
||||
/// <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) {
|
||||
var parameters = new List<(string Name, object Value)>();
|
||||
string predicate = Build(query, parameters);
|
||||
return new CompiledSearch(predicate, parameters);
|
||||
}
|
||||
|
||||
/// <summary>Recursively builds the SQL expression for one node.</summary>
|
||||
private static string Build(SearchNode node, List<(string Name, object Value)> parameters)
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
/// <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) {
|
||||
switch (node) {
|
||||
case SearchNode.And and:
|
||||
return "(" + string.Join(" AND ", and.Terms.Select(term => Build(term, parameters))) + ")";
|
||||
|
||||
case SearchNode.Or or:
|
||||
return "(" + string.Join(" OR ", or.Terms.Select(term => Build(term, parameters))) + ")";
|
||||
|
||||
case SearchNode.FreeText freeText:
|
||||
{
|
||||
case SearchNode.FreeText freeText: {
|
||||
// A bare word matches a substring of the title OR the content.
|
||||
string titleParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
|
||||
string contentParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
|
||||
return $"(c.title LIKE {titleParam} ESCAPE '\\' OR c.content LIKE {contentParam} ESCAPE '\\')";
|
||||
string param = AddParameter(parameters, SqliteDatabase.Fold(freeText.Text));
|
||||
return $"({Contains("c.title", param)} OR {Contains("c.content", param)})";
|
||||
}
|
||||
|
||||
case SearchNode.FieldText field:
|
||||
{
|
||||
case SearchNode.FieldText field: {
|
||||
string column = field.Field == SearchField.Title ? "c.title" : "c.content";
|
||||
string param = AddParameter(parameters, "%" + EscapeLike(field.Text) + "%");
|
||||
return $"{column} LIKE {param} ESCAPE '\\'";
|
||||
string param = AddParameter(parameters, SqliteDatabase.Fold(field.Text));
|
||||
return Contains(column, param);
|
||||
}
|
||||
|
||||
case SearchNode.TagName tag:
|
||||
{
|
||||
string param = AddParameter(parameters, tag.Name);
|
||||
case SearchNode.TagName tag: {
|
||||
string param = AddParameter(parameters, SqliteDatabase.Fold(tag.Name));
|
||||
return "EXISTS (SELECT 1 FROM card_tags ct JOIN tags t ON t.id = ct.tag_id " +
|
||||
$"WHERE ct.card_id = c.id AND t.name COLLATE NOCASE = {param})";
|
||||
$"WHERE ct.card_id = c.id AND {Folded("t.name")} = {param})";
|
||||
}
|
||||
|
||||
case SearchNode.ColumnTitle column:
|
||||
{
|
||||
string param = AddParameter(parameters, column.Title);
|
||||
return $"c.column_id IN (SELECT id FROM columns WHERE title COLLATE NOCASE = {param})";
|
||||
case SearchNode.ColumnTitle column: {
|
||||
string param = AddParameter(parameters, SqliteDatabase.Fold(column.Title));
|
||||
return $"c.column_id IN (SELECT id FROM columns WHERE {Folded("title")} = {param})";
|
||||
}
|
||||
|
||||
case SearchNode.CardId id:
|
||||
{
|
||||
case SearchNode.CardId id: {
|
||||
string param = AddParameter(parameters, id.Id);
|
||||
return $"c.id = {param}";
|
||||
}
|
||||
@@ -72,15 +77,30 @@ public static class SearchSqlCompiler
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Binds a value under a fresh name and returns the SQL placeholder.</summary>
|
||||
private static string AddParameter(List<(string Name, object Value)> parameters, object value)
|
||||
{
|
||||
/// <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) {
|
||||
string name = "$p" + parameters.Count.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
parameters.Add((name, value));
|
||||
return name;
|
||||
}
|
||||
|
||||
/// <summary>Escapes LIKE wildcards and the escape character inside user text.</summary>
|
||||
private static string EscapeLike(string text) =>
|
||||
text.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_");
|
||||
/// <summary>
|
||||
/// Wraps a column expression in the case-folding SQL function.
|
||||
/// </summary>
|
||||
/// <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";
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
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) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
namespace YKanBan.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Composition root for the whole process: owns the loaded configuration and
|
||||
/// the single open workspace session. The configuration is persisted once at
|
||||
/// shutdown; the session (lock plus connection) lives until disposal.
|
||||
/// </summary>
|
||||
public sealed class AppServices : IDisposable {
|
||||
/// <summary>
|
||||
/// Loads the configuration and prepares the service graph.
|
||||
/// </summary>
|
||||
public AppServices() {
|
||||
ConfigStore = new AppConfigStore(AppDataPaths.AppConfigJsonPath);
|
||||
Config = ConfigStore.Load();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mutable application configuration, persisted at shutdown.
|
||||
/// </summary>
|
||||
public AppConfig Config { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the store backing app.json.
|
||||
/// </summary>
|
||||
public AppConfigStore ConfigStore { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the open workspace session, or <see langword="null"/> while no
|
||||
/// workspace is open (for example on an error page).
|
||||
/// </summary>
|
||||
public WorkspaceSession? Session { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Opens a workspace, acquiring its exclusive lock and connection.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder to open.</param>
|
||||
/// <returns>The open session.</returns>
|
||||
/// <exception cref="YKanBan.Storage.WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
|
||||
/// <exception cref="YKanBan.Storage.WorkspaceLockException">Another instance already holds the lock.</exception>
|
||||
public WorkspaceSession OpenWorkspace(string folderPath) {
|
||||
Session = WorkspaceSession.Open(folderPath);
|
||||
return Session;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a fresh workspace and opens it, holding the lock throughout.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The folder to initialize.</param>
|
||||
/// <returns>The open session.</returns>
|
||||
/// <exception cref="YKanBan.Storage.WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
||||
/// <exception cref="YKanBan.Storage.WorkspaceLockException">Another instance already holds the lock.</exception>
|
||||
public WorkspaceSession InitializeWorkspace(string folderPath) {
|
||||
Session = WorkspaceSession.Initialize(folderPath);
|
||||
return Session;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the workspace session, if any, and forgets it.
|
||||
/// </summary>
|
||||
public void CloseWorkspace() {
|
||||
Session?.Dispose();
|
||||
Session = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the configuration; called once at shutdown.
|
||||
/// </summary>
|
||||
// YYC MARK: the whole app.json is rewritten unconditionally at shutdown.
|
||||
// Running several instances would make the last one to exit overwrite every
|
||||
// field with its own in-memory state. Multi-instance use is not supported,
|
||||
// so this last-writer-wins behavior is accepted.
|
||||
public void SaveConfiguration() => ConfigStore.Save(Config);
|
||||
|
||||
/// <summary>
|
||||
/// Releases the workspace session, if any.
|
||||
/// </summary>
|
||||
public void Dispose() => Session?.Dispose();
|
||||
}
|
||||
@@ -1,156 +1,230 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace YKanBan.Storage.AppData;
|
||||
|
||||
/// <summary>Card ordering options. All orders fall back to id ascending.</summary>
|
||||
public enum CardSortOption
|
||||
{
|
||||
/// <summary>Ascending primary key (default).</summary>
|
||||
[EnumMember(Value = "id")]
|
||||
Id,
|
||||
/// <summary>
|
||||
/// Display ordering options, used for both cards and columns. Except for the id
|
||||
/// order, every option falls back to id ascending as the final tie-breaker.
|
||||
/// </summary>
|
||||
public enum SortOption {
|
||||
/// <summary>
|
||||
/// Primary key ascending.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "id-asc")]
|
||||
IdAscending,
|
||||
|
||||
/// <summary>Creation time, oldest first.</summary>
|
||||
[EnumMember(Value = "created-at")]
|
||||
CreatedAt,
|
||||
/// <summary>
|
||||
/// Primary key descending.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "id-desc")]
|
||||
IdDescending,
|
||||
|
||||
/// <summary>Last modification time, most recent first.</summary>
|
||||
[EnumMember(Value = "updated-at")]
|
||||
UpdatedAt,
|
||||
/// <summary>
|
||||
/// Creation time ascending.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "created-asc")]
|
||||
CreatedAscending,
|
||||
|
||||
/// <summary>Title by code points (BINARY collation); empty titles sort first.</summary>
|
||||
[EnumMember(Value = "title")]
|
||||
Title,
|
||||
/// <summary>
|
||||
/// Creation time descending.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "created-desc")]
|
||||
CreatedDescending,
|
||||
|
||||
/// <summary>
|
||||
/// Last modification time ascending.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "updated-asc")]
|
||||
UpdatedAscending,
|
||||
|
||||
/// <summary>
|
||||
/// Last modification time descending.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "updated-desc")]
|
||||
UpdatedDescending,
|
||||
|
||||
/// <summary>
|
||||
/// Title by code points (BINARY collation) ascending.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "title-asc")]
|
||||
TitleAscending,
|
||||
|
||||
/// <summary>
|
||||
/// Title by code points (BINARY collation) descending.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "title-desc")]
|
||||
TitleDescending,
|
||||
}
|
||||
|
||||
/// <summary>Sidebar workspace list ordering.</summary>
|
||||
public enum SidebarSortOption
|
||||
{
|
||||
/// <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
|
||||
{
|
||||
/// <summary>Narrow preset.</summary>
|
||||
/// <summary>
|
||||
/// Column width presets. <see cref="Custom"/> uses a user-defined pixel width.
|
||||
/// </summary>
|
||||
public enum ColumnWidthPreset {
|
||||
/// <summary>
|
||||
/// Narrow preset.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "narrow")]
|
||||
Narrow,
|
||||
|
||||
/// <summary>Standard preset (320 px, the default).</summary>
|
||||
/// <summary>
|
||||
/// Standard preset (320 px, the default).
|
||||
/// </summary>
|
||||
[EnumMember(Value = "standard")]
|
||||
Standard,
|
||||
|
||||
/// <summary>Wide preset.</summary>
|
||||
/// <summary>
|
||||
/// Wide preset.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "wide")]
|
||||
Wide,
|
||||
|
||||
/// <summary>User-defined pixel width (160–720).</summary>
|
||||
/// <summary>
|
||||
/// User-defined pixel width (160–720).
|
||||
/// </summary>
|
||||
[EnumMember(Value = "custom")]
|
||||
Custom,
|
||||
}
|
||||
|
||||
/// <summary>UI theme selection.</summary>
|
||||
public enum ThemeOption
|
||||
{
|
||||
/// <summary>Always light.</summary>
|
||||
/// <summary>
|
||||
/// UI theme selection.
|
||||
/// </summary>
|
||||
public enum ThemeOption {
|
||||
/// <summary>
|
||||
/// Always light.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "light")]
|
||||
Light,
|
||||
|
||||
/// <summary>Always dark.</summary>
|
||||
/// <summary>
|
||||
/// Always dark.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "dark")]
|
||||
Dark,
|
||||
|
||||
/// <summary>Follow the operating system setting (default).</summary>
|
||||
/// <summary>
|
||||
/// Follow the operating system setting (default).
|
||||
/// </summary>
|
||||
[EnumMember(Value = "follow-system")]
|
||||
FollowSystem,
|
||||
}
|
||||
|
||||
/// <summary>Card and sidebar list ordering settings.</summary>
|
||||
public sealed class SortSettings
|
||||
{
|
||||
/// <summary>Card order used by all workspaces (global, not per workspace).</summary>
|
||||
[JsonProperty("card")]
|
||||
public CardSortOption Card { get; set; } = CardSortOption.Id;
|
||||
|
||||
/// <summary>Sidebar workspace list order.</summary>
|
||||
[JsonProperty("sidebar")]
|
||||
public SidebarSortOption Sidebar { get; set; } = SidebarSortOption.NameAsc;
|
||||
}
|
||||
|
||||
/// <summary>Board column width settings.</summary>
|
||||
public sealed class ColumnWidthSettings
|
||||
{
|
||||
/// <summary>Width preset applied globally.</summary>
|
||||
/// <summary>
|
||||
/// Board column width settings, applied globally.
|
||||
/// </summary>
|
||||
public sealed class ColumnWidthSettings {
|
||||
/// <summary>
|
||||
/// Gets or sets the active width preset.
|
||||
/// </summary>
|
||||
[JsonProperty("preset")]
|
||||
public ColumnWidthPreset Preset { get; set; } = ColumnWidthPreset.Standard;
|
||||
|
||||
/// <summary>Manual width in pixels used when <see cref="Preset"/> is Custom (range 160–720).</summary>
|
||||
/// <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")]
|
||||
public int CustomPixels { get; set; } = 320;
|
||||
}
|
||||
|
||||
/// <summary>Confirmation-dialog toggles for destructive actions.</summary>
|
||||
public sealed class ConfirmationSettings
|
||||
{
|
||||
/// <summary>Whether deleting a card asks for confirmation.</summary>
|
||||
/// <summary>
|
||||
/// Everything that controls how the board is displayed: the column width and
|
||||
/// the card and column ordering.
|
||||
/// </summary>
|
||||
public sealed class DisplaySettings {
|
||||
/// <summary>
|
||||
/// Gets or sets the board column width settings.
|
||||
/// </summary>
|
||||
[JsonProperty("column-width")]
|
||||
public ColumnWidthSettings ColumnWidth { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the order of cards within their column.
|
||||
/// </summary>
|
||||
[JsonProperty("card-sort")]
|
||||
public SortOption CardSort { get; set; } = SortOption.IdAscending;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the left-to-right order of the columns.
|
||||
/// </summary>
|
||||
[JsonProperty("column-sort")]
|
||||
public SortOption ColumnSort { get; set; } = SortOption.IdAscending;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Confirmation-dialog toggles for the destructive actions.
|
||||
/// </summary>
|
||||
public sealed class ConfirmationSettings {
|
||||
/// <summary>
|
||||
/// Gets or sets whether deleting a card asks for confirmation.
|
||||
/// </summary>
|
||||
[JsonProperty("delete-card")]
|
||||
public bool DeleteCard { get; set; } = true;
|
||||
|
||||
/// <summary>Whether deleting a column asks for confirmation.</summary>
|
||||
/// <summary>
|
||||
/// Gets or sets whether deleting a column asks for confirmation.
|
||||
/// </summary>
|
||||
[JsonProperty("delete-column")]
|
||||
public bool DeleteColumn { get; set; } = true;
|
||||
|
||||
/// <summary>Whether deleting a tag asks for confirmation.</summary>
|
||||
/// <summary>
|
||||
/// Gets or sets whether deleting a tag asks for confirmation.
|
||||
/// </summary>
|
||||
[JsonProperty("delete-tag")]
|
||||
public bool DeleteTag { get; set; } = true;
|
||||
|
||||
/// <summary>Whether discarding card edits asks for confirmation.</summary>
|
||||
/// <summary>
|
||||
/// Gets or sets whether discarding card edits asks for confirmation.
|
||||
/// </summary>
|
||||
[JsonProperty("discard-edit")]
|
||||
public bool DiscardEdit { get; set; } = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Root object of app.json — the trivial KV configuration store. Serialized
|
||||
/// as a whole with kebab-case names (declared via [JsonProperty] and
|
||||
/// [EnumMember]); the "version" field is the migration hook for future
|
||||
/// format changes.
|
||||
/// Root object of app.json, the whole-file key/value configuration store.
|
||||
/// Keys and enum values are serialized in kebab-case (declared explicitly via
|
||||
/// <see cref="JsonPropertyAttribute"/> and <see cref="EnumMemberAttribute"/>).
|
||||
/// The <c>version</c> field is the migration hook for future format changes.
|
||||
/// </summary>
|
||||
public sealed class AppConfig
|
||||
{
|
||||
/// <summary>Current configuration format version.</summary>
|
||||
public sealed class AppConfig {
|
||||
/// <summary>
|
||||
/// Current configuration format version.
|
||||
/// </summary>
|
||||
public const int CurrentFormatVersion = 1;
|
||||
|
||||
/// <summary>Configuration format version of this file.</summary>
|
||||
/// <summary>
|
||||
/// Default UI language code.
|
||||
/// </summary>
|
||||
public const string DefaultLanguage = "en";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the configuration format version of this file.
|
||||
/// </summary>
|
||||
[JsonProperty("version")]
|
||||
public int Version { get; set; } = CurrentFormatVersion;
|
||||
|
||||
/// <summary>UI language code: "en" (default) or "zh-Hans".</summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the UI language code ("en" default or "zh-Hans").
|
||||
/// </summary>
|
||||
[JsonProperty("language")]
|
||||
public string Language { get; set; } = "en";
|
||||
public string Language { get; set; } = DefaultLanguage;
|
||||
|
||||
/// <summary>UI theme selection (default: follow the system).</summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the UI theme selection (default: follow the system).
|
||||
/// </summary>
|
||||
[JsonProperty("theme")]
|
||||
public ThemeOption Theme { get; set; } = ThemeOption.FollowSystem;
|
||||
|
||||
/// <summary>Ordering settings.</summary>
|
||||
[JsonProperty("sort")]
|
||||
public SortSettings Sort { get; set; } = new();
|
||||
/// <summary>
|
||||
/// Gets or sets the board display settings (width and ordering).
|
||||
/// </summary>
|
||||
[JsonProperty("display")]
|
||||
public DisplaySettings Display { get; set; } = new();
|
||||
|
||||
/// <summary>Column width settings.</summary>
|
||||
[JsonProperty("column-width")]
|
||||
public ColumnWidthSettings ColumnWidth { get; set; } = new();
|
||||
|
||||
/// <summary>Confirmation-dialog settings.</summary>
|
||||
/// <summary>
|
||||
/// Gets or sets the confirmation-dialog settings.
|
||||
/// </summary>
|
||||
[JsonProperty("confirmations")]
|
||||
public ConfirmationSettings Confirmations { get; set; } = new();
|
||||
}
|
||||
@@ -4,71 +4,89 @@ using Newtonsoft.Json.Converters;
|
||||
namespace YKanBan.Storage.AppData;
|
||||
|
||||
/// <summary>
|
||||
/// Loads and saves app.json with graceful degradation: a missing file yields
|
||||
/// defaults; a corrupt file is backed up to app.json.bak and then defaults
|
||||
/// are used. Saving writes the file directly (no atomic replace) — losing
|
||||
/// the last session's settings to a crash is an accepted trade-off.
|
||||
/// Loads and saves app.json with graceful degradation: a missing or unreadable
|
||||
/// file yields defaults; a corrupt file is backed up to app.json.bak and then
|
||||
/// defaults are used. Saving writes the file directly (no atomic replace) —
|
||||
/// losing the last session's settings to a crash is an accepted trade-off.
|
||||
/// </summary>
|
||||
public sealed class AppConfigStore
|
||||
{
|
||||
private static readonly JsonSerializerSettings SerializerSettings = new()
|
||||
{
|
||||
public sealed class AppConfigStore {
|
||||
private static readonly JsonSerializerSettings SerializerSettings = new() {
|
||||
Formatting = Formatting.Indented,
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
|
||||
// Enums round-trip through the kebab-case strings declared via [EnumMember].
|
||||
Converters = { new StringEnumConverter() },
|
||||
// Enums round-trip through the kebab-case strings declared via [EnumMember];
|
||||
// numeric enum values are rejected like any other unknown value.
|
||||
// YYC MARK: non-enum fields (bool/int/string) are still coerced by
|
||||
// Newtonsoft (for example 0 or "true" to bool, "500" or 500.0 to int);
|
||||
// a wrongly typed non-enum value is accepted and converted rather than
|
||||
// treated as invalid. That leniency is accepted here.
|
||||
Converters = { new StringEnumConverter { AllowIntegerValues = false } },
|
||||
};
|
||||
|
||||
/// <summary>Creates a store bound to a specific app.json path.</summary>
|
||||
/// <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;
|
||||
|
||||
/// <summary>Full path of the managed app.json file.</summary>
|
||||
/// <summary>
|
||||
/// Gets the full path of the managed app.json file.
|
||||
/// </summary>
|
||||
public string FilePath { get; }
|
||||
|
||||
/// <summary>Loads the configuration: missing file → defaults; corrupt file → backup then defaults.</summary>
|
||||
/// <exception cref="IOException">The file exists but cannot be read.</exception>
|
||||
public AppConfig Load()
|
||||
{
|
||||
/// <summary>
|
||||
/// Loads the configuration. A missing file yields defaults; a corrupt file
|
||||
/// is backed up to app.json.bak and then defaults are used; a file that
|
||||
/// exists but cannot be read (I/O or permission error) also yields defaults.
|
||||
/// </summary>
|
||||
/// <returns>The loaded configuration, or defaults when none could be read.</returns>
|
||||
public AppConfig Load() {
|
||||
// Missing file is a normal first-run state: run with defaults.
|
||||
if (!File.Exists(FilePath))
|
||||
{
|
||||
if (!File.Exists(FilePath)) {
|
||||
return new AppConfig();
|
||||
}
|
||||
|
||||
string json = File.ReadAllText(FilePath);
|
||||
try
|
||||
{
|
||||
string json;
|
||||
try {
|
||||
json = File.ReadAllText(FilePath);
|
||||
} catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) {
|
||||
// A bad app.json must not stop startup.
|
||||
return new AppConfig();
|
||||
}
|
||||
|
||||
try {
|
||||
// A JSON null literal deserializes to null; treat it like defaults.
|
||||
AppConfig? config = JsonConvert.DeserializeObject<AppConfig>(json, SerializerSettings);
|
||||
if (config is null)
|
||||
{
|
||||
if (config is null) {
|
||||
return new AppConfig();
|
||||
}
|
||||
|
||||
// Older or hand-edited files may miss whole sections; each falls back to its defaults.
|
||||
config.Sort ??= new SortSettings();
|
||||
config.ColumnWidth ??= new ColumnWidthSettings();
|
||||
config.Display ??= new DisplaySettings();
|
||||
config.Confirmations ??= new ConfirmationSettings();
|
||||
return config;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Corrupt: keep a copy for inspection, then continue with defaults.
|
||||
} catch (JsonException) {
|
||||
// Corrupt: keep a copy for inspection (best effort), then continue with defaults.
|
||||
try {
|
||||
File.Copy(FilePath, FilePath + ".bak", overwrite: true);
|
||||
} catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) {
|
||||
// The backup is only a diagnostic aid; starting with defaults matters more.
|
||||
}
|
||||
return new AppConfig();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes the configuration directly to disk (no atomic replace).</summary>
|
||||
public void Save(AppConfig config)
|
||||
{
|
||||
// Create the parent folder on demand; normally it exists already.
|
||||
/// <summary>
|
||||
/// Writes the configuration directly to disk (no atomic replace).
|
||||
/// </summary>
|
||||
/// <param name="config">The configuration to serialize.</param>
|
||||
public void Save(AppConfig config) {
|
||||
// Create the parent folder on demand; normally it already exists.
|
||||
string? directory = Path.GetDirectoryName(FilePath);
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
{
|
||||
if (!string.IsNullOrEmpty(directory)) {
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
File.WriteAllText(FilePath, JsonConvert.SerializeObject(config, SerializerSettings));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace YKanBan.Storage.AppData;
|
||||
|
||||
/// <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 {
|
||||
/// <summary>
|
||||
/// Gets the per-user YKanBan application data folder.
|
||||
/// </summary>
|
||||
public static string Directory =>
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "YKanBan");
|
||||
|
||||
/// <summary>
|
||||
/// Gets the full path of app.json.
|
||||
/// </summary>
|
||||
public static string AppConfigJsonPath => Path.Combine(Directory, "app.json");
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
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();
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
namespace YKanBan.Storage;
|
||||
|
||||
/// <summary>A single incremental schema step applied when the stored user_version is one below <see cref="Version"/>.</summary>
|
||||
/// <param name="Version">Target user_version after applying this migration (contiguous, starting at 1).</param>
|
||||
/// <summary>
|
||||
/// A single incremental schema step. Migrations form a contiguous list
|
||||
/// 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="Sql">SQL script executed inside one transaction together with the user_version bump.</param>
|
||||
/// <param name="Sql">SQL script executed atomically together with the version bump.</param>
|
||||
public sealed record SchemaMigration(int Version, string Name, string Sql);
|
||||
@@ -3,67 +3,100 @@ using Microsoft.Data.Sqlite;
|
||||
namespace YKanBan.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Shared SQLite plumbing for both the per-workspace databases and the
|
||||
/// global app.db: opens connections with the mandated PRAGMA configuration
|
||||
/// (WAL journal, NORMAL synchronous mode, foreign keys on) and applies
|
||||
/// incremental user_version migrations.
|
||||
/// Shared SQLite plumbing for workspace databases: opens a connection with
|
||||
/// the mandated PRAGMA configuration (WAL journal, NORMAL synchronous mode,
|
||||
/// foreign keys on) and applies incremental <c>user_version</c> migrations.
|
||||
/// </summary>
|
||||
public static class SqliteDatabase
|
||||
{
|
||||
/// <summary>Opens (creating if needed) a database file, applies PRAGMAs and pending migrations.</summary>
|
||||
public static class SqliteDatabase {
|
||||
/// <summary>
|
||||
/// Name of the per-connection SQL function that applies <see cref="Fold"/>;
|
||||
/// search uses it for Unicode case-insensitive matching.
|
||||
/// </summary>
|
||||
public const string FoldFunctionName = "ykb_fold";
|
||||
|
||||
/// <summary>
|
||||
/// Unicode case folding shared by the SQL function and the search
|
||||
/// parameters it is compared against; comparisons after folding are ordinal.
|
||||
/// </summary>
|
||||
/// <param name="text">The text to fold.</param>
|
||||
/// <returns>The invariant lowercase form.</returns>
|
||||
public static string Fold(string text) => text.ToLowerInvariant();
|
||||
|
||||
/// <summary>
|
||||
/// 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="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>
|
||||
public static SqliteConnection Open(string databasePath, IReadOnlyList<SchemaMigration> migrations)
|
||||
{
|
||||
var connection = new SqliteConnection(new SqliteConnectionStringBuilder
|
||||
{
|
||||
public static SqliteConnection Open(string databasePath, IReadOnlyList<SchemaMigration> migrations) {
|
||||
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();
|
||||
try
|
||||
{
|
||||
try {
|
||||
ApplyPragmas(connection);
|
||||
RegisterFunctions(connection);
|
||||
ApplyMigrations(connection, migrations);
|
||||
return connection;
|
||||
}
|
||||
catch
|
||||
{
|
||||
} catch {
|
||||
connection.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the stored PRAGMA user_version value.</summary>
|
||||
public static long ReadUserVersion(SqliteConnection connection)
|
||||
{
|
||||
/// <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) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "PRAGMA user_version;";
|
||||
return (long)command.ExecuteScalar()!;
|
||||
}
|
||||
|
||||
/// <summary>Applies per-connection PRAGMAs. WAL itself is a persistent database property.</summary>
|
||||
internal static void ApplyPragmas(SqliteConnection connection)
|
||||
{
|
||||
// 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.
|
||||
/// <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) {
|
||||
// WAL plus NORMAL synchronous is the chosen durability/performance trade-off.
|
||||
Execute(connection, "PRAGMA journal_mode=WAL;");
|
||||
Execute(connection, "PRAGMA synchronous=NORMAL;");
|
||||
Execute(connection, "PRAGMA foreign_keys=ON;");
|
||||
}
|
||||
|
||||
/// <summary>Runs every migration newer than the stored user_version, each in its own transaction.</summary>
|
||||
/// <exception cref="SchemaVersionException">The database was written by a newer build.</exception>
|
||||
/// <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>
|
||||
internal static void ApplyMigrations(SqliteConnection connection, IReadOnlyList<SchemaMigration> 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)
|
||||
{
|
||||
/// <exception cref="SchemaVersionException">The database was written by a newer build.</exception>
|
||||
internal static void ApplyMigrations(SqliteConnection connection, IReadOnlyList<SchemaMigration> migrations) {
|
||||
// Contract check: the list must be ordered, contiguous and start 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));
|
||||
}
|
||||
}
|
||||
@@ -72,18 +105,16 @@ public static class SqliteDatabase
|
||||
int latest = migrations.Count;
|
||||
|
||||
// A database written by a newer build cannot be managed by this one; refuse loudly.
|
||||
if (current > latest)
|
||||
{
|
||||
if (current > latest) {
|
||||
throw new SchemaVersionException(current, latest);
|
||||
}
|
||||
|
||||
// Apply each pending migration atomically so a crash never leaves a half-migrated database.
|
||||
foreach (SchemaMigration migration in migrations)
|
||||
{
|
||||
if (migration.Version <= current)
|
||||
{
|
||||
foreach (SchemaMigration migration in migrations) {
|
||||
if (migration.Version <= current) {
|
||||
continue;
|
||||
}
|
||||
|
||||
using var transaction = connection.BeginTransaction();
|
||||
Execute(connection, migration.Sql, transaction);
|
||||
Execute(connection, $"PRAGMA user_version={migration.Version};", transaction);
|
||||
@@ -91,9 +122,13 @@ public static class SqliteDatabase
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Executes a non-query SQL script, optionally inside an explicit transaction.</summary>
|
||||
private static void Execute(SqliteConnection connection, string commandText, SqliteTransaction? transaction = null)
|
||||
{
|
||||
/// <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) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = commandText;
|
||||
|
||||
@@ -1,89 +1,123 @@
|
||||
namespace YKanBan.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Typed exceptions thrown by the YKanBan storage and application layers.
|
||||
/// Exception messages are always English and never localized; the UI maps
|
||||
/// exception types to localized resource keys instead.
|
||||
/// Base class for the typed exceptions raised by the storage layer.
|
||||
/// Exception messages are always English and never localized; the UI maps the
|
||||
/// exception type to a localized resource key instead.
|
||||
/// </summary>
|
||||
public abstract class YKanBanException : Exception
|
||||
{
|
||||
/// <summary>Creates an exception with an English diagnostic message.</summary>
|
||||
public abstract class YKanBanException : Exception {
|
||||
/// <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)
|
||||
: base(message, innerException)
|
||||
{
|
||||
: base(message, innerException) {
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Signals that the workspace folder does not exist on disk.</summary>
|
||||
public sealed class WorkspaceDirectoryMissingException : YKanBanException
|
||||
{
|
||||
/// <summary>The folder path that was expected to exist.</summary>
|
||||
/// <summary>
|
||||
/// Signals that the folder passed on the command line does not exist on disk.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceDirectoryMissingException : YKanBanException {
|
||||
/// <summary>
|
||||
/// Gets the folder path that was expected to exist.
|
||||
/// </summary>
|
||||
public string FolderPath { get; }
|
||||
|
||||
/// <summary>Creates an exception for a folder that is absent on disk.</summary>
|
||||
/// <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)
|
||||
: base($"The folder does not exist: {folderPath}")
|
||||
{
|
||||
: base($"The folder does not exist: {folderPath}") {
|
||||
FolderPath = folderPath;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Signals that the folder has no .ykanban structure yet.</summary>
|
||||
public sealed class WorkspaceNotInitializedException : YKanBanException
|
||||
{
|
||||
/// <summary>The folder path that lacks the .ykanban structure.</summary>
|
||||
/// <summary>
|
||||
/// Signals that a folder exists but has no .ykanban structure, so it is not
|
||||
/// (yet) a workspace.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceNotInitializedException : YKanBanException {
|
||||
/// <summary>
|
||||
/// Gets the folder path that lacks the .ykanban structure.
|
||||
/// </summary>
|
||||
public string FolderPath { get; }
|
||||
|
||||
/// <summary>Creates an exception for a folder without .ykanban.</summary>
|
||||
/// <summary>
|
||||
/// Initializes the exception for a folder without a .ykanban structure.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The uninitialized folder path.</param>
|
||||
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}") {
|
||||
FolderPath = folderPath;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Signals that another instance holds the workspace lock.</summary>
|
||||
public sealed class WorkspaceLockException : YKanBanException
|
||||
{
|
||||
/// <summary>The lock file that could not be acquired.</summary>
|
||||
/// <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 {
|
||||
/// <summary>
|
||||
/// Gets the lock file that could not be acquired.
|
||||
/// </summary>
|
||||
public string LockFilePath { get; }
|
||||
|
||||
/// <summary>Best-effort diagnostics (PID/machine/time) read from the lock file, if readable.</summary>
|
||||
public string? HolderDiagnostics { get; }
|
||||
|
||||
/// <summary>Creates an exception for a failed lock acquisition.</summary>
|
||||
public WorkspaceLockException(string lockFilePath, string? holderDiagnostics, Exception innerException)
|
||||
: base(BuildMessage(lockFilePath, holderDiagnostics), innerException)
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes the exception for a failed lock acquisition.
|
||||
/// </summary>
|
||||
/// <param name="lockFilePath">The lock file that is already held.</param>
|
||||
/// <param name="innerException">The underlying I/O error.</param>
|
||||
public WorkspaceLockException(string lockFilePath, Exception innerException)
|
||||
: base($"The workspace is locked by another instance: {lockFilePath}", innerException) {
|
||||
LockFilePath = lockFilePath;
|
||||
HolderDiagnostics = holderDiagnostics;
|
||||
}
|
||||
|
||||
/// <summary>Composes the message, including holder details when they were readable.</summary>
|
||||
private static string BuildMessage(string lockFilePath, string? holderDiagnostics)
|
||||
{
|
||||
string message = $"The workspace is locked by another instance: {lockFilePath}";
|
||||
if (!string.IsNullOrEmpty(holderDiagnostics))
|
||||
{
|
||||
message += $" Lock holder: {holderDiagnostics}";
|
||||
}
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Signals that the stored schema version is not manageable by this build.</summary>
|
||||
public sealed class SchemaVersionException : YKanBanException
|
||||
{
|
||||
/// <summary>The user_version value found in the database.</summary>
|
||||
/// <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 {
|
||||
/// <summary>
|
||||
/// Gets the user_version value found in the database.
|
||||
/// </summary>
|
||||
public long StoredVersion { get; }
|
||||
|
||||
/// <summary>The latest schema version this build understands.</summary>
|
||||
/// <summary>
|
||||
/// Gets the newest schema version this build understands.
|
||||
/// </summary>
|
||||
public int SupportedVersion { get; }
|
||||
|
||||
/// <summary>Creates an exception for an unmanageable schema version.</summary>
|
||||
/// <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)
|
||||
: 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}.") {
|
||||
StoredVersion = storedVersion;
|
||||
SupportedVersion = supportedVersion;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
namespace YKanBan.Storage;
|
||||
|
||||
/// <summary>Provides the current Unix time; all persisted timestamps are INTEGER Unix seconds.</summary>
|
||||
public static class UnixTime
|
||||
{
|
||||
/// <summary>Current UTC time as Unix seconds.</summary>
|
||||
/// <summary>
|
||||
/// Supplies the current Unix timestamp. Every timestamp persisted by YKanBan
|
||||
/// is an INTEGER count of Unix seconds.
|
||||
/// </summary>
|
||||
public static class UnixTime {
|
||||
/// <summary>
|
||||
/// Gets the current UTC time expressed as Unix seconds.
|
||||
/// </summary>
|
||||
public static long Now => DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -4,31 +4,43 @@ namespace YKanBan.Storage.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the .ykanban structure for a folder: the folder itself and an
|
||||
/// empty, fully migrated database. Seeding preset content is a separate
|
||||
/// concern handled by <see cref="WorkspacePreset"/>.
|
||||
/// empty, fully migrated database. Adding preset content is deliberately a
|
||||
/// separate concern handled by <see cref="WorkspacePreset"/>, so the
|
||||
/// database can be created without any rows.
|
||||
/// </summary>
|
||||
public static class WorkspaceInitializer
|
||||
{
|
||||
/// <summary>Returns true when the folder contains a .ykanban structure (no parent lookup).</summary>
|
||||
public static class WorkspaceInitializer {
|
||||
/// <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));
|
||||
|
||||
/// <summary>Initializes a fresh workspace: creates .ykanban and an empty migrated database.</summary>
|
||||
/// <summary>
|
||||
/// Initializes a fresh workspace: creates .ykanban and an empty migrated
|
||||
/// database, without adding any preset content.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The existing folder to initialize.</param>
|
||||
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
||||
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
|
||||
public static void Initialize(string folderPath)
|
||||
{
|
||||
if (!Directory.Exists(folderPath))
|
||||
{
|
||||
public static void Initialize(string folderPath) {
|
||||
// YYC MARK: this class is deliberately a lock-free, functional unit; it
|
||||
// does not acquire the workspace lock. Ensuring the lock is held before
|
||||
// initialization is the caller's responsibility (see
|
||||
// WorkspaceSession.Initialize). The schema migration and the later preset
|
||||
// writes are also not one transaction, so a crash mid-initialization can
|
||||
// leave a partially built database; that is accepted here.
|
||||
if (!Directory.Exists(folderPath)) {
|
||||
throw new WorkspaceDirectoryMissingException(folderPath);
|
||||
}
|
||||
|
||||
string databasePath = WorkspacePaths.Database(folderPath);
|
||||
if (File.Exists(databasePath))
|
||||
{
|
||||
if (File.Exists(databasePath)) {
|
||||
throw new InvalidOperationException($"The workspace database already exists: {databasePath}");
|
||||
}
|
||||
|
||||
// Create the .ykanban folder and the migrated, still empty database.
|
||||
// Create the .ykanban folder, then the migrated but still empty database.
|
||||
Directory.CreateDirectory(WorkspacePaths.Root(folderPath));
|
||||
using SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations);
|
||||
}
|
||||
|
||||
@@ -1,72 +1,56 @@
|
||||
using System.Text;
|
||||
|
||||
namespace YKanBan.Storage.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Exclusive, OS-enforced lock over a workspace's ykanban.lock. The handle
|
||||
/// is held until disposal; crashes and power loss release it automatically.
|
||||
/// The lock file carries PID / machine name / time for human diagnostics
|
||||
/// only.
|
||||
/// Exclusive, OS-enforced lock over a workspace's ykanban.lock. The handle is
|
||||
/// held until disposal, so crashes and power loss release it automatically. The
|
||||
/// lock file is kept empty; only its exclusive OS handle carries meaning.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceLock : IDisposable
|
||||
{
|
||||
public sealed class WorkspaceLock : IDisposable {
|
||||
private readonly FileStream _stream;
|
||||
|
||||
private WorkspaceLock(FileStream stream, string lockFilePath)
|
||||
{
|
||||
/// <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) {
|
||||
_stream = stream;
|
||||
LockFilePath = lockFilePath;
|
||||
}
|
||||
|
||||
/// <summary>Path of the lock file being held.</summary>
|
||||
/// <summary>
|
||||
/// Gets the path of the lock file being held.
|
||||
/// </summary>
|
||||
public string LockFilePath { get; }
|
||||
|
||||
/// <summary>Acquires the workspace lock or throws <see cref="WorkspaceLockException"/>.</summary>
|
||||
/// <summary>
|
||||
/// Acquires the workspace lock, leaving the lock file empty.
|
||||
/// </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="WorkspaceLockException">Another instance holds the lock.</exception>
|
||||
public static WorkspaceLock Acquire(string folderPath)
|
||||
{
|
||||
/// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception>
|
||||
public static WorkspaceLock Acquire(string folderPath) {
|
||||
string lockFilePath = WorkspacePaths.LockFile(folderPath);
|
||||
FileStream stream;
|
||||
try
|
||||
{
|
||||
// FileShare.None gives the exclusive semantics; FileMode.Create truncates any stale content.
|
||||
try {
|
||||
// FileShare.None gives the exclusive semantics; FileMode.Create empties any stale file.
|
||||
// SAFETY: FileMode.Create truncates a pre-existing file, but the lock
|
||||
// file is empty by design and the path always comes from
|
||||
// WorkspacePaths.LockFile, so no user data is ever affected.
|
||||
stream = new FileStream(lockFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
} catch (DirectoryNotFoundException) {
|
||||
throw new WorkspaceNotInitializedException(folderPath);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
throw new WorkspaceLockException(lockFilePath, ReadDiagnosticsBestEffort(lockFilePath), ex);
|
||||
} catch (IOException ex) {
|
||||
throw new WorkspaceLockException(lockFilePath, ex);
|
||||
}
|
||||
|
||||
// Write holder diagnostics so humans can identify the owning instance from the file alone.
|
||||
string diagnostics = $"pid={Environment.ProcessId};machine={Environment.MachineName};time={DateTimeOffset.UtcNow:O}";
|
||||
byte[] payload = Encoding.UTF8.GetBytes(diagnostics);
|
||||
stream.Write(payload, 0, payload.Length);
|
||||
stream.Flush();
|
||||
return new WorkspaceLock(stream, lockFilePath);
|
||||
}
|
||||
|
||||
/// <summary>Attempts to read holder diagnostics from a lock file we failed to acquire.</summary>
|
||||
private static string? ReadDiagnosticsBestEffort(string lockFilePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
return File.ReadAllText(lockFilePath);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Releases the exclusive handle. The lock file itself is intentionally left on disk.</summary>
|
||||
/// <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();
|
||||
}
|
||||
@@ -1,23 +1,43 @@
|
||||
namespace YKanBan.Storage.Workspace;
|
||||
|
||||
/// <summary>Well-known file and folder names inside a workspace's .ykanban structure.</summary>
|
||||
public static class WorkspacePaths
|
||||
{
|
||||
/// <summary>Name of the workspace root folder created inside a managed project.</summary>
|
||||
/// <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 {
|
||||
/// <summary>
|
||||
/// Name of the workspace root folder created inside a managed project.
|
||||
/// </summary>
|
||||
public const string RootFolderName = ".ykanban";
|
||||
|
||||
/// <summary>Name of the SQLite database inside .ykanban.</summary>
|
||||
/// <summary>
|
||||
/// Name of the SQLite database inside .ykanban.
|
||||
/// </summary>
|
||||
public const string DatabaseFileName = "ykanban.db";
|
||||
|
||||
/// <summary>Name of the exclusive lock file inside .ykanban.</summary>
|
||||
/// <summary>
|
||||
/// Name of the exclusive lock file inside .ykanban.
|
||||
/// </summary>
|
||||
public const string LockFileName = "ykanban.lock";
|
||||
|
||||
/// <summary>Returns the .ykanban root path for a workspace folder.</summary>
|
||||
/// <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);
|
||||
|
||||
/// <summary>Returns the workspace database path for a workspace folder.</summary>
|
||||
public static string Database(string folderPath) => Path.Combine(folderPath, RootFolderName, DatabaseFileName);
|
||||
/// <summary>
|
||||
/// Returns the workspace database path for a workspace folder.
|
||||
/// </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>Returns the workspace lock file path for a workspace folder.</summary>
|
||||
public static string LockFile(string folderPath) => Path.Combine(folderPath, RootFolderName, LockFileName);
|
||||
/// <summary>
|
||||
/// Returns the workspace lock file path for a workspace folder.
|
||||
/// </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);
|
||||
}
|
||||
@@ -3,44 +3,85 @@ using Microsoft.Data.Sqlite;
|
||||
namespace YKanBan.Storage.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Seeds initial workspace content. The three preset column titles are read
|
||||
/// straight from the ResX resources in the UI language active at seeding
|
||||
/// time, then stored as ordinary data that no longer follows language
|
||||
/// switches.
|
||||
/// Adds the initial workspace content. The preset column titles/descriptions and
|
||||
/// tag names/descriptions are read straight from the ResX resources in the UI
|
||||
/// language active when they are added; they then become ordinary data that no
|
||||
/// longer follows language switches.
|
||||
/// </summary>
|
||||
public static class WorkspacePreset
|
||||
{
|
||||
/// <summary>Inserts the three preset columns (To Do / In Progress / Done equivalents).</summary>
|
||||
/// <exception cref="SqliteException">A title collides with an existing column.</exception>
|
||||
public static void SeedColumns(string folderPath)
|
||||
{
|
||||
public static class WorkspacePreset {
|
||||
/// <summary>
|
||||
/// Inserts the three preset columns (the current language's equivalents of
|
||||
/// To Do / In Progress / Done) with their descriptions in a single transaction.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The initialized workspace folder.</param>
|
||||
/// <exception cref="SqliteException">The workspace database does not exist or a title collides with an existing column.</exception>
|
||||
public static void AddPresetColumns(string folderPath) {
|
||||
using SqliteConnection connection = SqliteDatabase.Open(
|
||||
WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
|
||||
|
||||
long now = UnixTime.Now;
|
||||
|
||||
// Preset titles are data at creation time: whatever the current language says gets stored.
|
||||
string[] titles =
|
||||
// Preset titles and descriptions are data at creation time: whatever the current language says gets stored.
|
||||
(string Title, string Description)[] columns =
|
||||
[
|
||||
Resources.PresetColumn_Todo,
|
||||
Resources.PresetColumn_InProgress,
|
||||
Resources.PresetColumn_Done,
|
||||
(Resources.PresetColumn_Todo, Resources.PresetColumn_Todo_Description),
|
||||
(Resources.PresetColumn_InProgress, Resources.PresetColumn_InProgress_Description),
|
||||
(Resources.PresetColumn_Done, Resources.PresetColumn_Done_Description),
|
||||
];
|
||||
|
||||
// Insert all three in one transaction so a half-seeded workspace can never exist.
|
||||
// Insert all three atomically so a partially populated workspace can never exist.
|
||||
using var transaction = connection.BeginTransaction();
|
||||
foreach (string title in titles)
|
||||
{
|
||||
foreach ((string title, string description) in columns) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = """
|
||||
INSERT INTO columns (title, description, created_at, updated_at)
|
||||
VALUES ($title, '', $now, $now);
|
||||
VALUES ($title, $description, $now, $now);
|
||||
""";
|
||||
command.Parameters.AddWithValue("$title", title);
|
||||
command.Parameters.AddWithValue("$description", description);
|
||||
command.Parameters.AddWithValue("$now", now);
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
transaction.Commit();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts the preset tag set (names, colors and descriptions in the current
|
||||
/// language) in a single transaction.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The initialized workspace folder.</param>
|
||||
/// <exception cref="SqliteException">The workspace database does not exist or a tag name collides.</exception>
|
||||
public static void AddPresetTags(string folderPath) {
|
||||
using SqliteConnection connection = SqliteDatabase.Open(
|
||||
WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
|
||||
|
||||
// Colors are stored in the canonical lowercase #rrggbb form.
|
||||
(string Name, string Color, string Description)[] tags =
|
||||
[
|
||||
(Resources.PresetTag_Bug_Name, "#d73a4a", Resources.PresetTag_Bug_Description),
|
||||
(Resources.PresetTag_Documentation_Name, "#0075ca", Resources.PresetTag_Documentation_Description),
|
||||
(Resources.PresetTag_Duplicate_Name, "#cfd3d7", Resources.PresetTag_Duplicate_Description),
|
||||
(Resources.PresetTag_Enhancement_Name, "#a2eeef", Resources.PresetTag_Enhancement_Description),
|
||||
(Resources.PresetTag_HelpWanted_Name, "#008672", Resources.PresetTag_HelpWanted_Description),
|
||||
(Resources.PresetTag_Invalid_Name, "#e4e669", Resources.PresetTag_Invalid_Description),
|
||||
(Resources.PresetTag_Question_Name, "#d876e3", Resources.PresetTag_Question_Description),
|
||||
(Resources.PresetTag_Wontfix_Name, "#ffffff", Resources.PresetTag_Wontfix_Description),
|
||||
];
|
||||
|
||||
using var transaction = connection.BeginTransaction();
|
||||
foreach ((string name, string color, string description) in tags) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = """
|
||||
INSERT INTO tags (name, color, description)
|
||||
VALUES ($name, $color, $description);
|
||||
""";
|
||||
command.Parameters.AddWithValue("$name", name);
|
||||
command.Parameters.AddWithValue("$color", color);
|
||||
command.Parameters.AddWithValue("$description", description);
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
transaction.Commit();
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Search;
|
||||
|
||||
namespace YKanBan.Storage.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Data access for one open workspace database: CRUD for columns, cards and
|
||||
/// 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.
|
||||
/// tags, card moves and tag assignment. Cascading deletes are left to the DDL.
|
||||
///
|
||||
/// Timestamp rules:
|
||||
/// - cards.updated_at refreshes only when a card edit is confirmed with
|
||||
@@ -16,45 +15,46 @@ namespace YKanBan.Storage.Workspace;
|
||||
/// - columns.updated_at refreshes only when title or description changes;
|
||||
/// - a confirmation with no effective change performs no write at all.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceRepository : IDisposable
|
||||
{
|
||||
private readonly string _folderPath;
|
||||
private readonly AppDatabase _appDatabase;
|
||||
public sealed class WorkspaceRepository : IDisposable {
|
||||
private readonly SqliteConnection _connection;
|
||||
|
||||
/// <summary>Opens the repository over an initialized workspace database.</summary>
|
||||
/// <param name="folderPath">Workspace folder; the exact value is used as the app.db registry key.</param>
|
||||
/// <param name="appDatabase">Global registry refreshed after every successful write.</param>
|
||||
public WorkspaceRepository(string folderPath, AppDatabase appDatabase)
|
||||
{
|
||||
_folderPath = folderPath;
|
||||
_appDatabase = appDatabase;
|
||||
/// <summary>
|
||||
/// Opens the repository over an initialized workspace database.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder.</param>
|
||||
public WorkspaceRepository(string folderPath) {
|
||||
_connection = SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
|
||||
}
|
||||
|
||||
/// <summary>Closes the underlying connection.</summary>
|
||||
/// <summary>
|
||||
/// Closes the underlying connection.
|
||||
/// </summary>
|
||||
public void Dispose() => _connection.Dispose();
|
||||
|
||||
#region Columns
|
||||
|
||||
/// <summary>Returns all columns ordered by id.</summary>
|
||||
public IReadOnlyList<ColumnModel> GetColumns()
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns all columns ordered by id ascending.
|
||||
/// </summary>
|
||||
/// <returns>All columns in id order.</returns>
|
||||
public IReadOnlyList<ColumnModel> GetColumns() {
|
||||
using var command = CreateCommand(
|
||||
"SELECT id, title, description, created_at, updated_at FROM columns ORDER BY id ASC;");
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var columns = new List<ColumnModel>();
|
||||
while (reader.Read())
|
||||
{
|
||||
while (reader.Read()) {
|
||||
columns.Add(ReadColumn(reader));
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
/// <summary>Returns the column with the given id, or null.</summary>
|
||||
public ColumnModel? GetColumn(long columnId)
|
||||
{
|
||||
/// <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) {
|
||||
using var command = CreateCommand(
|
||||
"SELECT id, title, description, created_at, updated_at FROM columns WHERE id = $id;");
|
||||
command.Parameters.AddWithValue("$id", columnId);
|
||||
@@ -62,10 +62,14 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
return reader.Read() ? ReadColumn(reader) : null;
|
||||
}
|
||||
|
||||
/// <summary>Creates a column with created_at = updated_at.</summary>
|
||||
/// <summary>
|
||||
/// Creates a column with created_at equal to updated_at.
|
||||
/// </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="SqliteException">The title is empty or not unique.</exception>
|
||||
public ColumnModel AddColumn(string title, string description)
|
||||
{
|
||||
public ColumnModel AddColumn(string title, string description) {
|
||||
long now = UnixTime.Now;
|
||||
using var transaction = _connection.BeginTransaction();
|
||||
long id = ExecuteInsert(transaction,
|
||||
@@ -73,21 +77,25 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
("$title", title), ("$description", description), ("$now", now));
|
||||
transaction.Commit();
|
||||
|
||||
TouchEdited();
|
||||
return new ColumnModel(id, title, description, now, now);
|
||||
}
|
||||
|
||||
/// <summary>Rewrites title and description; a no-change call writes nothing.</summary>
|
||||
/// <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="SqliteException">The new title is empty or 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)
|
||||
?? throw new InvalidOperationException($"Column {columnId} does not exist.");
|
||||
|
||||
// Unchanged title and description: no write, no timestamps.
|
||||
if (existing.Title == title && existing.Description == description)
|
||||
{
|
||||
// Unchanged title and description: no write, no timestamp refresh.
|
||||
if (existing.Title == title && existing.Description == description) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
@@ -100,20 +108,25 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
command.Parameters.AddWithValue("$id", columnId);
|
||||
command.ExecuteNonQuery();
|
||||
|
||||
TouchEdited();
|
||||
return new ColumnModel(columnId, title, description, existing.CreatedAt, now);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a column; the DDL cascade removes its cards and their tag links. Returns true when a row was deleted.</summary>
|
||||
/// <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);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Cards
|
||||
|
||||
/// <summary>Returns all cards with their tags loaded, ordered by id.</summary>
|
||||
public IReadOnlyList<CardModel> GetCards()
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns all cards with their assigned tags loaded, ordered by id ascending.
|
||||
/// </summary>
|
||||
/// <returns>All cards in id order.</returns>
|
||||
public IReadOnlyList<CardModel> GetCards() {
|
||||
using var command = CreateCommand("""
|
||||
SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at,
|
||||
t.id, t.name, t.color, t.description
|
||||
@@ -124,14 +137,12 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
""");
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
// Single grouped pass: one output card per distinct card id, its tags accumulated alongside.
|
||||
// Single grouped pass: one output card per distinct card id, with its tags accumulated alongside.
|
||||
var cards = new List<CardModel>();
|
||||
var tagsByCard = new Dictionary<long, List<TagModel>>();
|
||||
while (reader.Read())
|
||||
{
|
||||
while (reader.Read()) {
|
||||
long cardId = reader.GetInt64(0);
|
||||
if (!tagsByCard.TryGetValue(cardId, out List<TagModel>? tags))
|
||||
{
|
||||
if (!tagsByCard.TryGetValue(cardId, out List<TagModel>? tags)) {
|
||||
tags = new List<TagModel>();
|
||||
tagsByCard[cardId] = tags;
|
||||
cards.Add(new CardModel(
|
||||
@@ -143,17 +154,39 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
reader.GetInt64(5),
|
||||
tags));
|
||||
}
|
||||
if (!reader.IsDBNull(6))
|
||||
{
|
||||
tags.Add(new TagModel(reader.GetInt64(6), reader.GetString(7), RgbColor.Parse(reader.GetString(8)), reader.GetString(9)));
|
||||
|
||||
if (!reader.IsDBNull(6)) {
|
||||
tags.Add(ReadTag(reader, 6));
|
||||
}
|
||||
}
|
||||
return cards;
|
||||
}
|
||||
|
||||
/// <summary>Returns the card with the given id (tags loaded), or null.</summary>
|
||||
public CardModel? GetCard(long cardId)
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the ids of the cards matching a compiled search predicate.
|
||||
/// </summary>
|
||||
/// <param name="search">The compiled search predicate and its parameters.</param>
|
||||
/// <returns>The matching card ids.</returns>
|
||||
public IReadOnlyCollection<long> GetCardIdsMatching(CompiledSearch search) {
|
||||
using var command = CreateCommand($"SELECT c.id FROM cards c WHERE {search.Predicate};");
|
||||
foreach ((string name, object value) in search.Parameters) {
|
||||
command.Parameters.AddWithValue(name, value);
|
||||
}
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var ids = new HashSet<long>();
|
||||
while (reader.Read()) {
|
||||
ids.Add(reader.GetInt64(0));
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/// <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) {
|
||||
using var command = CreateCommand("""
|
||||
SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at,
|
||||
t.id, t.name, t.color, t.description
|
||||
@@ -166,13 +199,11 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
command.Parameters.AddWithValue("$id", cardId);
|
||||
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;
|
||||
var tags = new List<TagModel>();
|
||||
while (reader.Read())
|
||||
{
|
||||
if (card is null)
|
||||
{
|
||||
card = new CardModel(
|
||||
while (reader.Read()) {
|
||||
card ??= new CardModel(
|
||||
reader.GetInt64(0),
|
||||
reader.GetInt64(1),
|
||||
reader.GetString(2),
|
||||
@@ -180,121 +211,129 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
reader.GetInt64(4),
|
||||
reader.GetInt64(5),
|
||||
tags);
|
||||
}
|
||||
if (!reader.IsDBNull(6))
|
||||
{
|
||||
tags.Add(new TagModel(reader.GetInt64(6), reader.GetString(7), RgbColor.Parse(reader.GetString(8)), reader.GetString(9)));
|
||||
|
||||
if (!reader.IsDBNull(6)) {
|
||||
tags.Add(ReadTag(reader, 6));
|
||||
}
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
/// <summary>Creates a card with its initial tag assignment (created_at = updated_at).</summary>
|
||||
/// <exception cref="SqliteException">The column does not exist, or a tag id does not exist.</exception>
|
||||
public CardModel AddCard(long columnId, string title, string content, IReadOnlyCollection<long> tagIds)
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a card with its initial tag assignment and created_at equal to updated_at.
|
||||
/// </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) {
|
||||
long now = UnixTime.Now;
|
||||
using var transaction = _connection.BeginTransaction();
|
||||
long id = ExecuteInsert(transaction,
|
||||
"INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES ($columnId, $title, $content, $now, $now);",
|
||||
("$columnId", columnId), ("$title", title), ("$content", content), ("$now", now));
|
||||
foreach (long tagId in tagIds.Distinct())
|
||||
{
|
||||
foreach (long tagId in tagIds.Distinct()) {
|
||||
ExecuteNonQuery(transaction,
|
||||
"INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);",
|
||||
("$cardId", id), ("$tagId", tagId));
|
||||
}
|
||||
transaction.Commit();
|
||||
|
||||
TouchEdited();
|
||||
return new CardModel(id, columnId, title, content, now, now, LoadTags(id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies one card edit confirmation as a single atomic unit: the card
|
||||
/// row (title, content, refreshed updated_at) plus the complete tag
|
||||
/// assignment. A confirmation with no effective change writes nothing;
|
||||
/// a failure mid-way rolls the whole edit back.
|
||||
/// Applies one card edit confirmation as a single atomic unit: the card row
|
||||
/// (title, content, refreshed updated_at) plus the complete tag assignment.
|
||||
/// A confirmation with no effective change writes nothing; a failure
|
||||
/// mid-way rolls the whole edit back.
|
||||
/// </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="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) {
|
||||
CardModel existing = GetCard(cardId)
|
||||
?? throw new InvalidOperationException($"Card {cardId} does not exist.");
|
||||
|
||||
// No change in title, content or tag set: no write, no timestamps.
|
||||
// No effective change in title, content or tag set: no write, no timestamp refresh.
|
||||
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;
|
||||
}
|
||||
|
||||
// The confirmed write refreshes updated_at even when only the tag set changed.
|
||||
long now = UnixTime.Now;
|
||||
using var transaction = _connection.BeginTransaction();
|
||||
// The confirm write refreshes updated_at even when only the tag set changed.
|
||||
ExecuteNonQuery(transaction,
|
||||
"UPDATE cards SET title = $title, content = $content, updated_at = $now WHERE id = $id;",
|
||||
("$title", title), ("$content", content), ("$now", now), ("$id", cardId));
|
||||
|
||||
// Tag assignment is rewritten wholesale; card_tags carries nothing beyond the pair.
|
||||
ExecuteNonQuery(transaction, "DELETE FROM card_tags WHERE card_id = $id;", ("$id", cardId));
|
||||
foreach (long tagId in tagIds.Distinct())
|
||||
{
|
||||
foreach (long tagId in tagIds.Distinct()) {
|
||||
ExecuteNonQuery(transaction,
|
||||
"INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);",
|
||||
("$cardId", cardId), ("$tagId", tagId));
|
||||
}
|
||||
transaction.Commit();
|
||||
|
||||
TouchEdited();
|
||||
return new CardModel(cardId, existing.ColumnId, title, content, existing.CreatedAt, now, LoadTags(cardId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a card to another column. This is a data write (refreshes the
|
||||
/// workspace last_edited_at) but deliberately does NOT refresh the
|
||||
/// card's updated_at; moving to the current column is a no-write no-op.
|
||||
/// Returns true when the card moved.
|
||||
/// Moves a card to another column. This writes to the database but
|
||||
/// deliberately does NOT refresh the card's updated_at; moving to the
|
||||
/// current column is a no-op.
|
||||
/// </summary>
|
||||
public bool MoveCard(long cardId, long targetColumnId)
|
||||
{
|
||||
/// <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) {
|
||||
using var command = CreateCommand(
|
||||
"UPDATE cards SET column_id = $columnId WHERE id = $id AND column_id <> $columnId;");
|
||||
command.Parameters.AddWithValue("$columnId", targetColumnId);
|
||||
command.Parameters.AddWithValue("$id", cardId);
|
||||
bool moved = command.ExecuteNonQuery() > 0;
|
||||
if (moved)
|
||||
{
|
||||
TouchEdited();
|
||||
}
|
||||
return moved;
|
||||
return command.ExecuteNonQuery() > 0;
|
||||
}
|
||||
|
||||
/// <summary>Deletes a card; the DDL cascade removes its tag links. Returns true when a row was deleted.</summary>
|
||||
/// <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);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Tags
|
||||
|
||||
/// <summary>Returns all tags ordered by id; unreferenced tags are included.</summary>
|
||||
public IReadOnlyList<TagModel> GetTags()
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns all tags ordered by id ascending; unreferenced tags are included.
|
||||
/// </summary>
|
||||
/// <returns>All tags in id order.</returns>
|
||||
public IReadOnlyList<TagModel> GetTags() {
|
||||
using var command = CreateCommand(
|
||||
"SELECT id, name, color, description FROM tags ORDER BY id ASC;");
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var tags = new List<TagModel>();
|
||||
while (reader.Read())
|
||||
{
|
||||
tags.Add(ReadTag(reader));
|
||||
while (reader.Read()) {
|
||||
tags.Add(ReadTag(reader, 0));
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
/// <summary>Returns every tag together with the number of cards using it, ordered by id.</summary>
|
||||
public IReadOnlyList<(TagModel Tag, long UsageCount)> GetTagsWithUsage()
|
||||
{
|
||||
/// <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() {
|
||||
using var command = CreateCommand("""
|
||||
SELECT t.id, t.name, t.color, t.description, COUNT(ct.card_id)
|
||||
FROM tags t
|
||||
@@ -305,38 +344,46 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var tags = new List<(TagModel Tag, long UsageCount)>();
|
||||
while (reader.Read())
|
||||
{
|
||||
tags.Add((ReadTag(reader), reader.GetInt64(4)));
|
||||
while (reader.Read()) {
|
||||
tags.Add((ReadTag(reader, 0), reader.GetInt64(4)));
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
/// <summary>Creates a tag.</summary>
|
||||
/// <exception cref="SqliteException">The name is empty/not unique.</exception>
|
||||
public TagModel AddTag(string name, RgbColor color, string description)
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a tag.
|
||||
/// </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="SqliteException">The name is empty or not unique.</exception>
|
||||
public TagModel AddTag(string name, RgbColor color, string description) {
|
||||
using var transaction = _connection.BeginTransaction();
|
||||
long id = ExecuteInsert(transaction,
|
||||
"INSERT INTO tags (name, color, description) VALUES ($name, $color, $description);",
|
||||
("$name", name), ("$color", color.ToString()), ("$description", description));
|
||||
transaction.Commit();
|
||||
|
||||
TouchEdited();
|
||||
return new TagModel(id, name, color, description);
|
||||
}
|
||||
|
||||
/// <summary>Rewrites name, color and description; a no-change call writes nothing.</summary>
|
||||
/// <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="SqliteException">The new name is empty/not unique.</exception>
|
||||
public TagModel UpdateTag(long tagId, string name, RgbColor color, string description)
|
||||
{
|
||||
/// <exception cref="SqliteException">The new name is empty or not unique.</exception>
|
||||
public TagModel UpdateTag(long tagId, string name, RgbColor color, string description) {
|
||||
TagModel existing = GetTag(tagId)
|
||||
?? throw new InvalidOperationException($"Tag {tagId} does not exist.");
|
||||
|
||||
// Unchanged name, color and description: no write.
|
||||
if (existing.Name == name && existing.Color == color && existing.Description == description)
|
||||
{
|
||||
if (existing.Name == name && existing.Color == color && existing.Description == description) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
@@ -348,30 +395,39 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
command.Parameters.AddWithValue("$id", tagId);
|
||||
command.ExecuteNonQuery();
|
||||
|
||||
TouchEdited();
|
||||
return new TagModel(tagId, name, color, description);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a tag; the DDL cascade removes its card links while the cards survive. Returns true when a row was deleted.</summary>
|
||||
/// <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);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Helpers
|
||||
|
||||
/// <summary>Returns the tag with the given id, or null.</summary>
|
||||
private TagModel? GetTag(long tagId)
|
||||
{
|
||||
/// <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) {
|
||||
using var command = CreateCommand(
|
||||
"SELECT id, name, color, description FROM tags WHERE id = $id;");
|
||||
command.Parameters.AddWithValue("$id", tagId);
|
||||
using var reader = command.ExecuteReader();
|
||||
return reader.Read() ? ReadTag(reader) : null;
|
||||
return reader.Read() ? ReadTag(reader, 0) : null;
|
||||
}
|
||||
|
||||
/// <summary>Returns the tags currently assigned to a card, ordered by id.</summary>
|
||||
private IReadOnlyList<TagModel> LoadTags(long cardId)
|
||||
{
|
||||
/// <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) {
|
||||
using var command = CreateCommand("""
|
||||
SELECT t.id, t.name, t.color, t.description
|
||||
FROM tags t
|
||||
@@ -383,64 +439,81 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var tags = new List<TagModel>();
|
||||
while (reader.Read())
|
||||
{
|
||||
tags.Add(ReadTag(reader));
|
||||
while (reader.Read()) {
|
||||
tags.Add(ReadTag(reader, 0));
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
/// <summary>Reads a columns row from the reader cursor.</summary>
|
||||
/// <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) =>
|
||||
new(reader.GetInt64(0), reader.GetString(1), reader.GetString(2), reader.GetInt64(3), reader.GetInt64(4));
|
||||
|
||||
/// <summary>Reads a tags row from the reader cursor; color text converts to components.</summary>
|
||||
private static TagModel ReadTag(SqliteDataReader reader) =>
|
||||
new(reader.GetInt64(0), reader.GetString(1), RgbColor.Parse(reader.GetString(2)), reader.GetString(3));
|
||||
/// <summary>
|
||||
/// Reads a tags row from the reader cursor, starting at the given column
|
||||
/// offset; the color text is converted to its components.
|
||||
/// </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>Creates a command bound to this connection.</summary>
|
||||
private SqliteCommand CreateCommand(string sql, SqliteTransaction? transaction = null)
|
||||
{
|
||||
/// <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) {
|
||||
SqliteCommand command = _connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = sql;
|
||||
return command;
|
||||
}
|
||||
|
||||
/// <summary>Executes a parameterized non-query statement inside a transaction.</summary>
|
||||
private void ExecuteNonQuery(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters)
|
||||
{
|
||||
/// <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) {
|
||||
using SqliteCommand command = CreateCommand(sql, transaction);
|
||||
foreach ((string name, object? value) in parameters)
|
||||
{
|
||||
foreach ((string name, object? value) in parameters) {
|
||||
command.Parameters.AddWithValue(name, value);
|
||||
}
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
/// <summary>Inserts a row inside a transaction and returns the generated rowid.</summary>
|
||||
private long ExecuteInsert(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters)
|
||||
{
|
||||
/// <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) {
|
||||
ExecuteNonQuery(transaction, sql, parameters);
|
||||
using SqliteCommand rowId = CreateCommand("SELECT last_insert_rowid();", transaction);
|
||||
return (long)rowId.ExecuteScalar()!;
|
||||
}
|
||||
|
||||
/// <summary>Deletes by id; refreshes last_edited_at only when a row was actually removed.</summary>
|
||||
private bool ExecuteDelete(string sql, long id)
|
||||
{
|
||||
/// <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) {
|
||||
using SqliteCommand command = CreateCommand(sql);
|
||||
command.Parameters.AddWithValue("$id", id);
|
||||
if (command.ExecuteNonQuery() == 0)
|
||||
{
|
||||
return false;
|
||||
return command.ExecuteNonQuery() > 0;
|
||||
}
|
||||
TouchEdited();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Mirrors a successful data write into the global registry.</summary>
|
||||
private void TouchEdited() => _appDatabase.TouchLastEdited(_folderPath);
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -1,21 +1,24 @@
|
||||
namespace YKanBan.Storage.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Schema definitions for the per-workspace database. The board is a single
|
||||
/// board with a columns → cards hierarchy. All data validation is expressed
|
||||
/// in DDL (CHECK / UNIQUE / FOREIGN KEY) so that any row entering the
|
||||
/// database is valid by construction; cascading deletes are covered by the
|
||||
/// same DDL.
|
||||
/// Schema definitions for the per-workspace database. A workspace holds a
|
||||
/// single board with a columns → cards hierarchy plus tags and their
|
||||
/// assignments. Data validity is expressed in DDL (CHECK / UNIQUE / FOREIGN
|
||||
/// KEY) so every stored row is valid by construction, and cascading deletes
|
||||
/// are covered by the same DDL.
|
||||
/// </summary>
|
||||
public static class WorkspaceSchema
|
||||
{
|
||||
/// <summary>Latest workspace schema version this build understands.</summary>
|
||||
public static class WorkspaceSchema {
|
||||
/// <summary>
|
||||
/// Newest workspace schema version this build understands.
|
||||
/// </summary>
|
||||
public const int CurrentVersion = 1;
|
||||
|
||||
/// <summary>Ordered, contiguous migration list for the workspace database.</summary>
|
||||
public static readonly IReadOnlyList<SchemaMigration> Migrations = new SchemaMigration[]
|
||||
{
|
||||
new SchemaMigration(1, "initial schema", """
|
||||
/// <summary>
|
||||
/// Ordered, contiguous migration list for the workspace database.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<SchemaMigration> Migrations =
|
||||
[
|
||||
new SchemaMigration(CurrentVersion, "initial schema", """
|
||||
CREATE TABLE columns (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL UNIQUE CHECK (length(title) > 0),
|
||||
@@ -46,5 +49,5 @@ public static class WorkspaceSchema
|
||||
PRIMARY KEY (card_id, tag_id)
|
||||
);
|
||||
"""),
|
||||
};
|
||||
];
|
||||
}
|
||||
@@ -1,21 +1,106 @@
|
||||
namespace YKanBan.Storage.Workspace;
|
||||
|
||||
/// <summary>One open workspace: the exclusive lock plus its repository.</summary>
|
||||
public sealed class WorkspaceSession : IDisposable
|
||||
{
|
||||
/// <summary>Canonical workspace folder path.</summary>
|
||||
public required string FolderPath { get; init; }
|
||||
/// <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 {
|
||||
private readonly WorkspaceLock _workspaceLock;
|
||||
|
||||
/// <summary>The exclusive lock held while this session is open.</summary>
|
||||
public required WorkspaceLock Lock { get; init; }
|
||||
/// <summary>
|
||||
/// Initializes the session around an acquired lock and an open repository.
|
||||
/// </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>The data access object for this workspace.</summary>
|
||||
public required WorkspaceRepository Repository { get; init; }
|
||||
/// <summary>
|
||||
/// Gets the canonical workspace folder path.
|
||||
/// </summary>
|
||||
public string FolderPath { get; }
|
||||
|
||||
/// <summary>Disposes the repository, then releases the lock.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
/// <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="WorkspaceDatabaseMissingException">.ykanban exists but its database file does not.</exception>
|
||||
/// <exception cref="WorkspaceLockException">Another instance already holds the lock.</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 tags, then opens it.
|
||||
/// The lock is taken right after .ykanban is created and is never released in
|
||||
/// between, so no other instance can interleave with the initialization.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The existing folder to initialize.</param>
|
||||
/// <returns>The opened session; dispose it to release the lock and connection.</returns>
|
||||
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
||||
/// <exception cref="WorkspaceLockException">Another instance holds the workspace lock.</exception>
|
||||
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
|
||||
public static WorkspaceSession Initialize(string folderPath) {
|
||||
// .ykanban first: the lock file lives inside it. Taking the lock here,
|
||||
// before any database work, keeps two instances from initializing the same
|
||||
// folder at once; WorkspaceInitializer stays a lock-free functional class.
|
||||
Directory.CreateDirectory(WorkspacePaths.Root(folderPath));
|
||||
WorkspaceLock workspaceLock = WorkspaceLock.Acquire(folderPath);
|
||||
try {
|
||||
WorkspaceInitializer.Initialize(folderPath);
|
||||
WorkspacePreset.AddPresetColumns(folderPath);
|
||||
WorkspacePreset.AddPresetTags(folderPath);
|
||||
return OpenLocked(folderPath, workspaceLock);
|
||||
} catch {
|
||||
workspaceLock.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the repository under an already held lock; the lock is released if that fails.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder.</param>
|
||||
/// <param name="workspaceLock">The held workspace lock.</param>
|
||||
/// <returns>The opened session.</returns>
|
||||
private static WorkspaceSession OpenLocked(string folderPath, WorkspaceLock workspaceLock) {
|
||||
try {
|
||||
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() {
|
||||
Repository.Dispose();
|
||||
Lock.Dispose();
|
||||
_workspaceLock.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
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)!;
|
||||
}
|
||||
|
||||
// YYC MARK: the missing-view placeholder is a programmer error (a view
|
||||
// model without its matching view), not a user-facing message. It must be
|
||||
// caught by the code-behind convention test before release, so it is kept
|
||||
// as a hard-coded English diagnostic and is deliberately not localized.
|
||||
return new TextBlock { Text = "Not Found: " + name };
|
||||
}
|
||||
|
||||
public bool Match(object? data) {
|
||||
return data is ViewModelBase;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Search;
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// The board tab: a toolbar (search box, add-column and the Display button)
|
||||
/// over horizontally arranged columns of vertically stacked cards. All
|
||||
/// persistence goes through the workspace repository; the board reloads from it
|
||||
/// after each change.
|
||||
/// </summary>
|
||||
public sealed partial class BoardViewModel : ViewModelBase {
|
||||
private readonly AppServices _services;
|
||||
private readonly WorkspaceRepository _repository;
|
||||
|
||||
// The active search result filter, or null when the whole board is shown.
|
||||
private IReadOnlyCollection<long>? _matchedCardIds;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the board, loading its current content.
|
||||
/// </summary>
|
||||
/// <param name="services">The process composition root (configuration access).</param>
|
||||
/// <param name="session">The open workspace session.</param>
|
||||
public BoardViewModel(AppServices services, WorkspaceSession session) {
|
||||
_services = services;
|
||||
_repository = session.Repository;
|
||||
Display = new DisplaySettingsViewModel(_services.Config, Reload);
|
||||
|
||||
Reload();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the workspace repository used for all board data access.
|
||||
/// </summary>
|
||||
public WorkspaceRepository Repository => _repository;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the live application configuration.
|
||||
/// </summary>
|
||||
public AppConfig Config => _services.Config;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display options (column width, card sort, column sort).
|
||||
/// </summary>
|
||||
public DisplaySettingsViewModel Display { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the columns shown by the board, in display order.
|
||||
/// </summary>
|
||||
public ObservableCollection<ColumnViewModel> Columns { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the search box text. The board does not filter on change;
|
||||
/// the search runs only when the search button is used.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string searchText = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the rendered column width in pixels, applied globally.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double columnWidth;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether a search filter is currently applied.
|
||||
/// </summary>
|
||||
public bool IsFiltering => _matchedCardIds is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized filter status text shown as the status icon tooltip.
|
||||
/// </summary>
|
||||
public string FilterStatusText => IsFiltering ? Resources.Board_FilterActive : Resources.Board_FilterInactive;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the status icon opacity: full while filtering, dimmed otherwise.
|
||||
/// </summary>
|
||||
public double FilterIconOpacity => IsFiltering ? 1.0 : 0.4;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the board has any columns.
|
||||
/// </summary>
|
||||
public bool HasColumns => Columns.Count > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the board is empty.
|
||||
/// </summary>
|
||||
public bool HasNoColumns => Columns.Count == 0;
|
||||
|
||||
#region Interactions
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that opens the new-column editor.
|
||||
/// </summary>
|
||||
public Interaction<Unit> AddColumn { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that opens the column editor.
|
||||
/// </summary>
|
||||
public Interaction<ColumnViewModel> EditColumn { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that confirms and deletes a column.
|
||||
/// </summary>
|
||||
public Interaction<ColumnViewModel> DeleteColumn { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that opens the new-card editor.
|
||||
/// </summary>
|
||||
public Interaction<ColumnViewModel> AddCard { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that opens the card editor.
|
||||
/// </summary>
|
||||
public Interaction<CardViewModel> EditCard { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that confirms and deletes a card.
|
||||
/// </summary>
|
||||
public Interaction<CardViewModel> DeleteCard { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that opens the move-card dialog.
|
||||
/// </summary>
|
||||
public Interaction<CardViewModel> MoveCard { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that shows the search error dialog, carrying the English parser detail.
|
||||
/// </summary>
|
||||
public Interaction<string> ShowSearchError { get; } = new();
|
||||
|
||||
#endregion
|
||||
|
||||
#region Commands
|
||||
|
||||
/// <summary>
|
||||
/// Opens the new-column editor.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private Task AddNewColumnAsync() => AddColumn.Handle(Unit.Value);
|
||||
|
||||
/// <summary>
|
||||
/// Runs the current search. A blank query shows everything; an invalid
|
||||
/// expression opens the error dialog and keeps the previous results and text.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task SearchAsync() {
|
||||
if (string.IsNullOrWhiteSpace(SearchText)) {
|
||||
ApplyFilter(null);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
SearchNode? query = SearchQueryParser.Parse(SearchText);
|
||||
if (query is null) {
|
||||
ApplyFilter(null);
|
||||
return;
|
||||
}
|
||||
|
||||
CompiledSearch compiled = SearchSqlCompiler.Compile(query);
|
||||
ApplyFilter(_repository.GetCardIdsMatching(compiled));
|
||||
} catch (SearchSyntaxException exception) {
|
||||
// The error dialog carries the parser's non-localized English detail.
|
||||
await ShowSearchError.Handle(exception.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the search box and restores the unfiltered board.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void ClearSearch() {
|
||||
SearchText = string.Empty;
|
||||
ApplyFilter(null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies a new result filter (null clears it) and rebuilds the board when it changed.
|
||||
/// </summary>
|
||||
/// <param name="matchedIds">The new filter, or <see langword="null"/> for no filter.</param>
|
||||
private void ApplyFilter(IReadOnlyCollection<long>? matchedIds) {
|
||||
if (_matchedCardIds is null && matchedIds is null) {
|
||||
return;
|
||||
}
|
||||
|
||||
_matchedCardIds = matchedIds;
|
||||
OnPropertyChanged(nameof(IsFiltering));
|
||||
OnPropertyChanged(nameof(FilterStatusText));
|
||||
OnPropertyChanged(nameof(FilterIconOpacity));
|
||||
Reload();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Requests from columns and cards
|
||||
|
||||
/// <summary>
|
||||
/// Requests the new-card editor for the given column.
|
||||
/// </summary>
|
||||
/// <param name="column">The target column.</param>
|
||||
/// <returns>A task completing after the editor closes.</returns>
|
||||
public Task RequestAddCardAsync(ColumnViewModel column) => AddCard.Handle(column);
|
||||
|
||||
/// <summary>
|
||||
/// Requests the editor for the given card.
|
||||
/// </summary>
|
||||
/// <param name="card">The card to edit.</param>
|
||||
/// <returns>A task completing after the editor closes.</returns>
|
||||
public Task RequestEditCardAsync(CardViewModel card) => EditCard.Handle(card);
|
||||
|
||||
/// <summary>
|
||||
/// Requests deletion of the given card.
|
||||
/// </summary>
|
||||
/// <param name="card">The card to delete.</param>
|
||||
/// <returns>A task completing after confirmation.</returns>
|
||||
public Task RequestDeleteCardAsync(CardViewModel card) => DeleteCard.Handle(card);
|
||||
|
||||
/// <summary>
|
||||
/// Requests moving the given card to another column.
|
||||
/// </summary>
|
||||
/// <param name="card">The card to move.</param>
|
||||
/// <returns>A task completing after the move.</returns>
|
||||
public Task RequestMoveCardAsync(CardViewModel card) => MoveCard.Handle(card);
|
||||
|
||||
/// <summary>
|
||||
/// Requests the editor for the given column.
|
||||
/// </summary>
|
||||
/// <param name="column">The column to edit.</param>
|
||||
/// <returns>A task completing after the editor closes.</returns>
|
||||
public Task RequestEditColumnAsync(ColumnViewModel column) => EditColumn.Handle(column);
|
||||
|
||||
/// <summary>
|
||||
/// Requests deletion of the given column.
|
||||
/// </summary>
|
||||
/// <param name="column">The column to delete.</param>
|
||||
/// <returns>A task completing after confirmation.</returns>
|
||||
public Task RequestDeleteColumnAsync(ColumnViewModel column) => DeleteColumn.Handle(column);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Loading and ordering
|
||||
|
||||
/// <summary>
|
||||
/// Reloads all columns and cards from the repository and rebuilds the board.
|
||||
/// </summary>
|
||||
public void Reload() {
|
||||
IReadOnlyList<ColumnModel> columns = _repository.GetColumns();
|
||||
IReadOnlyList<CardModel> cards = _repository.GetCards();
|
||||
|
||||
// An active search hides non-matching cards while every column stays visible.
|
||||
if (_matchedCardIds is not null) {
|
||||
cards = cards.Where(card => _matchedCardIds.Contains(card.Id)).ToList();
|
||||
}
|
||||
|
||||
// Group cards by column once so each column can be built independently.
|
||||
Dictionary<long, List<CardModel>> cardsByColumn = cards
|
||||
.GroupBy(card => card.ColumnId)
|
||||
.ToDictionary(group => group.Key, group => group.ToList());
|
||||
|
||||
IEnumerable<ColumnModel> orderedColumns = SortColumns(columns, _services.Config.Display.ColumnSort);
|
||||
|
||||
Columns.Clear();
|
||||
foreach (ColumnModel column in orderedColumns) {
|
||||
// Cards are sorted within their column by the selected card order.
|
||||
IEnumerable<CardModel> columnCards = cardsByColumn.TryGetValue(column.Id, out List<CardModel>? list)
|
||||
? SortCards(list, _services.Config.Display.CardSort)
|
||||
: [];
|
||||
Columns.Add(new ColumnViewModel(this, column, columnCards.Select(card => new CardViewModel(this, card))));
|
||||
}
|
||||
|
||||
ApplyColumnWidth();
|
||||
OnPropertyChanged(nameof(HasColumns));
|
||||
OnPropertyChanged(nameof(HasNoColumns));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recomputes the global column width and pushes it to every column.
|
||||
/// </summary>
|
||||
public void ApplyColumnWidth() {
|
||||
ColumnWidth = ColumnWidthPixels(_services.Config.Display.ColumnWidth);
|
||||
foreach (ColumnViewModel column in Columns) {
|
||||
column.Width = ColumnWidth;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves a column width setting to its pixel value.
|
||||
/// </summary>
|
||||
/// <param name="settings">The configured column width.</param>
|
||||
/// <returns>The width in pixels.</returns>
|
||||
public static double ColumnWidthPixels(ColumnWidthSettings settings) => settings.Preset switch {
|
||||
ColumnWidthPreset.Narrow => 240,
|
||||
ColumnWidthPreset.Wide => 480,
|
||||
ColumnWidthPreset.Custom => settings.CustomPixels,
|
||||
_ => 320,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Orders cards by the selected option, tie-breaking by id ascending.
|
||||
/// </summary>
|
||||
/// <param name="cards">The cards to order.</param>
|
||||
/// <param name="option">The selected order.</param>
|
||||
/// <returns>The ordered cards.</returns>
|
||||
private static IEnumerable<CardModel> SortCards(IEnumerable<CardModel> cards, SortOption option) => option switch {
|
||||
SortOption.IdAscending => cards.OrderBy(card => card.Id),
|
||||
SortOption.IdDescending => cards.OrderByDescending(card => card.Id),
|
||||
SortOption.CreatedAscending => cards.OrderBy(card => card.CreatedAt).ThenBy(card => card.Id),
|
||||
SortOption.CreatedDescending => cards.OrderByDescending(card => card.CreatedAt).ThenBy(card => card.Id),
|
||||
SortOption.UpdatedAscending => cards.OrderBy(card => card.UpdatedAt).ThenBy(card => card.Id),
|
||||
SortOption.UpdatedDescending => cards.OrderByDescending(card => card.UpdatedAt).ThenBy(card => card.Id),
|
||||
SortOption.TitleAscending => cards.OrderBy(card => card.Title, StringComparer.Ordinal).ThenBy(card => card.Id),
|
||||
SortOption.TitleDescending => cards.OrderByDescending(card => card.Title, StringComparer.Ordinal).ThenBy(card => card.Id),
|
||||
_ => cards.OrderBy(card => card.Id),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Orders columns by the selected option, tie-breaking by id ascending.
|
||||
/// </summary>
|
||||
/// <param name="columns">The columns to order.</param>
|
||||
/// <param name="option">The selected order.</param>
|
||||
/// <returns>The ordered columns.</returns>
|
||||
private static IEnumerable<ColumnModel> SortColumns(IEnumerable<ColumnModel> columns, SortOption option) => option switch {
|
||||
SortOption.IdAscending => columns.OrderBy(column => column.Id),
|
||||
SortOption.IdDescending => columns.OrderByDescending(column => column.Id),
|
||||
SortOption.CreatedAscending => columns.OrderBy(column => column.CreatedAt).ThenBy(column => column.Id),
|
||||
SortOption.CreatedDescending => columns.OrderByDescending(column => column.CreatedAt).ThenBy(column => column.Id),
|
||||
SortOption.UpdatedAscending => columns.OrderBy(column => column.UpdatedAt).ThenBy(column => column.Id),
|
||||
SortOption.UpdatedDescending => columns.OrderByDescending(column => column.UpdatedAt).ThenBy(column => column.Id),
|
||||
SortOption.TitleAscending => columns.OrderBy(column => column.Title, StringComparer.Ordinal).ThenBy(column => column.Id),
|
||||
SortOption.TitleDescending => columns.OrderByDescending(column => column.Title, StringComparer.Ordinal).ThenBy(column => column.Id),
|
||||
_ => columns.OrderBy(column => column.Id),
|
||||
};
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// One card on the board. Clicking the card body opens the editor; the corner
|
||||
/// menu offers delete and move. The shown text is the "#id title" heading, a
|
||||
/// truncated content preview and the colored tag badges; timestamps are not
|
||||
/// shown on the board.
|
||||
/// </summary>
|
||||
public sealed partial class CardViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Maximum number of content characters shown in the card preview.
|
||||
/// </summary>
|
||||
private const int PreviewLength = 200;
|
||||
|
||||
/// <summary>
|
||||
/// Maximum number of explicit content lines shown in the card preview.
|
||||
/// </summary>
|
||||
private const int PreviewMaxLines = 10;
|
||||
|
||||
private readonly BoardViewModel _board;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the card view from its model.
|
||||
/// </summary>
|
||||
/// <param name="board">The owning board view model.</param>
|
||||
/// <param name="card">The card model to display.</param>
|
||||
public CardViewModel(BoardViewModel board, CardModel card) {
|
||||
_board = board;
|
||||
Model = card;
|
||||
TagBadges = card.Tags.Select(tag => new TagBadgeViewModel(tag)).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the underlying card model.
|
||||
/// </summary>
|
||||
public CardModel Model { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the card id.
|
||||
/// </summary>
|
||||
public long Id => Model.Id;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the owning column id.
|
||||
/// </summary>
|
||||
public long ColumnId => Model.ColumnId;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tag badges shown under the content.
|
||||
/// </summary>
|
||||
public IReadOnlyList<TagBadgeViewModel> TagBadges { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the bold id marker, for example "#61".
|
||||
/// </summary>
|
||||
public string IdText => $"#{Model.Id}";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the card title, empty when the card has no title.
|
||||
/// </summary>
|
||||
public string TitleText => Model.Title;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the card has a title to show.
|
||||
/// </summary>
|
||||
public bool HasTitle => Model.Title.Length > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the card has content to preview.
|
||||
/// </summary>
|
||||
public bool HasContent => Model.Content.Length > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the content preview, truncated to at most 200 characters and
|
||||
/// 10 explicit lines, with an ellipsis when anything was cut.
|
||||
/// </summary>
|
||||
// YYC MARK: the preview is truncated here instead of in the view because
|
||||
// both a character cap and an explicit-line cap are needed, and because
|
||||
// Avalonia 11.3.x renders no ellipsis when MaxLines clips wrapped text
|
||||
// (fixed upstream in 12.1.2, PR #22017, never backported). Revisit after
|
||||
// upgrading Avalonia.
|
||||
public string PreviewContent {
|
||||
get {
|
||||
string content = Model.Content;
|
||||
|
||||
// Cut at whichever boundary comes first: 200 characters or the 10th line break.
|
||||
int limit = content.Length;
|
||||
int breaks = 0;
|
||||
for (int i = 0; i < content.Length; i++) {
|
||||
if (i == PreviewLength || (content[i] == '\n' && ++breaks == PreviewMaxLines)) {
|
||||
limit = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return limit < content.Length ? content[..limit] + "…" : content;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the card has any tags.
|
||||
/// </summary>
|
||||
public bool HasTags => TagBadges.Count > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Opens the card editor.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Edit() => _ = _board.RequestEditCardAsync(this);
|
||||
|
||||
/// <summary>
|
||||
/// Asks the board to delete this card.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Delete() => _ = _board.RequestDeleteCardAsync(this);
|
||||
|
||||
/// <summary>
|
||||
/// Asks the board to move this card to another column.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Move() => _ = _board.RequestMoveCardAsync(this);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// One board column: a header with its title, card count and actions, plus the
|
||||
/// vertically stacked cards.
|
||||
/// </summary>
|
||||
public sealed partial class ColumnViewModel : ViewModelBase {
|
||||
private readonly BoardViewModel _board;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the column view from its model and cards.
|
||||
/// </summary>
|
||||
/// <param name="board">The owning board view model.</param>
|
||||
/// <param name="column">The column model.</param>
|
||||
/// <param name="cards">The already sorted cards belonging to this column.</param>
|
||||
public ColumnViewModel(BoardViewModel board, ColumnModel column, IEnumerable<CardViewModel> cards) {
|
||||
_board = board;
|
||||
Model = column;
|
||||
Cards = new ObservableCollection<CardViewModel>(cards);
|
||||
width = board.ColumnWidth;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the underlying column model.
|
||||
/// </summary>
|
||||
public ColumnModel Model { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the column id.
|
||||
/// </summary>
|
||||
public long Id => Model.Id;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the column title.
|
||||
/// </summary>
|
||||
public string Title => Model.Title;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the column description.
|
||||
/// </summary>
|
||||
public string Description => Model.Description;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the cards in this column, already in display order.
|
||||
/// </summary>
|
||||
public ObservableCollection<CardViewModel> Cards { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of cards in this column.
|
||||
/// </summary>
|
||||
public int CardCount => Cards.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tooltip text: the column description when present, otherwise
|
||||
/// <see langword="null"/> so no tooltip is shown.
|
||||
/// </summary>
|
||||
public string? ToolTipText => Model.Description.Length > 0 ? Model.Description : null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the rendered column width in pixels, applied globally.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double width;
|
||||
|
||||
/// <summary>
|
||||
/// Opens the editor for a new card in this column.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void AddCard() => _ = _board.RequestAddCardAsync(this);
|
||||
|
||||
/// <summary>
|
||||
/// Opens the editor for this column.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Edit() => _ = _board.RequestEditColumnAsync(this);
|
||||
|
||||
/// <summary>
|
||||
/// Asks the board to delete this column.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Delete() => _ = _board.RequestDeleteColumnAsync(this);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
using YKanBan.Storage.AppData;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// The board display options shown in the Display flyout: the global column
|
||||
/// width and the separate card and column orderings. Every change writes to
|
||||
/// the configuration and asks the board to refresh immediately.
|
||||
/// </summary>
|
||||
public sealed partial class DisplaySettingsViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Smallest accepted manual width.
|
||||
/// </summary>
|
||||
public const int MinimumPixels = 160;
|
||||
|
||||
/// <summary>
|
||||
/// Largest accepted manual width.
|
||||
/// </summary>
|
||||
public const int MaximumPixels = 720;
|
||||
|
||||
private readonly AppConfig _config;
|
||||
private readonly Action _refresh;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the display options from the configuration.
|
||||
/// </summary>
|
||||
/// <param name="config">The live application configuration.</param>
|
||||
/// <param name="refresh">Invoked after every change to refresh the board.</param>
|
||||
public DisplaySettingsViewModel(AppConfig config, Action refresh) {
|
||||
_config = config;
|
||||
_refresh = refresh;
|
||||
|
||||
Presets =
|
||||
[
|
||||
new OptionItem(ColumnWidthPreset.Narrow, Resources.WidthPreset_Narrow),
|
||||
new OptionItem(ColumnWidthPreset.Standard, Resources.WidthPreset_Standard),
|
||||
new OptionItem(ColumnWidthPreset.Wide, Resources.WidthPreset_Wide),
|
||||
new OptionItem(ColumnWidthPreset.Custom, Resources.WidthPreset_Custom),
|
||||
];
|
||||
SortOptions = BuildSortOptions();
|
||||
|
||||
selectedPreset = Presets.FirstOrDefault(option => (ColumnWidthPreset)option.Value == config.Display.ColumnWidth.Preset)
|
||||
?? Presets[1];
|
||||
customPixels = config.Display.ColumnWidth.CustomPixels;
|
||||
selectedCardSort = FindSort(SortOptions, config.Display.CardSort);
|
||||
selectedColumnSort = FindSort(SortOptions, config.Display.ColumnSort);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the width preset choices.
|
||||
/// </summary>
|
||||
public IReadOnlyList<OptionItem> Presets { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ordering choices (shared by cards and columns).
|
||||
/// </summary>
|
||||
public IReadOnlyList<OptionItem> SortOptions { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the selected width preset.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private OptionItem? selectedPreset;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the manual pixel width used by the custom preset.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private decimal? customPixels;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the selected card order.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private OptionItem? selectedCardSort;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the selected column order.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private OptionItem? selectedColumnSort;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the custom preset is selected.
|
||||
/// </summary>
|
||||
public bool IsCustom => SelectedPreset is not null && (ColumnWidthPreset)SelectedPreset.Value == ColumnWidthPreset.Custom;
|
||||
|
||||
/// <summary>
|
||||
/// Stores the width preset and refreshes the board.
|
||||
/// </summary>
|
||||
/// <param name="value">The new selection.</param>
|
||||
partial void OnSelectedPresetChanged(OptionItem? value) {
|
||||
OnPropertyChanged(nameof(IsCustom));
|
||||
if (value is not null) {
|
||||
_config.Display.ColumnWidth.Preset = (ColumnWidthPreset)value.Value;
|
||||
_refresh();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the manual width and refreshes the board when the custom preset is active.
|
||||
/// </summary>
|
||||
/// <param name="value">The new pixel count.</param>
|
||||
partial void OnCustomPixelsChanged(decimal? value) {
|
||||
if (value is null) {
|
||||
return;
|
||||
}
|
||||
|
||||
int pixels = (int)value.Value;
|
||||
_config.Display.ColumnWidth.CustomPixels = pixels;
|
||||
if (IsCustom) {
|
||||
_refresh();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the card order and refreshes the board.
|
||||
/// </summary>
|
||||
/// <param name="value">The new selection.</param>
|
||||
partial void OnSelectedCardSortChanged(OptionItem? value) {
|
||||
if (value is not null) {
|
||||
_config.Display.CardSort = (SortOption)value.Value;
|
||||
_refresh();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the column order and refreshes the board.
|
||||
/// </summary>
|
||||
/// <param name="value">The new selection.</param>
|
||||
partial void OnSelectedColumnSortChanged(OptionItem? value) {
|
||||
if (value is not null) {
|
||||
_config.Display.ColumnSort = (SortOption)value.Value;
|
||||
_refresh();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the localized eight-way ordering option list.
|
||||
/// </summary>
|
||||
/// <returns>The ordering options.</returns>
|
||||
private static IReadOnlyList<OptionItem> BuildSortOptions() =>
|
||||
[
|
||||
new OptionItem(SortOption.IdAscending, Resources.Sort_IdAsc),
|
||||
new OptionItem(SortOption.IdDescending, Resources.Sort_IdDesc),
|
||||
new OptionItem(SortOption.CreatedAscending, Resources.Sort_CreatedAsc),
|
||||
new OptionItem(SortOption.CreatedDescending, Resources.Sort_CreatedDesc),
|
||||
new OptionItem(SortOption.UpdatedAscending, Resources.Sort_UpdatedAsc),
|
||||
new OptionItem(SortOption.UpdatedDescending, Resources.Sort_UpdatedDesc),
|
||||
new OptionItem(SortOption.TitleAscending, Resources.Sort_TitleAsc),
|
||||
new OptionItem(SortOption.TitleDescending, Resources.Sort_TitleDesc),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Finds the option matching a stored sort value.
|
||||
/// </summary>
|
||||
/// <param name="options">The option list.</param>
|
||||
/// <param name="value">The stored value.</param>
|
||||
/// <returns>The matching option, or the first option.</returns>
|
||||
private static OptionItem FindSort(IReadOnlyList<OptionItem> options, SortOption value) =>
|
||||
options.FirstOrDefault(option => (SortOption)option.Value == value) ?? options[0];
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Avalonia.Media;
|
||||
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// A read-only colored tag badge shown on a card: the tag name over a
|
||||
/// background taken directly from the tag color (user data, never themed) and
|
||||
/// an automatically contrasting text color.
|
||||
/// </summary>
|
||||
public sealed class TagBadgeViewModel {
|
||||
/// <summary>
|
||||
/// Initializes a badge from a tag.
|
||||
/// </summary>
|
||||
/// <param name="tag">The tag to render.</param>
|
||||
public TagBadgeViewModel(TagModel tag) {
|
||||
Tag = tag;
|
||||
Name = tag.Name;
|
||||
Color background = Color.FromRgb(tag.Color.R, tag.Color.G, tag.Color.B);
|
||||
Background = new SolidColorBrush(background);
|
||||
Foreground = new SolidColorBrush(ContrastingTextColor(background));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the underlying tag model.
|
||||
/// </summary>
|
||||
public TagModel Tag { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tag name.
|
||||
/// </summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tooltip text: the tag description when present, otherwise
|
||||
/// <see langword="null"/> so no tooltip is shown.
|
||||
/// </summary>
|
||||
public string? ToolTipText => Tag.Description.Length > 0 ? Tag.Description : null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the badge background brush.
|
||||
/// </summary>
|
||||
public IBrush Background { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the badge text brush.
|
||||
/// </summary>
|
||||
public IBrush Foreground { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Picks black or white text for readability against the given background.
|
||||
/// </summary>
|
||||
/// <param name="background">The badge background color.</param>
|
||||
/// <returns>The contrasting text color.</returns>
|
||||
private static Color ContrastingTextColor(Color background) {
|
||||
double luminance = (0.299 * background.R + 0.587 * background.G + 0.114 * background.B) / 255.0;
|
||||
return luminance > 0.6 ? Colors.Black : Colors.White;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The about dialog: application name, version, repository link and license.
|
||||
/// </summary>
|
||||
public sealed class AboutDialogViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Initializes the view model, reading the version from the assembly.
|
||||
/// </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>
|
||||
/// Gets the application name.
|
||||
/// </summary>
|
||||
public string AppName => Resources.App_Name;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized version line.
|
||||
/// </summary>
|
||||
public string Version { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the repository URL.
|
||||
/// </summary>
|
||||
public string RepositoryUrl => "https://github.com/yyc12345/YKanBan";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the license name.
|
||||
/// </summary>
|
||||
public string License => Resources.About_LicenseValue;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using Avalonia.Media;
|
||||
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.ViewModels.Board;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// One tag assigned to the card being edited, shown with a colored badge and a
|
||||
/// remove action that only changes the in-memory assignment (the actual write
|
||||
/// happens on confirm).
|
||||
/// </summary>
|
||||
public sealed partial class AssignedTagViewModel {
|
||||
private readonly CardEditorViewModel _editor;
|
||||
private readonly TagBadgeViewModel _badge;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the assigned-tag row.
|
||||
/// </summary>
|
||||
/// <param name="editor">The owning card editor.</param>
|
||||
/// <param name="tag">The assigned tag.</param>
|
||||
public AssignedTagViewModel(CardEditorViewModel editor, TagModel tag) {
|
||||
_editor = editor;
|
||||
Tag = tag;
|
||||
_badge = new TagBadgeViewModel(tag);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the assigned tag model.
|
||||
/// </summary>
|
||||
public TagModel Tag { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tag name.
|
||||
/// </summary>
|
||||
public string Name => _badge.Name;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the badge background brush.
|
||||
/// </summary>
|
||||
public IBrush Background => _badge.Background;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the badge text brush.
|
||||
/// </summary>
|
||||
public IBrush Foreground => _badge.Foreground;
|
||||
|
||||
/// <summary>
|
||||
/// Removes this tag from the in-memory assignment.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Remove() => _editor.RemoveTag(Tag);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The add/edit card dialog: title, content and the assigned-tag area, plus
|
||||
/// read-only id and timestamps for an existing card. The confirm writes the
|
||||
/// card and its tag assignment as one unit; a confirm with no effective change
|
||||
/// writes nothing; cancelling never writes.
|
||||
/// </summary>
|
||||
public sealed partial class CardEditorViewModel : ViewModelBase {
|
||||
private readonly WorkspaceRepository _repository;
|
||||
private readonly long _columnId;
|
||||
private readonly CardModel? _existing;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the dialog for a new or existing card.
|
||||
/// </summary>
|
||||
/// <param name="repository">The workspace repository.</param>
|
||||
/// <param name="columnId">The owning column (used when adding).</param>
|
||||
/// <param name="existing">The card to edit, or <see langword="null"/> to add one.</param>
|
||||
public CardEditorViewModel(WorkspaceRepository repository, long columnId, CardModel? existing) {
|
||||
_repository = repository;
|
||||
_columnId = columnId;
|
||||
_existing = existing;
|
||||
title = existing?.Title ?? string.Empty;
|
||||
content = existing?.Content ?? string.Empty;
|
||||
AssignedTags = new ObservableCollection<AssignedTagViewModel>(
|
||||
(existing?.Tags ?? []).Select(tag => new AssignedTagViewModel(this, tag)));
|
||||
|
||||
if (existing is not null) {
|
||||
IdLine = string.Format(Culture, Resources.CardDialog_Id, $"#{existing.Id}");
|
||||
CreatedLine = string.Format(Culture, Resources.CardDialog_Created, FormatTime(existing.CreatedAt));
|
||||
ModifiedLine = string.Format(Culture, Resources.CardDialog_Modified, FormatTime(existing.UpdatedAt));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that opens the nested tag picker.
|
||||
/// </summary>
|
||||
public Interaction<Unit, TagModel?> ShowTagPicker { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the workspace repository (used by the tag picker).
|
||||
/// </summary>
|
||||
public WorkspaceRepository Repository => _repository;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this dialog creates a new card.
|
||||
/// </summary>
|
||||
public bool IsNew => _existing is null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized window title.
|
||||
/// </summary>
|
||||
public string WindowTitle => IsNew ? Resources.CardDialog_AddTitle : Resources.CardDialog_EditTitle;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the read-only id line, empty for a new card.
|
||||
/// </summary>
|
||||
public string IdLine { get; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the read-only created line, empty for a new card.
|
||||
/// </summary>
|
||||
public string CreatedLine { get; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the read-only modified line, empty for a new card.
|
||||
/// </summary>
|
||||
public string ModifiedLine { get; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tags currently assigned to the card (in memory until confirmed).
|
||||
/// </summary>
|
||||
public ObservableCollection<AssignedTagViewModel> AssignedTags { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the card title.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string title;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the card content.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string content;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the inline error shown when the write fails.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string? errorMessage;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether there are unsaved effective changes.
|
||||
/// </summary>
|
||||
public bool HasChanges {
|
||||
get {
|
||||
if (_existing is null) {
|
||||
return Title.Length > 0 || Content.Length > 0 || AssignedTags.Count > 0;
|
||||
}
|
||||
|
||||
bool tagsChanged = !AssignedTags.Select(row => row.Tag.Id).ToHashSet()
|
||||
.SetEquals(_existing.Tags.Select(tag => tag.Id));
|
||||
return _existing.Title != Title || _existing.Content != Content || tagsChanged;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the nested tag picker and adds the chosen tag when it is new to the card.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task AddTagAsync() {
|
||||
TagModel? tag = await ShowTagPicker.Handle(Unit.Value);
|
||||
if (tag is not null && AssignedTags.All(row => row.Tag.Id != tag.Id)) {
|
||||
AssignedTags.Add(new AssignedTagViewModel(this, tag));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a tag from the in-memory assignment.
|
||||
/// </summary>
|
||||
/// <param name="tag">The tag to remove.</param>
|
||||
public void RemoveTag(TagModel tag) {
|
||||
AssignedTagViewModel? row = AssignedTags.FirstOrDefault(item => item.Tag.Id == tag.Id);
|
||||
if (row is not null) {
|
||||
AssignedTags.Remove(row);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the card and its tags when there is an effective change.
|
||||
/// </summary>
|
||||
/// <returns><see langword="true"/> when the dialog may close.</returns>
|
||||
public bool TryAccept() {
|
||||
ErrorMessage = null;
|
||||
|
||||
// A confirm with no effective change writes nothing and just closes.
|
||||
if (!HasChanges) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
IReadOnlyCollection<long> tagIds = AssignedTags.Select(row => row.Tag.Id).ToList();
|
||||
if (_existing is null) {
|
||||
_repository.AddCard(_columnId, Title, Content, tagIds);
|
||||
} else {
|
||||
_repository.UpdateCard(_existing.Id, Title, Content, tagIds);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (SqliteException) {
|
||||
ErrorMessage = Resources.CardDialog_Error;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the culture used for formatted read-only lines.
|
||||
/// </summary>
|
||||
private static CultureInfo Culture => Resources.Culture ?? CultureInfo.CurrentCulture;
|
||||
|
||||
/// <summary>
|
||||
/// Formats a stored timestamp as a local time using the UI language pattern.
|
||||
/// </summary>
|
||||
/// <param name="unixSeconds">The stored timestamp.</param>
|
||||
/// <returns>The formatted local time.</returns>
|
||||
private static string FormatTime(long unixSeconds) =>
|
||||
DateTimeOffset.FromUnixTimeSeconds(unixSeconds).ToLocalTime().ToString(Resources.CardDialog_TimePattern, Culture);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The add/edit column dialog: a required title and an optional description.
|
||||
/// The write happens when the dialog is accepted; a duplicate or empty title
|
||||
/// keeps the dialog open with an inline error.
|
||||
/// </summary>
|
||||
public sealed partial class ColumnEditorViewModel : ViewModelBase {
|
||||
private readonly WorkspaceRepository _repository;
|
||||
private readonly ColumnModel? _existing;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the dialog for a new or existing column.
|
||||
/// </summary>
|
||||
/// <param name="repository">The workspace repository.</param>
|
||||
/// <param name="existing">The column to edit, or <see langword="null"/> to add one.</param>
|
||||
public ColumnEditorViewModel(WorkspaceRepository repository, ColumnModel? existing) {
|
||||
_repository = repository;
|
||||
_existing = existing;
|
||||
title = existing?.Title ?? string.Empty;
|
||||
description = existing?.Description ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this dialog creates a new column.
|
||||
/// </summary>
|
||||
public bool IsNew => _existing is null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized window title.
|
||||
/// </summary>
|
||||
public string WindowTitle => IsNew ? Resources.ColumnDialog_AddTitle : Resources.ColumnDialog_EditTitle;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the column title.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string title;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the column description.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string description;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the inline error shown when the title is rejected.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string? errorMessage;
|
||||
|
||||
/// <summary>
|
||||
/// Writes the column when accepted.
|
||||
/// </summary>
|
||||
/// <returns><see langword="true"/> when the dialog may close.</returns>
|
||||
public bool TryAccept() {
|
||||
ErrorMessage = null;
|
||||
try {
|
||||
if (_existing is null) {
|
||||
_repository.AddColumn(Title, Description);
|
||||
} else {
|
||||
_repository.UpdateColumn(_existing.Id, Title, Description);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (SqliteException) {
|
||||
ErrorMessage = Resources.ColumnDialog_InvalidTitle;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The confirmation shown before deleting a card, naming the card id.
|
||||
/// </summary>
|
||||
public sealed class DeleteCardConfirmViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Initializes the confirmation.
|
||||
/// </summary>
|
||||
/// <param name="cardId">The id of the card to delete.</param>
|
||||
public DeleteCardConfirmViewModel(long cardId) {
|
||||
Message = string.Format(
|
||||
Resources.Culture ?? CultureInfo.CurrentCulture,
|
||||
Resources.Confirm_DeleteCard_Message,
|
||||
cardId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized confirmation message.
|
||||
/// </summary>
|
||||
public string Message { get; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The confirmation shown before deleting a column, naming the column and how
|
||||
/// many cards it will cascade-delete.
|
||||
/// </summary>
|
||||
public sealed class DeleteColumnConfirmViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Initializes the confirmation.
|
||||
/// </summary>
|
||||
/// <param name="columnTitle">The title of the column to delete.</param>
|
||||
/// <param name="cardCount">The number of cards in the column.</param>
|
||||
public DeleteColumnConfirmViewModel(string columnTitle, int cardCount) {
|
||||
Message = string.Format(
|
||||
Resources.Culture ?? CultureInfo.CurrentCulture,
|
||||
Resources.Confirm_DeleteColumn_Message,
|
||||
columnTitle,
|
||||
cardCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized confirmation message.
|
||||
/// </summary>
|
||||
public string Message { get; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The confirmation shown before deleting a tag, naming the tag and how many
|
||||
/// cards it will be removed from.
|
||||
/// </summary>
|
||||
public sealed class DeleteTagConfirmViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Initializes the confirmation.
|
||||
/// </summary>
|
||||
/// <param name="tagName">The name of the tag to delete.</param>
|
||||
/// <param name="usageCount">The number of cards using the tag.</param>
|
||||
public DeleteTagConfirmViewModel(string tagName, long usageCount) {
|
||||
Message = string.Format(
|
||||
Resources.Culture ?? CultureInfo.CurrentCulture,
|
||||
Resources.DeleteTag_Confirm_Message,
|
||||
tagName,
|
||||
usageCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized confirmation message.
|
||||
/// </summary>
|
||||
public string Message { get; }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The confirmation shown before closing an editor with unsaved changes.
|
||||
/// </summary>
|
||||
public sealed class DiscardEditConfirmViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Gets the localized confirmation message.
|
||||
/// </summary>
|
||||
public string Message => Resources.Confirm_Discard_Message;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The confirmation dialog shown after a successful Markdown export, naming the
|
||||
/// written file.
|
||||
/// </summary>
|
||||
public sealed class ExportDoneViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Initializes the dialog with the exported file path.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The path the export was written to.</param>
|
||||
public ExportDoneViewModel(string filePath) {
|
||||
Message = string.Format(
|
||||
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Export_Done_Message, filePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized confirmation message.
|
||||
/// </summary>
|
||||
public string Message { get; }
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The move-card dialog: choose one of the other columns as the destination.
|
||||
/// </summary>
|
||||
public sealed partial class MoveCardViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Initializes the dialog with the candidate destination columns.
|
||||
/// </summary>
|
||||
/// <param name="columns">All columns; the card's current column is excluded.</param>
|
||||
/// <param name="currentColumnId">The card's current column id.</param>
|
||||
public MoveCardViewModel(IReadOnlyList<ColumnModel> columns, long currentColumnId) {
|
||||
Targets = columns
|
||||
.Where(column => column.Id != currentColumnId)
|
||||
.Select(column => new OptionItem(column.Id, column.Title))
|
||||
.ToList();
|
||||
selectedTarget = Targets.FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the candidate destination columns.
|
||||
/// </summary>
|
||||
public IReadOnlyList<OptionItem> Targets { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the selected destination column.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private OptionItem? selectedTarget;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether there is anywhere to move the card.
|
||||
/// </summary>
|
||||
public bool CanMove => Targets.Count > 0;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The pure-information dialog shown when the search expression is invalid. It
|
||||
/// wraps the parser's non-localized English detail in the localized message.
|
||||
/// </summary>
|
||||
public sealed class SearchErrorViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Initializes the dialog with the parser's English detail.
|
||||
/// </summary>
|
||||
/// <param name="detail">The non-localized parser error description.</param>
|
||||
public SearchErrorViewModel(string detail) {
|
||||
Message = string.Format(
|
||||
Resources.Culture ?? CultureInfo.CurrentCulture,
|
||||
Resources.Search_Error_Message,
|
||||
detail);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized error message.
|
||||
/// </summary>
|
||||
public string Message { get; }
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using System.Globalization;
|
||||
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
using YKanBan.Storage.AppData;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The settings dialog: language (restart to apply), theme and the four
|
||||
/// confirmation-dialog toggles. Nothing is applied until the user accepts;
|
||||
/// cancelling or closing the window discards the changes.
|
||||
/// </summary>
|
||||
public sealed partial class SettingsDialogViewModel : ViewModelBase {
|
||||
private readonly AppConfig _config;
|
||||
private readonly string _startupLanguage;
|
||||
|
||||
/// <summary>
|
||||
/// 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;
|
||||
_startupLanguage = startupLanguage;
|
||||
|
||||
Languages =
|
||||
[
|
||||
LanguageOption(AppConfig.DefaultLanguage),
|
||||
LanguageOption("zh-Hans"),
|
||||
LanguageOption("ja"),
|
||||
];
|
||||
selectedLanguage = Languages.FirstOrDefault(option => (string)option.Value == _config.Language)
|
||||
?? Languages[0];
|
||||
|
||||
Themes =
|
||||
[
|
||||
new OptionItem(ThemeOption.Light, Resources.Settings_ThemeLight),
|
||||
new OptionItem(ThemeOption.Dark, Resources.Settings_ThemeDark),
|
||||
new OptionItem(ThemeOption.FollowSystem, Resources.Settings_ThemeFollowSystem),
|
||||
];
|
||||
selectedTheme = Themes.FirstOrDefault(option => option.Value.Equals(_config.Theme)) ?? Themes[^1];
|
||||
|
||||
confirmDeleteCard = _config.Confirmations.DeleteCard;
|
||||
confirmDeleteColumn = _config.Confirmations.DeleteColumn;
|
||||
confirmDeleteTag = _config.Confirmations.DeleteTag;
|
||||
confirmDiscardEdit = _config.Confirmations.DiscardEdit;
|
||||
RefreshRestartNotice();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the available languages.
|
||||
/// </summary>
|
||||
public IReadOnlyList<OptionItem> Languages { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the available themes.
|
||||
/// </summary>
|
||||
public IReadOnlyList<OptionItem> Themes { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the selected language; takes effect after a restart.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private OptionItem? selectedLanguage;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the selected theme; applied when the dialog is accepted.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private OptionItem? selectedTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether deleting a card asks for confirmation.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool confirmDeleteCard;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether deleting a column asks for confirmation.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool confirmDeleteColumn;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether deleting a tag asks for confirmation.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool confirmDeleteTag;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether discarding card edits asks for confirmation.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool confirmDiscardEdit;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the working language differs from the one applied at startup.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool restartNoticeVisible;
|
||||
|
||||
/// <summary>
|
||||
/// Commits the working values into the live configuration.
|
||||
/// </summary>
|
||||
public void Accept() {
|
||||
if (SelectedLanguage is not null) {
|
||||
_config.Language = (string)SelectedLanguage.Value;
|
||||
}
|
||||
if (SelectedTheme is not null) {
|
||||
_config.Theme = (ThemeOption)SelectedTheme.Value;
|
||||
App.ApplyTheme(_config.Theme);
|
||||
}
|
||||
|
||||
_config.Confirmations.DeleteCard = ConfirmDeleteCard;
|
||||
_config.Confirmations.DeleteColumn = ConfirmDeleteColumn;
|
||||
_config.Confirmations.DeleteTag = ConfirmDeleteTag;
|
||||
_config.Confirmations.DiscardEdit = ConfirmDiscardEdit;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes the restart notice after a language selection change.
|
||||
/// </summary>
|
||||
/// <param name="value">The new selection.</param>
|
||||
partial void OnSelectedLanguageChanged(OptionItem? value) => RefreshRestartNotice();
|
||||
|
||||
/// <summary>
|
||||
/// Recomputes whether the restart notice must be shown.
|
||||
/// </summary>
|
||||
private void RefreshRestartNotice() =>
|
||||
RestartNoticeVisible = SelectedLanguage is not null && (string)SelectedLanguage.Value != _startupLanguage;
|
||||
|
||||
/// <summary>
|
||||
/// Builds a language option whose label is the culture's native name, so the
|
||||
/// language designates itself identically under every UI culture.
|
||||
/// </summary>
|
||||
/// <param name="code">The language code stored in app.json.</param>
|
||||
private static OptionItem LanguageOption(string code) => new(code, new CultureInfo(code).NativeName);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using Avalonia.Media;
|
||||
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The add/edit tag dialog: a name, a color chosen with a color picker and an
|
||||
/// optional description. The write happens when the dialog is accepted; a
|
||||
/// duplicate or empty name keeps the dialog open with an inline error.
|
||||
/// </summary>
|
||||
public sealed partial class TagEditorViewModel : ViewModelBase {
|
||||
private readonly WorkspaceRepository _repository;
|
||||
private readonly TagModel? _existing;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the dialog for a new or existing tag.
|
||||
/// </summary>
|
||||
/// <param name="repository">The workspace repository.</param>
|
||||
/// <param name="existing">The tag to edit, or <see langword="null"/> to add one.</param>
|
||||
public TagEditorViewModel(WorkspaceRepository repository, TagModel? existing) {
|
||||
_repository = repository;
|
||||
_existing = existing;
|
||||
name = existing?.Name ?? string.Empty;
|
||||
description = existing?.Description ?? string.Empty;
|
||||
color = existing is not null
|
||||
? Color.FromRgb(existing.Color.R, existing.Color.G, existing.Color.B)
|
||||
: Colors.Gray;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this dialog creates a new tag.
|
||||
/// </summary>
|
||||
public bool IsNew => _existing is null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized window title.
|
||||
/// </summary>
|
||||
public string WindowTitle => IsNew ? Resources.TagEditor_AddTitle : Resources.TagEditor_EditTitle;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tag name.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string name;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tag color.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private Color color;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tag description.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string description;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the inline error shown when the name is rejected.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string? errorMessage;
|
||||
|
||||
/// <summary>
|
||||
/// Writes the tag when accepted.
|
||||
/// </summary>
|
||||
/// <returns><see langword="true"/> when the dialog may close.</returns>
|
||||
public bool TryAccept() {
|
||||
ErrorMessage = null;
|
||||
var rgb = new RgbColor(Color.R, Color.G, Color.B);
|
||||
|
||||
try {
|
||||
if (_existing is null) {
|
||||
_repository.AddTag(Name, rgb, Description);
|
||||
} else {
|
||||
_repository.UpdateTag(_existing.Id, Name, rgb, Description);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (SqliteException) {
|
||||
ErrorMessage = Resources.TagEditor_InvalidName;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.ViewModels.Board;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The nested tag picker opened from the card editor: choose one tag that is
|
||||
/// not already assigned to the card. When no candidate remains the picker
|
||||
/// shows a message and cannot be confirmed.
|
||||
/// </summary>
|
||||
public sealed partial class TagPickerViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Initializes the picker with the tags not yet assigned to the card.
|
||||
/// </summary>
|
||||
/// <param name="repository">The workspace repository.</param>
|
||||
/// <param name="assignedTagIds">The tag ids already assigned to the card.</param>
|
||||
public TagPickerViewModel(WorkspaceRepository repository, IReadOnlyCollection<long> assignedTagIds) {
|
||||
Targets = repository.GetTags()
|
||||
.Where(tag => !assignedTagIds.Contains(tag.Id))
|
||||
.Select(tag => new TagBadgeViewModel(tag))
|
||||
.ToList();
|
||||
selectedTarget = Targets.FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the assignable tags.
|
||||
/// </summary>
|
||||
public IReadOnlyList<TagBadgeViewModel> Targets { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the selected tag.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private TagBadgeViewModel? selectedTarget;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether there is a tag to add.
|
||||
/// </summary>
|
||||
public bool CanAdd => Targets.Count > 0;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
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 {
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
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; }
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Globalization;
|
||||
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage;
|
||||
|
||||
namespace YKanBan.ViewModels.ErrorPages;
|
||||
|
||||
/// <summary>
|
||||
/// The full-window page shown when a workspace cannot be opened or initialized:
|
||||
/// a schema newer than this build, a missing, unopenable or damaged database, an
|
||||
/// I/O or permission error, or any unrecognized failure. It shows a localized
|
||||
/// message chosen by exception type plus the read-only, copyable English
|
||||
/// exception details, and has no operations.
|
||||
/// </summary>
|
||||
public sealed class OpenFailedPageViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Initializes the page for a failed open or initialization.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder.</param>
|
||||
/// <param name="exception">The failure.</param>
|
||||
public OpenFailedPageViewModel(string folderPath, Exception exception) {
|
||||
FolderPath = folderPath;
|
||||
Message = BuildMessage(folderPath, exception);
|
||||
|
||||
// Exception texts are English: ours by convention, .NET and SQLite ones by design.
|
||||
Details = exception.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the workspace folder.
|
||||
/// </summary>
|
||||
public string FolderPath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized explanatory message.
|
||||
/// </summary>
|
||||
public string Message { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the English exception details for diagnosis.
|
||||
/// </summary>
|
||||
public string Details { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Maps the exception type to its localized message; unrecognized types get the generic one.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder.</param>
|
||||
/// <param name="exception">The failure.</param>
|
||||
/// <returns>The localized message.</returns>
|
||||
public static string BuildMessage(string folderPath, Exception exception) {
|
||||
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentCulture;
|
||||
return exception switch {
|
||||
SchemaVersionException schema => string.Format(
|
||||
culture, Resources.Error_OpenFailed_SchemaTooNew, folderPath, schema.StoredVersion, schema.SupportedVersion),
|
||||
WorkspaceDatabaseMissingException => string.Format(culture, Resources.Error_OpenFailed_DatabaseMissing, folderPath),
|
||||
SqliteException => string.Format(culture, Resources.Error_OpenFailed_Database, folderPath),
|
||||
UnauthorizedAccessException => string.Format(culture, Resources.Error_OpenFailed_AccessDenied, folderPath),
|
||||
IOException => string.Format(culture, Resources.Error_OpenFailed_Io, folderPath),
|
||||
_ => string.Format(culture, Resources.Error_OpenFailed_Generic, folderPath),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
namespace YKanBan.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Input placeholder for interactions that carry no meaningful payload.
|
||||
/// </summary>
|
||||
public readonly record struct Unit {
|
||||
/// <summary>
|
||||
/// Gets the single unit value.
|
||||
/// </summary>
|
||||
public static Unit Value => default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A view-model side request with no result that the owning view fulfils
|
||||
/// through a registered handler (opening a dialog, for example) — the classic
|
||||
/// MVVM interaction 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>
|
||||
/// <typeparam name="TInput">The request payload.</typeparam>
|
||||
/// <typeparam name="TOutput">The handler's answer.</typeparam>
|
||||
public sealed class Interaction<TInput, TOutput> {
|
||||
private Func<TInput, Task<TOutput>>? _handler;
|
||||
|
||||
/// <summary>
|
||||
/// Registers the single handler; the view calls this once.
|
||||
/// </summary>
|
||||
/// <param name="handler">The handler that fulfils the request.</param>
|
||||
public void RegisterHandler(Func<TInput, Task<TOutput>> handler) => _handler = 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>
|
||||
public Task<TOutput> Handle(TInput input) =>
|
||||
_handler is null
|
||||
? throw new InvalidOperationException("No handler registered for this interaction.")
|
||||
: _handler(input);
|
||||
}
|
||||
@@ -1,5 +1,127 @@
|
||||
namespace YKanBan.ViewModels;
|
||||
using System.Diagnostics;
|
||||
|
||||
public partial class MainWindowViewModel : ViewModelBase
|
||||
{
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
using YKanBan.Launching;
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.ViewModels.ErrorPages;
|
||||
|
||||
namespace YKanBan.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// The main window view model. It resolves the launch arguments into either the
|
||||
/// normal workspace view or one of the full-window error pages, and owns the
|
||||
/// interactions that the view fulfils by opening dialogs.
|
||||
/// </summary>
|
||||
public sealed partial class MainWindowViewModel : ViewModelBase {
|
||||
private readonly AppServices _services;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the view model and resolves the workspace state.
|
||||
/// </summary>
|
||||
/// <param name="services">The process composition root.</param>
|
||||
/// <param name="arguments">The command-line arguments (excluding the executable).</param>
|
||||
public MainWindowViewModel(AppServices services, IReadOnlyList<string> arguments) {
|
||||
_services = services;
|
||||
ShowSettings = new Interaction<Unit>();
|
||||
ShowAbout = new Interaction<Unit>();
|
||||
InitializeWorkspace = new Interaction<Unit>();
|
||||
InitializeWorkspace.RegisterHandler(_ => InitializeCurrentWorkspaceAsync());
|
||||
Resolve(arguments);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that opens the settings dialog.
|
||||
/// </summary>
|
||||
public Interaction<Unit> ShowSettings { get; }
|
||||
|
||||
/// <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)) {
|
||||
Content = new ArgumentErrorPageViewModel();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
OpenWorkspace(folderPath);
|
||||
} catch (WorkspaceNotInitializedException) {
|
||||
Content = new NotInitializedPageViewModel(folderPath, InitializeWorkspace);
|
||||
} 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>
|
||||
/// Opens the workspace and switches the content to the normal view.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder to open.</param>
|
||||
private void OpenWorkspace(string folderPath) => OpenWorkspace(folderPath, _services.OpenWorkspace(folderPath));
|
||||
|
||||
/// <summary>
|
||||
/// Switches the content to the normal view of an already opened workspace.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder.</param>
|
||||
/// <param name="session">The opened workspace session.</param>
|
||||
private void OpenWorkspace(string folderPath, WorkspaceSession session) {
|
||||
try {
|
||||
Content = new WorkspaceViewModel(_services, session, ShowSettings, ShowAbout);
|
||||
} catch {
|
||||
// The first board read failed: the caller shows an error page, which holds no workspace.
|
||||
_services.CloseWorkspace();
|
||||
throw;
|
||||
}
|
||||
|
||||
Title = $"{new DirectoryInfo(folderPath).Name} - {Resources.App_Name}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the folder shown by the not-initialized page, adds the preset
|
||||
/// 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) {
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
try {
|
||||
OpenWorkspace(page.FolderPath, _services.InitializeWorkspace(page.FolderPath));
|
||||
} catch (Exception exception) when (exception is YKanBanException or IOException or UnauthorizedAccessException) {
|
||||
// Initialization failed; the page remains so the user can retry.
|
||||
Debug.WriteLine(exception);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace YKanBan.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// A selectable option for combo boxes: a backing value plus its localized
|
||||
/// display label.
|
||||
/// </summary>
|
||||
/// <param name="Value">The backing value (an enum value or a language code).</param>
|
||||
/// <param name="Label">The localized display label.</param>
|
||||
public sealed record OptionItem(object Value, string Label);
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.Globalization;
|
||||
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.ViewModels.Board;
|
||||
|
||||
namespace YKanBan.ViewModels.Tags;
|
||||
|
||||
/// <summary>
|
||||
/// One row of the tag manager: a color swatch, the name, the description and the
|
||||
/// usage count, plus edit and delete actions.
|
||||
/// </summary>
|
||||
public sealed partial class TagItemViewModel {
|
||||
private readonly TagsViewModel _owner;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the row.
|
||||
/// </summary>
|
||||
/// <param name="owner">The owning tag manager.</param>
|
||||
/// <param name="tag">The tag model.</param>
|
||||
/// <param name="usageCount">The number of cards using the tag.</param>
|
||||
public TagItemViewModel(TagsViewModel owner, TagModel tag, long usageCount) {
|
||||
_owner = owner;
|
||||
Tag = tag;
|
||||
Badge = new TagBadgeViewModel(tag);
|
||||
UsageCount = usageCount;
|
||||
UsageText = string.Format(
|
||||
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Tags_Usage, usageCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the underlying tag model.
|
||||
/// </summary>
|
||||
public TagModel Tag { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the colored badge for the swatch and name.
|
||||
/// </summary>
|
||||
public TagBadgeViewModel Badge { 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 a value indicating whether the tag has a description.
|
||||
/// </summary>
|
||||
public bool HasDescription => Tag.Description.Length > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of cards using the tag.
|
||||
/// </summary>
|
||||
public long UsageCount { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized usage count.
|
||||
/// </summary>
|
||||
public string UsageText { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Asks the manager to edit this tag.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Edit() => _ = _owner.RequestEditAsync(this);
|
||||
|
||||
/// <summary>
|
||||
/// Asks the manager to delete this tag.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Delete() => _ = _owner.RequestDeleteAsync(this);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
namespace YKanBan.ViewModels.Tags;
|
||||
|
||||
/// <summary>
|
||||
/// The tags tab: a manager for the workspace's tags (create, rename, recolor,
|
||||
/// re-describe and delete), showing each tag's color, name, description and
|
||||
/// usage count. Tag changes also refresh the board.
|
||||
/// </summary>
|
||||
public sealed partial class TagsViewModel : ViewModelBase {
|
||||
private readonly WorkspaceRepository _repository;
|
||||
private readonly Action _boardChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the manager, loading the current tags.
|
||||
/// </summary>
|
||||
/// <param name="repository">The workspace repository.</param>
|
||||
/// <param name="boardChanged">Invoked after a tag change so the board refreshes.</param>
|
||||
public TagsViewModel(WorkspaceRepository repository, Action boardChanged) {
|
||||
_repository = repository;
|
||||
_boardChanged = boardChanged;
|
||||
Reload();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the workspace repository used for tag access.
|
||||
/// </summary>
|
||||
public WorkspaceRepository Repository => _repository;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tags in id order.
|
||||
/// </summary>
|
||||
public ObservableCollection<TagItemViewModel> Tags { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the workspace has any tags.
|
||||
/// </summary>
|
||||
public bool HasTags => Tags.Count > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the workspace has no tags.
|
||||
/// </summary>
|
||||
public bool HasNoTags => Tags.Count == 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized total number of tags shown next to the add button.
|
||||
/// </summary>
|
||||
public string TagCountText => string.Format(
|
||||
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Tags_Count, Tags.Count);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that opens the new-tag editor.
|
||||
/// </summary>
|
||||
public Interaction<Unit> AddTag { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that opens the tag editor.
|
||||
/// </summary>
|
||||
public Interaction<TagItemViewModel> EditTag { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that confirms and deletes a tag.
|
||||
/// </summary>
|
||||
public Interaction<TagItemViewModel> DeleteTag { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Opens the new-tag editor.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private Task AddNewTagAsync() => AddTag.Handle(Unit.Value);
|
||||
|
||||
/// <summary>
|
||||
/// Requests the editor for a tag.
|
||||
/// </summary>
|
||||
/// <param name="item">The tag to edit.</param>
|
||||
/// <returns>A task completing after the editor closes.</returns>
|
||||
public Task RequestEditAsync(TagItemViewModel item) => EditTag.Handle(item);
|
||||
|
||||
/// <summary>
|
||||
/// Requests deletion of a tag.
|
||||
/// </summary>
|
||||
/// <param name="item">The tag to delete.</param>
|
||||
/// <returns>A task completing after confirmation.</returns>
|
||||
public Task RequestDeleteAsync(TagItemViewModel item) => DeleteTag.Handle(item);
|
||||
|
||||
/// <summary>
|
||||
/// Reloads the tag list from the repository.
|
||||
/// </summary>
|
||||
public void Reload() {
|
||||
Tags.Clear();
|
||||
foreach ((TagModel tag, long usage) in _repository.GetTagsWithUsage()) {
|
||||
Tags.Add(new TagItemViewModel(this, tag, usage));
|
||||
}
|
||||
|
||||
OnPropertyChanged(nameof(HasTags));
|
||||
OnPropertyChanged(nameof(HasNoTags));
|
||||
OnPropertyChanged(nameof(TagCountText));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reloads the tags and refreshes the board after a tag change.
|
||||
/// </summary>
|
||||
public void RefreshAfterChange() {
|
||||
Reload();
|
||||
_boardChanged();
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,5 @@
|
||||
|
||||
namespace YKanBan.ViewModels;
|
||||
|
||||
public class ViewModelBase : ObservableObject
|
||||
{
|
||||
public class ViewModelBase : ObservableObject {
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.ViewModels.Board;
|
||||
using YKanBan.ViewModels.Tags;
|
||||
|
||||
namespace YKanBan.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// The normal workspace view: the top display area (name, path and the export,
|
||||
/// settings and about buttons) plus the board and tags tabs.
|
||||
/// </summary>
|
||||
public sealed partial class WorkspaceViewModel : ViewModelBase {
|
||||
private readonly Interaction<Unit> _showSettings;
|
||||
private readonly Interaction<Unit> _showAbout;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the view for an open workspace.
|
||||
/// </summary>
|
||||
/// <param name="services">The process composition root.</param>
|
||||
/// <param name="session">The open workspace session.</param>
|
||||
/// <param name="showSettings">The interaction that opens the settings dialog.</param>
|
||||
/// <param name="showAbout">The interaction that opens the about dialog.</param>
|
||||
public WorkspaceViewModel(
|
||||
AppServices services,
|
||||
WorkspaceSession session,
|
||||
Interaction<Unit> showSettings,
|
||||
Interaction<Unit> showAbout) {
|
||||
Session = session;
|
||||
WorkspaceName = new DirectoryInfo(session.FolderPath).Name;
|
||||
WorkspacePath = session.FolderPath;
|
||||
_showSettings = showSettings;
|
||||
_showAbout = showAbout;
|
||||
|
||||
// Both tabs share the same repository; tag changes refresh the board.
|
||||
Board = new BoardViewModel(services, session);
|
||||
Tags = new TagsViewModel(session.Repository, Board.Reload);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the open workspace session (lock plus repository).
|
||||
/// </summary>
|
||||
public WorkspaceSession Session { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the workspace display name (the folder name).
|
||||
/// </summary>
|
||||
public string WorkspaceName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the full workspace folder path.
|
||||
/// </summary>
|
||||
public string WorkspacePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the board tab view model.
|
||||
/// </summary>
|
||||
public BoardViewModel Board { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tags tab view model.
|
||||
/// </summary>
|
||||
public TagsViewModel Tags { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that runs the export flow.
|
||||
/// </summary>
|
||||
public Interaction<Unit> Export { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Opens the settings dialog through the registered interaction.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task OpenSettingsAsync() => await _showSettings.Handle(Unit.Value);
|
||||
|
||||
/// <summary>
|
||||
/// Opens the about dialog through the registered interaction.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task OpenAboutAsync() => await _showAbout.Handle(Unit.Value);
|
||||
|
||||
/// <summary>
|
||||
/// Runs the export flow through the registered interaction.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task RunExportAsync() => await Export.Handle(Unit.Value);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Board"
|
||||
xmlns:vmBase="using:YKanBan.ViewModels"
|
||||
xmlns:lang="using:YKanBan"
|
||||
xmlns:icons="using:IconPacks.Avalonia.Lucide"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d" d:DesignWidth="1000" d:DesignHeight="600"
|
||||
x:Class="YKanBan.Views.Board.BoardView"
|
||||
x:DataType="vm:BoardViewModel">
|
||||
|
||||
<Grid RowDefinitions="Auto,*">
|
||||
|
||||
<!-- Toolbar: search, add column and the combined display options. -->
|
||||
<Grid Grid.Row="0" Margin="8" ColumnDefinitions="Auto,*,Auto,Auto,Auto,Auto">
|
||||
<!-- Wrapped in a transparent-border hit area so the tooltip triggers across the whole 16x16 box. -->
|
||||
<Border Grid.Column="0" Background="Transparent" Padding="2" Margin="0,0,6,0"
|
||||
VerticalAlignment="Center"
|
||||
ToolTip.Tip="{Binding FilterStatusText}">
|
||||
<icons:PackIconLucide Kind="ListFilter" Width="16" Height="16"
|
||||
Opacity="{Binding FilterIconOpacity}"/>
|
||||
</Border>
|
||||
|
||||
<TextBox Grid.Column="1" Text="{Binding SearchText}" VerticalAlignment="Center"
|
||||
Watermark="{x:Static lang:Resources.Board_SearchPlaceholder}">
|
||||
<TextBox.KeyBindings>
|
||||
<KeyBinding Gesture="Enter" Command="{Binding SearchCommand}"/>
|
||||
</TextBox.KeyBindings>
|
||||
</TextBox>
|
||||
|
||||
<Button Grid.Column="2" Margin="4,0,0,0" Command="{Binding ClearSearchCommand}"
|
||||
ToolTip.Tip="{x:Static lang:Resources.Board_ClearSearch}">
|
||||
<icons:PackIconLucide Kind="X" Width="16" Height="16"/>
|
||||
</Button>
|
||||
|
||||
<Button Grid.Column="3" Margin="4,0,0,0" Command="{Binding SearchCommand}"
|
||||
ToolTip.Tip="{x:Static lang:Resources.Board_Search}">
|
||||
<icons:PackIconLucide Kind="Search" Width="16" Height="16"/>
|
||||
</Button>
|
||||
|
||||
<Button Grid.Column="4" Margin="12,0,0,0" Command="{Binding AddNewColumnCommand}">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<icons:PackIconLucide Kind="Plus" Width="16" Height="16"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_AddColumn}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
|
||||
<Button Grid.Column="5" Margin="4,0,0,0">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<icons:PackIconLucide Kind="SlidersHorizontal" Width="16" Height="16"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_Display}"/>
|
||||
</StackPanel>
|
||||
<Button.Flyout>
|
||||
<Flyout Placement="BottomEdgeAlignedRight">
|
||||
<StackPanel Width="280" Spacing="12" Margin="4">
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_ColumnWidth}"/>
|
||||
<ComboBox ItemsSource="{Binding Display.Presets}"
|
||||
SelectedItem="{Binding Display.SelectedPreset}"
|
||||
HorizontalAlignment="Stretch">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vmBase:OptionItem">
|
||||
<TextBlock Text="{Binding Label}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8"
|
||||
IsVisible="{Binding Display.IsCustom}">
|
||||
<TextBlock Text="{x:Static lang:Resources.WidthDialog_Pixels}"
|
||||
VerticalAlignment="Center"/>
|
||||
<NumericUpDown Value="{Binding Display.CustomPixels}"
|
||||
Minimum="160" Maximum="720" Width="120"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_SortCard}"/>
|
||||
<ComboBox ItemsSource="{Binding Display.SortOptions}"
|
||||
SelectedItem="{Binding Display.SelectedCardSort}"
|
||||
HorizontalAlignment="Stretch">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vmBase:OptionItem">
|
||||
<TextBlock Text="{Binding Label}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_SortColumn}"/>
|
||||
<ComboBox ItemsSource="{Binding Display.SortOptions}"
|
||||
SelectedItem="{Binding Display.SelectedColumnSort}"
|
||||
HorizontalAlignment="Stretch">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vmBase:OptionItem">
|
||||
<TextBlock Text="{Binding Label}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
</StackPanel>
|
||||
|
||||
</StackPanel>
|
||||
</Flyout>
|
||||
</Button.Flyout>
|
||||
</Button>
|
||||
</Grid>
|
||||
|
||||
<!-- Board surface: columns horizontally, each scrolling its cards vertically. -->
|
||||
<ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled">
|
||||
<ItemsControl ItemsSource="{Binding Columns}" Margin="8">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Horizontal" Spacing="12"/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
|
||||
<TextBlock Grid.Row="1" Text="{x:Static lang:Resources.Board_NoColumns}"
|
||||
IsVisible="{Binding HasNoColumns}" Classes="Secondary"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
|
||||
</Grid>
|
||||
</UserControl>
|
||||
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user