Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2932352220 | ||
|
|
a7b07db034 | ||
|
|
7fd54fe84a | ||
|
|
d29a9ac38e | ||
|
|
210d0b65ed | ||
|
|
e84db09bd6 | ||
|
|
8714eec6ca | ||
|
|
253847323a | ||
|
|
a2c4e1853d | ||
|
|
e7076a76c2 | ||
|
|
ce6d9d2f83 | ||
|
|
4a88033695 | ||
|
|
1ecb48316d | ||
|
|
05a5169129 | ||
|
|
d3b071b0be | ||
|
|
c9523d0953 | ||
|
|
f9f0e71453 | ||
|
|
23f7806e2d | ||
|
|
1d744ba504 | ||
|
|
9277e2a331 | ||
|
|
b6e8e07d78 | ||
|
|
b56c79e5da | ||
|
|
98e001d719 | ||
|
|
8e144b9154 | ||
|
|
c12408d2e3 | ||
|
|
22102cd1ea | ||
|
|
d2a5d36bd2 | ||
|
|
8ae9780c0e |
No files matched your search
@@ -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.
|
||||
@@ -28,4 +28,4 @@ by the manually triggered workflow in `.github/workflows/build.yml`;
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
MIT — see [LICENSE](LICENSE).
|
||||
@@ -45,7 +45,8 @@ ykanban <path>
|
||||
```
|
||||
|
||||
- Exactly one argument is accepted. A relative path is resolved against the
|
||||
current working directory, so `ykanban .` opens the current folder.
|
||||
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
|
||||
@@ -57,11 +58,11 @@ instead:
|
||||
|
||||
| Page | When |
|
||||
|---|---|
|
||||
| Invalid arguments | No argument, more than one argument, an empty argument, or an argument starting with `-` (including `--help`). Shows the usage line. |
|
||||
| Invalid arguments | No argument, more than one argument, an empty or whitespace-only argument, an argument starting with `-` (including `--help`), or a path the operating system cannot represent (for example one containing a NUL character). Shows the usage line. |
|
||||
| Folder not found | `<path>` does not exist or is not a folder. |
|
||||
| No workspace here | `<path>` exists but has no `.ykanban`. The **Initialize workspace** button creates one, with the columns To Do / In Progress / Done (named in the current interface language). |
|
||||
| Workspace locked | Another YKanBan window already has this workspace open. Close that window first. |
|
||||
| Cannot open workspace | 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). The English error details can be selected and copied. |
|
||||
| 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.
|
||||
@@ -80,12 +81,17 @@ Double-clicking `YKanBan.app` starts it without a path, so it only shows the
|
||||
Launch Services or by running the executable inside the bundle:
|
||||
|
||||
```sh
|
||||
open -a YKanBan --args /path/to/project
|
||||
open -n -a YKanBan --args /path/to/project
|
||||
/Applications/YKanBan.app/Contents/MacOS/YKanBan /path/to/project
|
||||
```
|
||||
|
||||
`open -a YKanBan` finds the app once it is in `/Applications` (or another
|
||||
folder Launch Services knows about).
|
||||
- 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
|
||||
|
||||
@@ -153,7 +159,7 @@ 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 := '"' any text '"' -- escapes: \" and \\
|
||||
phrase := '"' one or more characters '"' -- escapes: \" and \\
|
||||
```
|
||||
|
||||
### Operators
|
||||
@@ -192,6 +198,10 @@ phrase := '"' any text '"' -- escapes: \" 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
|
||||
|
||||
@@ -215,11 +225,16 @@ These are invalid:
|
||||
| Problem | Example |
|
||||
|---|---|
|
||||
| Unbalanced parentheses | `(tag:bug`, `tag:bug)` |
|
||||
| Parentheses nested more than 64 levels deep | `((((…a…))))` with 65 `(` |
|
||||
| More than 256 search terms (words, phrases and qualifiers) | 257 words |
|
||||
| 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` |
|
||||
|
||||
@@ -123,7 +123,7 @@ public class MarkdownExporterTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalizes CRLF line endings so expected and actual compare consistently.
|
||||
/// Normalizes the expected document, built with the platform newline, to the exporter's LF.
|
||||
/// </summary>
|
||||
/// <param name="text">The text to normalize.</param>
|
||||
/// <returns>The text with normalized line endings.</returns>
|
||||
@@ -139,7 +139,7 @@ public class MarkdownExporterTests
|
||||
try
|
||||
{
|
||||
Resources.Culture = culture;
|
||||
Assert.AreEqual(Normalize(BuildExpected(culture)), Normalize(ExportBoard()));
|
||||
Assert.AreEqual(Normalize(BuildExpected(culture)), ExportBoard());
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -181,6 +181,21 @@ public class MarkdownExporterTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("D:\\", "D")]
|
||||
[DataRow("a<b>c|d?e*f\"g", "abcdefg")]
|
||||
[DataRow("/", null)]
|
||||
public void FileNameDropsCharactersThatAreInvalidInFileNames(string workspaceName, string? expectedName)
|
||||
{
|
||||
string fileName = MarkdownExporter.BuildFileName(workspaceName, ExportedAt);
|
||||
|
||||
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
|
||||
Assert.AreEqual(
|
||||
string.Format(culture, Resources.Export_FileNamePattern, expectedName ?? Resources.App_Name, ExportedAt),
|
||||
fileName);
|
||||
Assert.AreEqual(-1, fileName.IndexOfAny(Path.GetInvalidFileNameChars()));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagTableCellsEscapePipesAndLineBreaks()
|
||||
{
|
||||
@@ -204,6 +219,29 @@ public class MarkdownExporterTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagTableCellsEscapeBackslashesSoAPipeAfterOneStaysEscaped()
|
||||
{
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
var tag = new TagModel(1, @"a\|b", RgbColor.Parse("#112233"), @"C:\temp\");
|
||||
string markdown = MarkdownExporter.Export(
|
||||
"W",
|
||||
[new ColumnModel(1, "C", string.Empty, 1, 1)],
|
||||
[],
|
||||
[(tag, 0L)],
|
||||
ExportedAt);
|
||||
|
||||
StringAssert.Contains(markdown, @"| a\\\|b | #112233 | C:\\temp\\ | 0 |");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("plain", "`plain`")]
|
||||
[DataRow("a`b", "``a`b``")]
|
||||
@@ -225,7 +263,7 @@ public class MarkdownExporterTests
|
||||
[(tag, 1L)],
|
||||
ExportedAt);
|
||||
|
||||
StringAssert.Contains(markdown, string.Format(Resources.Culture, Resources.Export_TagsLine, expected) + Environment.NewLine);
|
||||
StringAssert.Contains(markdown, string.Format(Resources.Culture, Resources.Export_TagsLine, expected) + "\n");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -240,12 +278,12 @@ public class MarkdownExporterTests
|
||||
try
|
||||
{
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
string markdown = Normalize(MarkdownExporter.Export(
|
||||
string markdown = MarkdownExporter.Export(
|
||||
"W",
|
||||
[new ColumnModel(1, "C", "line one\n# not a heading | pipe", 1, 1)],
|
||||
[new CardModel(1, 1, "T", "body\n\n## raw | `md`", 1, 1, [])],
|
||||
[],
|
||||
ExportedAt));
|
||||
ExportedAt);
|
||||
|
||||
StringAssert.Contains(markdown, "\nline one\n# not a heading | pipe\n");
|
||||
StringAssert.Contains(markdown, "\nbody\n\n## raw | `md`\n");
|
||||
@@ -256,6 +294,53 @@ public class MarkdownExporterTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LineEndingsAreLfOnEveryPlatform()
|
||||
{
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
string markdown = MarkdownExporter.Export(
|
||||
"W",
|
||||
[new ColumnModel(1, "C", "one\r\ntwo\rthree", 1, 1)],
|
||||
[new CardModel(1, 1, "T", "a\r\nb", 1, 1, [])],
|
||||
[],
|
||||
ExportedAt);
|
||||
|
||||
Assert.IsFalse(markdown.Contains('\r'));
|
||||
StringAssert.Contains(markdown, "\none\ntwo\nthree\n");
|
||||
StringAssert.Contains(markdown, "\na\nb\n");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnTitleIsCollapsedToOneLine()
|
||||
{
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
string markdown = MarkdownExporter.Export(
|
||||
"W",
|
||||
[new ColumnModel(1, "To\r\nDo\nNow", string.Empty, 1, 1)],
|
||||
[],
|
||||
[],
|
||||
ExportedAt);
|
||||
|
||||
string heading = string.Format(Resources.Culture, Resources.Export_ColumnHeading, "To Do Now", 0);
|
||||
StringAssert.Contains(markdown, "\n" + heading + "\n");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnsAndCardsAreExportedInIdOrder()
|
||||
{
|
||||
|
||||
@@ -40,7 +40,7 @@ public class CardOrderingTests
|
||||
public void TitleSortsSupplementaryCharactersAfterBmpPrivateUse()
|
||||
{
|
||||
// U+1F600 is a surrogate pair in UTF-16, so ordinal comparison would put it before U+E000.
|
||||
CardModel[] cards = [Card(1, "\U0001F600"), Card(2, "")];
|
||||
CardModel[] cards = [Card(1, "\U0001F600"), Card(2, "\uE000")];
|
||||
CollectionAssert.AreEqual(new[] { 2L, 1L }, Ids(cards, CardSortOption.Title));
|
||||
}
|
||||
}
|
||||
@@ -227,6 +227,55 @@ public class SearchQueryParserTests
|
||||
AssertSyntaxError("a)");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NestingAtTheDepthLimitParses()
|
||||
{
|
||||
int depth = SearchQueryParser.MaxNestingDepth;
|
||||
AssertParsesTo(new SearchNode.FreeText("a"), new string('(', depth) + "a" + new string(')', depth));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NestingBeyondTheDepthLimitIsAnError()
|
||||
{
|
||||
int depth = SearchQueryParser.MaxNestingDepth + 1;
|
||||
AssertSyntaxError(new string('(', depth) + "a" + new string(')', depth));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SequentialGroupsDoNotCountTowardsTheDepthLimit()
|
||||
{
|
||||
string groups = string.Join(" ", Enumerable.Repeat("(a)", SearchQueryParser.MaxNestingDepth + 1));
|
||||
Assert.IsNotNull(SearchQueryParser.Parse(groups));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AtomCountAtTheLimitParses()
|
||||
{
|
||||
Assert.IsNotNull(SearchQueryParser.Parse(string.Join(" ", Enumerable.Repeat("a", SearchQueryParser.MaxAtomCount))));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(" ")]
|
||||
[DataRow(" OR ")]
|
||||
public void AtomCountBeyondTheLimitIsAnError(string separator)
|
||||
{
|
||||
AssertSyntaxError(string.Join(separator, Enumerable.Repeat("a", SearchQueryParser.MaxAtomCount + 1)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void QualifiersAndPhrasesCountTowardsTheAtomLimit()
|
||||
{
|
||||
int half = SearchQueryParser.MaxAtomCount / 2;
|
||||
string text = string.Join(" ", Enumerable.Repeat("tag:\"a b\"", half).Concat(Enumerable.Repeat("\"c\"", half + 1)));
|
||||
AssertSyntaxError(text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void VeryDeepNestingIsAnErrorRatherThanACrash()
|
||||
{
|
||||
AssertSyntaxError(new string('(', 100_000) + "a" + new string(')', 100_000));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EmptyParensAreAnError()
|
||||
{
|
||||
@@ -269,6 +318,42 @@ public class SearchQueryParserTests
|
||||
AssertSyntaxError("tag: bug");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("tag: \"x\"")]
|
||||
[DataRow("title: \"a b\"")]
|
||||
public void SpacedQualifierPhraseValueIsAnError(string text)
|
||||
{
|
||||
AssertSyntaxError(text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("a\"b\"")]
|
||||
[DataRow("\"a\"b")]
|
||||
[DataRow("\"a\"\"b\"")]
|
||||
[DataRow("tag:\"x\"y")]
|
||||
[DataRow("tag:\"x\"\"y\"")]
|
||||
public void PhraseGluedToOtherTextIsAnError(string text)
|
||||
{
|
||||
AssertSyntaxError(text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("\"\"")]
|
||||
[DataRow("a \"\"")]
|
||||
[DataRow("tag:\"\"")]
|
||||
public void EmptyPhraseIsAnError(string text)
|
||||
{
|
||||
AssertSyntaxError(text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PhraseMayTouchParentheses()
|
||||
{
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([new SearchNode.FreeText("a b"), new SearchNode.FreeText("c")]),
|
||||
"(\"a b\")(c)");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("id:12x")]
|
||||
[DataRow("id:abc")]
|
||||
|
||||
@@ -190,4 +190,20 @@ public class SearchSqlCompilerTests
|
||||
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("tag:äpfel"));
|
||||
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("column:érable"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LargestAcceptedQueriesRunWithinTheSqliteExpressionDepth()
|
||||
{
|
||||
using var fixture = new SearchFixture();
|
||||
int count = SearchQueryParser.MaxAtomCount;
|
||||
int depth = SearchQueryParser.MaxNestingDepth;
|
||||
string nested = string.Concat(Enumerable.Repeat("(tag:x OR ", depth))
|
||||
+ string.Join(" ", Enumerable.Repeat("apple", count - depth))
|
||||
+ new string(')', depth);
|
||||
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search(string.Join(" ", Enumerable.Repeat("apple", count))));
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search(string.Join(" OR ", Enumerable.Repeat("apple", count))));
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search(string.Join(" ", Enumerable.Repeat("title:apple", count))));
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search(nested));
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,43 @@ public class AppConfigStoreTests
|
||||
Assert.AreEqual("{ this is not valid json", File.ReadAllText(path + ".bak"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LoadUnreadableFileReturnsDefaults()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
File.WriteAllText(path, "{ \"language\": \"zh-Hans\" }");
|
||||
var store = new AppConfigStore(path);
|
||||
|
||||
AppConfig config;
|
||||
using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||
{
|
||||
config = store.Load();
|
||||
}
|
||||
|
||||
Assert.AreEqual(AppConfig.DefaultLanguage, config.Language);
|
||||
Assert.IsFalse(File.Exists(path + ".bak"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LoadCorruptFileReturnsDefaultsWhenTheBackupCannotBeWritten()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
File.WriteAllText(path, "{ this is not valid json");
|
||||
File.WriteAllText(path + ".bak", "older backup");
|
||||
var store = new AppConfigStore(path);
|
||||
|
||||
AppConfig config;
|
||||
using (new FileStream(path + ".bak", FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||
{
|
||||
config = store.Load();
|
||||
}
|
||||
|
||||
Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version);
|
||||
Assert.AreEqual("older backup", File.ReadAllText(path + ".bak"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LoadJsonNullReturnsDefaults()
|
||||
{
|
||||
@@ -185,6 +222,13 @@ public class AppConfigStoreTests
|
||||
[DataRow("\"column-width\": { \"custom-pixels\": \"wide\" }")]
|
||||
[DataRow("\"confirmations\": { \"delete-card\": \"nope\" }")]
|
||||
[DataRow("\"version\": \"one\"")]
|
||||
[DataRow("\"version\": \"1\"")]
|
||||
[DataRow("\"language\": [\"zh-Hans\"]")]
|
||||
[DataRow("\"confirmations\": { \"delete-card\": 0 }")]
|
||||
[DataRow("\"confirmations\": { \"delete-card\": \"false\" }")]
|
||||
[DataRow("\"column-width\": { \"custom-pixels\": \"500\" }")]
|
||||
[DataRow("\"column-width\": { \"custom-pixels\": 500.0 }")]
|
||||
[DataRow("\"column-width\": { \"custom-pixels\": 99999999999 }")]
|
||||
public void InvalidFieldFallsBackAloneWithoutBackup(string invalidMember)
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
@@ -252,7 +296,7 @@ public class AppConfigStoreTests
|
||||
|
||||
AppConfig config = store.Load();
|
||||
|
||||
Assert.IsFalse(store.SaveIfChanged(config));
|
||||
Assert.IsFalse(store.SaveIfDirty(config));
|
||||
Assert.IsFalse(File.Exists(path));
|
||||
}
|
||||
|
||||
@@ -267,7 +311,7 @@ public class AppConfigStoreTests
|
||||
|
||||
AppConfig config = store.Load();
|
||||
|
||||
Assert.IsFalse(store.SaveIfChanged(config));
|
||||
Assert.IsFalse(store.SaveIfDirty(config));
|
||||
Assert.AreEqual(original, File.ReadAllText(path));
|
||||
}
|
||||
|
||||
@@ -281,15 +325,15 @@ public class AppConfigStoreTests
|
||||
|
||||
config.Sort.Card = CardSortOption.UpdatedAt;
|
||||
|
||||
Assert.IsTrue(store.SaveIfChanged(config));
|
||||
Assert.IsTrue(store.SaveIfDirty(config));
|
||||
Assert.AreEqual(CardSortOption.UpdatedAt, new AppConfigStore(path).Load().Sort.Card);
|
||||
|
||||
// Saved state is the new baseline.
|
||||
Assert.IsFalse(store.SaveIfChanged(config));
|
||||
Assert.IsFalse(store.SaveIfDirty(config));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ChangeRevertedWithinSessionIsNotWritten()
|
||||
public void ChangeRevertedWithinSessionIsStillWritten()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
@@ -299,7 +343,49 @@ public class AppConfigStoreTests
|
||||
config.Theme = ThemeOption.Dark;
|
||||
config.Theme = ThemeOption.FollowSystem;
|
||||
|
||||
Assert.IsFalse(store.SaveIfChanged(config));
|
||||
Assert.IsTrue(store.SaveIfDirty(config));
|
||||
Assert.IsTrue(File.Exists(path));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AssigningTheCurrentValuesIsNotAChange()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
var store = new AppConfigStore(path);
|
||||
AppConfig config = store.Load();
|
||||
|
||||
config.Theme = config.Theme;
|
||||
config.Sort.Card = config.Sort.Card;
|
||||
config.Confirmations.DeleteTag = config.Confirmations.DeleteTag;
|
||||
|
||||
Assert.IsFalse(store.SaveIfDirty(config));
|
||||
Assert.IsFalse(File.Exists(path));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NestedSettingChangeMarksTheConfigurationDirty()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
var store = new AppConfigStore(path);
|
||||
AppConfig config = store.Load();
|
||||
|
||||
config.Confirmations.DiscardEdit = false;
|
||||
|
||||
Assert.IsTrue(config.IsDirty);
|
||||
Assert.IsTrue(store.SaveIfDirty(config));
|
||||
Assert.IsFalse(config.IsDirty);
|
||||
Assert.IsFalse(new AppConfigStore(path).Load().Confirmations.DiscardEdit);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LoadedFileIsNotDirty()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
File.WriteAllText(path, """{ "theme": "dark", "confirmations": { "delete-card": false } }""");
|
||||
|
||||
Assert.IsFalse(new AppConfigStore(path).Load().IsDirty);
|
||||
}
|
||||
}
|
||||
@@ -80,4 +80,48 @@ public class SqliteDatabaseTests
|
||||
|
||||
Assert.ThrowsExactly<ArgumentException>(() => SqliteDatabase.Open(databasePath, broken));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CreateBuildsSchemaAndSeedTogether()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string databasePath = Path.Combine(directory.FullPath, "create.db");
|
||||
|
||||
using SqliteConnection connection = SqliteDatabase.Create(databasePath, WorkspaceSchema.Migrations,
|
||||
(seedConnection, transaction) =>
|
||||
{
|
||||
using SqliteCommand command = seedConnection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = "INSERT INTO tags (name, color) VALUES ('seed', '#000000');";
|
||||
command.ExecuteNonQuery();
|
||||
});
|
||||
Assert.AreEqual(WorkspaceSchema.CurrentVersion, SqliteDatabase.ReadUserVersion(connection));
|
||||
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM tags;"));
|
||||
Assert.AreEqual("wal", SqliteTestHelper.ScalarString(connection, "PRAGMA journal_mode;"));
|
||||
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "PRAGMA foreign_keys;"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CreateWithFailingSeedLeavesNoDatabaseBehind()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string databasePath = Path.Combine(directory.FullPath, "failed.db");
|
||||
|
||||
Assert.ThrowsExactly<InvalidOperationException>(() => SqliteDatabase.Create(
|
||||
databasePath, WorkspaceSchema.Migrations, (_, _) => throw new InvalidOperationException("seed failed")));
|
||||
Assert.IsFalse(File.Exists(databasePath));
|
||||
Assert.IsFalse(File.Exists(databasePath + "-wal"));
|
||||
Assert.IsFalse(File.Exists(databasePath + "-shm"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CreateRefusesAnExistingDatabaseAndKeepsIt()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string databasePath = Path.Combine(directory.FullPath, "existing.db");
|
||||
SqliteDatabase.Create(databasePath, WorkspaceSchema.Migrations).Dispose();
|
||||
|
||||
Assert.ThrowsExactly<InvalidOperationException>(() => SqliteDatabase.Create(databasePath, WorkspaceSchema.Migrations));
|
||||
Assert.IsTrue(File.Exists(databasePath));
|
||||
}
|
||||
}
|
||||
@@ -29,8 +29,7 @@ public class WorkspacePresetTests
|
||||
];
|
||||
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
WorkspacePreset.AddPresetColumns(directory.FullPath);
|
||||
WorkspaceSession.Initialize(directory.FullPath).Dispose();
|
||||
|
||||
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection));
|
||||
@@ -56,8 +55,7 @@ public class WorkspacePresetTests
|
||||
];
|
||||
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
WorkspacePreset.AddPresetColumns(directory.FullPath);
|
||||
WorkspaceSession.Initialize(directory.FullPath).Dispose();
|
||||
|
||||
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection));
|
||||
@@ -83,8 +81,7 @@ public class WorkspacePresetTests
|
||||
];
|
||||
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
WorkspacePreset.AddPresetColumns(directory.FullPath);
|
||||
WorkspaceSession.Initialize(directory.FullPath).Dispose();
|
||||
|
||||
// Switching the language after adding the presets must not rewrite stored data.
|
||||
Resources.Culture = new CultureInfo("zh-Hans");
|
||||
|
||||
@@ -57,4 +57,51 @@ public class WorkspaceSessionTests
|
||||
Assert.AreEqual("bug", session.Repository.GetTags().Single().Name);
|
||||
Assert.AreEqual(tag.Id, session.Repository.GetTags().Single().Id);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InitializeAddsPresetColumnsAndHoldsTheLock()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
|
||||
using WorkspaceSession session = WorkspaceSession.Initialize(directory.FullPath);
|
||||
Assert.AreEqual(3, session.Repository.GetColumns().Count);
|
||||
Assert.ThrowsExactly<WorkspaceLockException>(() => WorkspaceSession.Open(directory.FullPath));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InitializeWhileAnotherInstanceHoldsTheLockThrowsLockConflict()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
Directory.CreateDirectory(WorkspacePaths.Root(directory.FullPath));
|
||||
using WorkspaceLock held = WorkspaceLock.Acquire(directory.FullPath);
|
||||
|
||||
Assert.ThrowsExactly<WorkspaceLockException>(() => WorkspaceSession.Initialize(directory.FullPath));
|
||||
Assert.IsFalse(File.Exists(WorkspacePaths.Database(directory.FullPath)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FailedInitializeReleasesTheLock()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
// The database already exists, so initialization fails after taking the lock.
|
||||
Assert.ThrowsExactly<InvalidOperationException>(() => WorkspaceSession.Initialize(directory.FullPath));
|
||||
using WorkspaceSession reopened = WorkspaceSession.Open(directory.FullPath);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OpenWithMissingDatabaseThrowsAndCreatesNothing()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
string databasePath = WorkspacePaths.Database(directory.FullPath);
|
||||
File.Delete(databasePath);
|
||||
|
||||
Assert.ThrowsExactly<WorkspaceDatabaseMissingException>(() => WorkspaceSession.Open(directory.FullPath));
|
||||
Assert.IsFalse(File.Exists(databasePath));
|
||||
|
||||
// The lock was released again: the next attempt fails the same way, not with a lock conflict.
|
||||
Assert.ThrowsExactly<WorkspaceDatabaseMissingException>(() => WorkspaceSession.Open(directory.FullPath));
|
||||
}
|
||||
}
|
||||
@@ -27,10 +27,12 @@ internal sealed class ScriptedDialogService : IDialogService
|
||||
return result ?? false;
|
||||
}
|
||||
|
||||
public Task<string?> PickSaveFilePathAsync(string suggestedFileName)
|
||||
public Task<Func<Task<Stream>>?> PickSaveFileAsync(string suggestedFileName)
|
||||
{
|
||||
SuggestedFileNames.Add(suggestedFileName);
|
||||
return Task.FromResult(SaveFilePath);
|
||||
string? path = SaveFilePath;
|
||||
return Task.FromResult<Func<Task<Stream>>?>(
|
||||
path is null ? null : () => Task.FromResult<Stream>(File.Create(path)));
|
||||
}
|
||||
|
||||
/// <summary>Answers every confirmation dialog with the given choice.</summary>
|
||||
|
||||
@@ -204,6 +204,66 @@ public class BoardViewModelTests
|
||||
Assert.AreEqual(card.Id, board.Columns[0].Cards.Single().Card.Id);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EditorThatWroteNothingLeavesTheColumnsAlone()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
fixture.Repository.AddCard(column.Id, "t", "", []);
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
ColumnViewModel shown = board.Columns.Single();
|
||||
int writes = 0;
|
||||
board.DataWritten += (_, _) => writes++;
|
||||
|
||||
// Cancel a new card, confirm an unchanged existing card, confirm an empty new card.
|
||||
fixture.Dialogs.Script = dialog => dialog is CardEditorDialogViewModel editor
|
||||
? editor.RequestCancelAsync()
|
||||
: Task.CompletedTask;
|
||||
await shown.AddCardCommand.ExecuteAsync(null);
|
||||
fixture.Dialogs.Script = dialog =>
|
||||
{
|
||||
(dialog as CardEditorDialogViewModel)?.ConfirmCommand.Execute(null);
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
await shown.Cards.Single().EditCommand.ExecuteAsync(null);
|
||||
await shown.AddCardCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.AreSame(shown, board.Columns.Single());
|
||||
Assert.AreEqual(0, writes);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TagCreatedInACancelledEditRefreshesTheBoard()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
fixture.Repository.AddColumn("A", "");
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
ColumnViewModel shown = board.Columns.Single();
|
||||
int writes = 0;
|
||||
board.DataWritten += (_, _) => writes++;
|
||||
fixture.Dialogs.Script = async dialog =>
|
||||
{
|
||||
switch (dialog)
|
||||
{
|
||||
case CardEditorDialogViewModel editor:
|
||||
await editor.AddTagCommand.ExecuteAsync(null);
|
||||
editor.Tags.Clear();
|
||||
await editor.RequestCancelAsync();
|
||||
break;
|
||||
case TagPickerDialogViewModel picker:
|
||||
picker.NewName = "fresh";
|
||||
picker.NewColor = "#123456";
|
||||
picker.CreateCommand.Execute(null);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
await shown.AddCardCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.AreNotSame(shown, board.Columns.Single());
|
||||
Assert.AreEqual(1, writes);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnchangedEditConfirmationWritesNothing()
|
||||
{
|
||||
@@ -225,6 +285,48 @@ public class BoardViewModelTests
|
||||
Assert.AreEqual(100, fixture.Repository.GetCard(card.Id)!.UpdatedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ConfirmingAnEmptyNewCardCreatesNothing()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
var editor = CardEditorDialogViewModel.ForNewCard(fixture.Repository, fixture.Dialogs, column.Id, confirmDiscard: true);
|
||||
bool? closedWith = null;
|
||||
editor.CloseRequested += (_, result) => closedWith = result;
|
||||
editor.CardTitle = "draft";
|
||||
editor.CardTitle = "";
|
||||
|
||||
editor.ConfirmCommand.Execute(null);
|
||||
|
||||
Assert.IsTrue(closedWith);
|
||||
Assert.IsNull(editor.SavedCard);
|
||||
Assert.AreEqual(0, fixture.Repository.GetCards().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NewCardWithOnlyATagIsCreated()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(255, 0, 0), "");
|
||||
var editor = CardEditorDialogViewModel.ForNewCard(fixture.Repository, fixture.Dialogs, column.Id, confirmDiscard: true);
|
||||
fixture.Dialogs.Script = dialog =>
|
||||
{
|
||||
if (dialog is TagPickerDialogViewModel picker)
|
||||
{
|
||||
picker.PickCommand.Execute(picker.FilteredTags.Single());
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
await editor.AddTagCommand.ExecuteAsync(null);
|
||||
editor.ConfirmCommand.Execute(null);
|
||||
|
||||
CardModel card = fixture.Repository.GetCards().Single();
|
||||
Assert.AreEqual("", card.Title);
|
||||
Assert.AreEqual(bug.Id, card.Tags.Single().Id);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DirtyCancelAsksAndStaysOpenWhenDeclined()
|
||||
{
|
||||
@@ -285,6 +387,52 @@ public class BoardViewModelTests
|
||||
Assert.AreEqual(0, fixture.Repository.GetCards().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task FailedSearchQueryIsReportedAndKeepsThePreviousResultAndFilter()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
fixture.Repository.AddCard(column.Id, "alpha", "", []);
|
||||
fixture.Repository.AddCard(column.Id, "beta", "", []);
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
board.SearchText = "alpha";
|
||||
await board.SearchCommand.ExecuteAsync(null);
|
||||
CompiledSearch? alphaFilter = board.ActiveFilter;
|
||||
|
||||
// Every read fails from now on.
|
||||
fixture.Repository.Dispose();
|
||||
board.SearchText = "beta";
|
||||
await board.SearchCommand.ExecuteAsync(null);
|
||||
|
||||
var error = (MessageDialogViewModel)fixture.Dialogs.Shown.Single();
|
||||
Assert.AreEqual(Resources.Error_Read_Title, error.Title);
|
||||
Assert.AreSame(alphaFilter, board.ActiveFilter);
|
||||
CollectionAssert.AreEqual(new[] { "alpha" }, board.Columns.Single().Cards.Select(card => card.Title).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ReadFailuresOnBoardCommandsAreReportedInsteadOfThrown()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
CardModel card = fixture.Repository.AddCard(column.Id, "a", "", []);
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
var editor = CardEditorDialogViewModel.ForExistingCard(fixture.Repository, fixture.Dialogs, card, confirmDiscard: false);
|
||||
fixture.Repository.Dispose();
|
||||
|
||||
board.SelectedSort = board.SortOptions.Single(option => (CardSortOption)option.Value == CardSortOption.Title);
|
||||
await board.ClearSearchCommand.ExecuteAsync(null);
|
||||
await board.Columns.Single().Cards.Single().EditCommand.ExecuteAsync(null);
|
||||
await board.Columns.Single().Cards.Single().MoveToCommand.ExecuteAsync(column.Id);
|
||||
await editor.AddTagCommand.ExecuteAsync(null);
|
||||
|
||||
// Sort, clear, edit, the failed move with its refresh, and the tag picker.
|
||||
string read = Resources.Error_Read_Title;
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { read, read, read, Resources.Error_Operation_Title, read, read },
|
||||
fixture.Dialogs.Shown.Select(dialog => ((MessageDialogViewModel)dialog).Title).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagPickerReportsInvalidColorAndDuplicateNameWithoutClosing()
|
||||
{
|
||||
@@ -308,6 +456,13 @@ public class BoardViewModelTests
|
||||
Assert.AreEqual(1, fixture.Repository.GetTags().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagBadgeShowsNoTooltipForAnEmptyDescription()
|
||||
{
|
||||
Assert.IsNull(new TagBadgeViewModel(new TagModel(1, "bug", new RgbColor(1, 2, 3), "")).ToolTip);
|
||||
Assert.AreEqual("why", new TagBadgeViewModel(new TagModel(1, "bug", new RgbColor(1, 2, 3), "why")).ToolTip);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagPickerHidesAssignedTagsAndFiltersCaseInsensitively()
|
||||
{
|
||||
|
||||
@@ -43,6 +43,9 @@ public class OpenFailedPageViewModelTests
|
||||
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)));
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
|
||||
namespace YKanBan.Tests.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the settings dialog: the theme is previewed as soon as it is
|
||||
/// selected, saved on accept and restored on cancel.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class SettingsDialogViewModelTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void OpeningTheDialogAppliesNothing()
|
||||
{
|
||||
var applied = new List<ThemeOption>();
|
||||
|
||||
_ = new SettingsDialogViewModel(new AppConfig(), AppConfig.DefaultLanguage, applied.Add);
|
||||
|
||||
Assert.AreEqual(0, applied.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SelectingAThemeAppliesItImmediatelyWithoutSavingIt()
|
||||
{
|
||||
var config = new AppConfig();
|
||||
var applied = new List<ThemeOption>();
|
||||
var dialog = new SettingsDialogViewModel(config, AppConfig.DefaultLanguage, applied.Add);
|
||||
|
||||
dialog.SelectedTheme = dialog.Themes.Single(option => option.Value.Equals(ThemeOption.Dark));
|
||||
|
||||
CollectionAssert.AreEqual(new[] { ThemeOption.Dark }, applied);
|
||||
Assert.AreEqual(ThemeOption.FollowSystem, config.Theme);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AcceptSavesThePreviewedTheme()
|
||||
{
|
||||
var config = new AppConfig();
|
||||
var applied = new List<ThemeOption>();
|
||||
var dialog = new SettingsDialogViewModel(config, AppConfig.DefaultLanguage, applied.Add);
|
||||
dialog.SelectedTheme = dialog.Themes.Single(option => option.Value.Equals(ThemeOption.Light));
|
||||
|
||||
dialog.Accept();
|
||||
|
||||
Assert.AreEqual(ThemeOption.Light, config.Theme);
|
||||
CollectionAssert.AreEqual(new[] { ThemeOption.Light }, applied);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CancelRestoresTheThemeTheDialogOpenedWith()
|
||||
{
|
||||
var config = new AppConfig { Theme = ThemeOption.Light };
|
||||
var applied = new List<ThemeOption>();
|
||||
var dialog = new SettingsDialogViewModel(config, AppConfig.DefaultLanguage, applied.Add);
|
||||
dialog.SelectedTheme = dialog.Themes.Single(option => option.Value.Equals(ThemeOption.Dark));
|
||||
|
||||
dialog.Cancel();
|
||||
|
||||
Assert.AreEqual(ThemeOption.Light, config.Theme);
|
||||
CollectionAssert.AreEqual(new[] { ThemeOption.Dark, ThemeOption.Light }, applied);
|
||||
}
|
||||
}
|
||||
@@ -138,7 +138,7 @@ public class TagsAndSearchViewModelTests
|
||||
board.SearchText = "alpha";
|
||||
await board.SearchCommand.ExecuteAsync(null);
|
||||
Assert.IsTrue(board.HasSearchText);
|
||||
board.ClearSearchCommand.Execute(null);
|
||||
await board.ClearSearchCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.AreEqual("", board.SearchText);
|
||||
Assert.IsFalse(board.HasSearchText);
|
||||
@@ -312,6 +312,24 @@ public class TagsAndSearchViewModelTests
|
||||
Assert.AreEqual(0, fixture.Repository.GetTags().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TagReadFailuresAreReportedInsteadOfThrown()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
|
||||
fixture.Config.Confirmations.DeleteTag = false;
|
||||
TagsViewModel tags = fixture.CreateTags();
|
||||
|
||||
// Every read and write fails from now on.
|
||||
fixture.Repository.Dispose();
|
||||
await tags.Tags[0].DeleteCommand.ExecuteAsync(null);
|
||||
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { Resources.Error_Operation_Title, Resources.Error_Read_Title },
|
||||
fixture.Dialogs.Shown.Select(dialog => ((MessageDialogViewModel)dialog).Title).ToArray());
|
||||
Assert.AreEqual("bug", tags.Tags.Single().Tag.Name);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Workspace wiring and export
|
||||
@@ -334,7 +352,7 @@ public class TagsAndSearchViewModelTests
|
||||
Assert.AreEqual(0, workspace.Board.Columns.Sum(column => column.CardCount));
|
||||
|
||||
// Re-tag through the repository, then a board write updates the usage count.
|
||||
workspace.Board.ClearSearchCommand.Execute(null);
|
||||
await workspace.Board.ClearSearchCommand.ExecuteAsync(null);
|
||||
TagModel ui = fixture.Repository.AddTag("ui", new RgbColor(4, 5, 6), "");
|
||||
fixture.Repository.UpdateCard(card.Id, "a", "", [ui.Id]);
|
||||
Assert.AreEqual(0, workspace.Tags.Tags.Count);
|
||||
@@ -396,5 +414,22 @@ public class TagsAndSearchViewModelTests
|
||||
Assert.IsTrue(message.HasDetails);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ExportReadFailureIsReportedAndLeavesTheTargetUntouched()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
WorkspaceViewModel workspace = fixture.CreateWorkspace();
|
||||
string path = Path.Combine(fixture.Directory.FullPath, "out.md");
|
||||
File.WriteAllText(path, "previous");
|
||||
fixture.Dialogs.SaveFilePath = path;
|
||||
|
||||
fixture.Repository.Dispose();
|
||||
await workspace.ExportCommand.ExecuteAsync(null);
|
||||
|
||||
var message = (MessageDialogViewModel)fixture.Dialogs.Shown.Single();
|
||||
Assert.AreEqual(Resources.Export_Failed_Title, message.Title);
|
||||
Assert.AreEqual("previous", File.ReadAllText(path));
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -79,6 +79,9 @@
|
||||
<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>
|
||||
@@ -340,6 +343,15 @@
|
||||
<data name="Error_Operation_Message" xml:space="preserve">
|
||||
<value>The change could not be written to the workspace. The board shows the stored state.</value>
|
||||
</data>
|
||||
<data name="Error_ViewNotFound" xml:space="preserve">
|
||||
<value>View not found: {0}</value>
|
||||
</data>
|
||||
<data name="Error_Read_Title" xml:space="preserve">
|
||||
<value>Reading failed</value>
|
||||
</data>
|
||||
<data name="Error_Read_Message" xml:space="preserve">
|
||||
<value>The data could not be read from the workspace. What is shown may be out of date.</value>
|
||||
</data>
|
||||
<data name="TagEditor_TitleNew" xml:space="preserve">
|
||||
<value>New tag</value>
|
||||
</data>
|
||||
|
||||
@@ -79,6 +79,9 @@
|
||||
<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>
|
||||
@@ -340,6 +343,15 @@
|
||||
<data name="Error_Operation_Message" xml:space="preserve">
|
||||
<value>更改未能写入工作区,看板显示的是已保存的状态。</value>
|
||||
</data>
|
||||
<data name="Error_ViewNotFound" xml:space="preserve">
|
||||
<value>找不到视图:{0}</value>
|
||||
</data>
|
||||
<data name="Error_Read_Title" xml:space="preserve">
|
||||
<value>读取失败</value>
|
||||
</data>
|
||||
<data name="Error_Read_Message" xml:space="preserve">
|
||||
<value>无法从工作区读取数据,当前显示的内容可能不是最新的。</value>
|
||||
</data>
|
||||
<data name="TagEditor_TitleNew" xml:space="preserve">
|
||||
<value>新建标签</value>
|
||||
</data>
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 172 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
@@ -8,9 +8,10 @@ namespace YKanBan.Export;
|
||||
/// Generates the human-readable Markdown snapshot of a whole board. All
|
||||
/// template text and the time format come from the ResX resources in the current
|
||||
/// UI language; every timestamp (export time and card created/modified times)
|
||||
/// uses that one per-language pattern. Card bodies and column descriptions are
|
||||
/// emitted verbatim; tag names become inline code with a long enough backtick
|
||||
/// fence; tag table cells escape '|' and turn line breaks into <br>. The
|
||||
/// uses that one per-language pattern. The whole document uses LF line endings
|
||||
/// on every platform. Card bodies and column descriptions are emitted verbatim
|
||||
/// apart from line endings; column and card titles are collapsed to one line;
|
||||
/// tag names become inline code with a long enough backtick fence; tag table cells escape '\' and '|' and turn line breaks into <br>. The
|
||||
/// output is meant for reading only — there is no re-import.
|
||||
/// </summary>
|
||||
public static class MarkdownExporter
|
||||
@@ -36,10 +37,10 @@ public static class MarkdownExporter
|
||||
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(
|
||||
AppendLine(builder, string.Format(culture, Resources.Export_WorkspaceHeading, SingleLine(workspaceName)));
|
||||
AppendLine(builder, string.Format(
|
||||
culture, Resources.Export_ExportedAtLine, exportedAt.ToString(Resources.Export_TimePattern, culture)));
|
||||
builder.AppendLine();
|
||||
AppendLine(builder);
|
||||
|
||||
// Board body: every column in id order, empty ones included; independent of
|
||||
// the board's search filter and card sort option.
|
||||
@@ -47,12 +48,12 @@ public static class MarkdownExporter
|
||||
{
|
||||
IReadOnlyList<CardModel> cardsInColumn =
|
||||
cards.Where(card => card.ColumnId == column.Id).OrderBy(card => card.Id).ToArray();
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, column.Title, cardsInColumn.Count));
|
||||
AppendLine(builder, string.Format(culture, Resources.Export_ColumnHeading, SingleLine(column.Title), cardsInColumn.Count));
|
||||
if (column.Description.Length > 0)
|
||||
{
|
||||
builder.AppendLine(column.Description);
|
||||
AppendLine(builder, ToLf(column.Description));
|
||||
}
|
||||
builder.AppendLine();
|
||||
AppendLine(builder);
|
||||
|
||||
foreach (CardModel card in cardsInColumn)
|
||||
{
|
||||
@@ -66,7 +67,10 @@ public static class MarkdownExporter
|
||||
|
||||
/// <summary>
|
||||
/// Builds the default export file name in the UI language, for example
|
||||
/// "MyRepo-export-20260930-142537.md".
|
||||
/// "MyRepo-export-20260930-142537.md". Characters that are not allowed in a
|
||||
/// file name on any supported platform are dropped from the workspace name
|
||||
/// (a workspace at a drive root is named "D:\"); a name left empty falls
|
||||
/// back to the application name.
|
||||
/// </summary>
|
||||
/// <param name="workspaceName">Workspace display name.</param>
|
||||
/// <param name="exportedAt">Export moment.</param>
|
||||
@@ -74,8 +78,22 @@ public static class MarkdownExporter
|
||||
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>
|
||||
/// 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.
|
||||
@@ -86,25 +104,25 @@ public static class MarkdownExporter
|
||||
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
|
||||
AppendLine(builder, card.Title.Length == 0
|
||||
? $"### #{card.Id}"
|
||||
: $"### #{card.Id} {SingleLine(card.Title)}");
|
||||
|
||||
if (card.Content.Length > 0)
|
||||
{
|
||||
builder.AppendLine(card.Content);
|
||||
AppendLine(builder, ToLf(card.Content));
|
||||
}
|
||||
|
||||
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));
|
||||
AppendLine(builder, string.Format(culture, Resources.Export_TagsLine, names));
|
||||
}
|
||||
|
||||
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();
|
||||
AppendLine(builder, string.Format(culture, Resources.Export_CreatedModifiedLine, created, updated));
|
||||
AppendLine(builder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -118,23 +136,25 @@ public static class MarkdownExporter
|
||||
IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
|
||||
CultureInfo culture)
|
||||
{
|
||||
builder.AppendLine(Resources.Export_TagsSummaryHeading);
|
||||
builder.AppendLine(Resources.Export_TagsTableHeader);
|
||||
builder.AppendLine("|---|---|---|---|");
|
||||
AppendLine(builder, Resources.Export_TagsSummaryHeading);
|
||||
AppendLine(builder, Resources.Export_TagsTableHeader);
|
||||
AppendLine(builder, "|---|---|---|---|");
|
||||
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} |");
|
||||
AppendLine(builder, $"| {Cell(tag.Name)} | {tag.Color} | {Cell(tag.Description)} | {usage} |");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Formats a table cell: escaped pipe characters, line breaks as <br>.
|
||||
/// 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) =>
|
||||
text.Replace("|", "\\|").Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>");
|
||||
// Backslashes first: the table splitter reads "\\" as an escaped backslash, so the
|
||||
// '|' after a literal backslash would otherwise end the cell.
|
||||
text.Replace("\\", "\\\\").Replace("|", "\\|").Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>");
|
||||
|
||||
/// <summary>
|
||||
/// Renders text as an inline code span whose backtick fence is one longer than
|
||||
@@ -158,6 +178,20 @@ public static class MarkdownExporter
|
||||
return fence + padding + text + padding + fence;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends a line terminated by LF, whatever the platform's newline.
|
||||
/// </summary>
|
||||
/// <param name="builder">The output builder.</param>
|
||||
/// <param name="text">The line text; empty for a blank line.</param>
|
||||
private static void AppendLine(StringBuilder builder, string text = "") => builder.Append(text).Append('\n');
|
||||
|
||||
/// <summary>
|
||||
/// Converts CRLF and lone CR line breaks to LF.
|
||||
/// </summary>
|
||||
/// <param name="text">The raw text.</param>
|
||||
/// <returns>The text with LF line breaks only.</returns>
|
||||
private static string ToLf(string text) => text.Replace("\r\n", "\n").Replace('\r', '\n');
|
||||
|
||||
/// <summary>
|
||||
/// Collapses line breaks so the text stays on one Markdown line.
|
||||
/// </summary>
|
||||
|
||||
+8
-1
@@ -12,10 +12,17 @@ sealed class Program
|
||||
{
|
||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
|
||||
// The lifetime has ended: persist the configuration once, then release services.
|
||||
// The lifetime has ended: persist the configuration once, then release
|
||||
// services; the workspace lock and connection are released even if saving fails.
|
||||
try
|
||||
{
|
||||
App.Services?.SaveConfiguration();
|
||||
}
|
||||
finally
|
||||
{
|
||||
App.Services?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// Avalonia configuration, don't remove; also used by visual designer.
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
|
||||
@@ -36,8 +36,11 @@ public abstract record SearchToken
|
||||
///
|
||||
/// 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. Any input not covered by the token rules
|
||||
/// is rejected rather than silently ignored.
|
||||
/// 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
|
||||
{
|
||||
@@ -70,37 +73,101 @@ public static class SearchLexer
|
||||
.AtLeastOnce()
|
||||
.Select(chars => (SearchToken)new SearchToken.Word(new string(chars.ToArray())));
|
||||
|
||||
private static readonly Parser<char, SearchToken> TokenParser =
|
||||
// Each token with its source span, so adjacency can be checked afterwards.
|
||||
private static readonly Parser<char, PositionedToken> TokenParser =
|
||||
Parser.SkipWhitespaces.Then(
|
||||
PhraseParser
|
||||
from start in Parser<char>.CurrentOffset
|
||||
from token in PhraseParser
|
||||
.Or(OpenParenParser)
|
||||
.Or(CloseParenParser)
|
||||
.Or(WordParser));
|
||||
.Or(WordParser)
|
||||
from end in Parser<char>.CurrentOffset
|
||||
select new PositionedToken(token, start, end));
|
||||
|
||||
// Try(...) keeps a failed token non-consuming so Many stops gracefully; End
|
||||
// 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<SearchToken>> Lexer =
|
||||
private static readonly Parser<char, IReadOnlyList<PositionedToken>> Lexer =
|
||||
Parser.Try(TokenParser).Many()
|
||||
.Before(Parser.SkipWhitespaces)
|
||||
.Before(Parser<char>.End)
|
||||
.Select(tokens => (IReadOnlyList<SearchToken>)tokens.ToList());
|
||||
.Select(tokens => (IReadOnlyList<PositionedToken>)tokens.ToList());
|
||||
|
||||
/// <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 or an unterminated phrase.</exception>
|
||||
/// <exception cref="SearchSyntaxException">
|
||||
/// The text contains an invalid escape, an unterminated or empty phrase, a
|
||||
/// phrase glued to other text, or whitespace between a qualifier and its phrase value.
|
||||
/// </exception>
|
||||
public static IReadOnlyList<SearchToken> Tokenize(string input)
|
||||
{
|
||||
IReadOnlyList<PositionedToken> tokens;
|
||||
try
|
||||
{
|
||||
return Lexer.ParseOrThrow(input);
|
||||
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);
|
||||
}
|
||||
@@ -8,8 +8,9 @@ namespace YKanBan.Search;
|
||||
/// (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"/>.
|
||||
/// to AND/OR, id values that are not an unquoted positive integer with an
|
||||
/// optional '#', parentheses nested deeper than <see cref="MaxNestingDepth"/>,
|
||||
/// and more than <see cref="MaxAtomCount"/> atoms) 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
|
||||
@@ -18,6 +19,20 @@ namespace YKanBan.Search;
|
||||
/// </summary>
|
||||
public static class SearchQueryParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Deepest accepted parenthesis nesting. The parser recurses once per level,
|
||||
/// so an unbounded depth would overflow the stack and kill the process.
|
||||
/// </summary>
|
||||
public const int MaxNestingDepth = 64;
|
||||
|
||||
/// <summary>
|
||||
/// Most atoms (words, phrases and qualifiers) accepted in one expression.
|
||||
/// The compiled SQL chains every atom into one expression, and SQLite
|
||||
/// rejects expressions nested deeper than 1000 levels; together with
|
||||
/// <see cref="MaxNestingDepth"/> this keeps every valid query well below that.
|
||||
/// </summary>
|
||||
public const int MaxAtomCount = 256;
|
||||
|
||||
/// <summary>The recognized qualifier keys; add new entries here to extend the grammar.</summary>
|
||||
private static readonly (string Key, QualifierKind Kind)[] QualifierTable =
|
||||
[
|
||||
@@ -114,7 +129,10 @@ public static class SearchQueryParser
|
||||
try
|
||||
{
|
||||
List<SearchToken> tokens = SearchLexer.Tokenize(text).ToList();
|
||||
return Query.ParseOrThrow(tokens);
|
||||
EnsureNestingWithinLimit(tokens);
|
||||
SearchNode query = Query.ParseOrThrow(tokens);
|
||||
EnsureAtomCountWithinLimit(query);
|
||||
return query;
|
||||
}
|
||||
catch (ParseException exception)
|
||||
{
|
||||
@@ -122,6 +140,53 @@ public static class SearchQueryParser
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rejects parenthesis nesting deeper than <see cref="MaxNestingDepth"/>
|
||||
/// before the recursive parser sees it. Balance itself is left to the parser.
|
||||
/// </summary>
|
||||
/// <param name="tokens">The token stream.</param>
|
||||
/// <exception cref="SearchSyntaxException">The nesting is too deep.</exception>
|
||||
private static void EnsureNestingWithinLimit(IEnumerable<SearchToken> tokens)
|
||||
{
|
||||
int depth = 0;
|
||||
foreach (SearchToken token in tokens)
|
||||
{
|
||||
if (token is SearchToken.OpenParen && ++depth > MaxNestingDepth)
|
||||
{
|
||||
throw new SearchSyntaxException($"Parentheses are nested more than {MaxNestingDepth} levels deep.");
|
||||
}
|
||||
if (token is SearchToken.CloseParen && depth > 0)
|
||||
{
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rejects expressions with more than <see cref="MaxAtomCount"/> atoms.
|
||||
/// </summary>
|
||||
/// <param name="query">The parsed query.</param>
|
||||
/// <exception cref="SearchSyntaxException">The expression has too many atoms.</exception>
|
||||
private static void EnsureAtomCountWithinLimit(SearchNode query)
|
||||
{
|
||||
if (CountAtoms(query) > MaxAtomCount)
|
||||
{
|
||||
throw new SearchSyntaxException($"The expression has more than {MaxAtomCount} search terms.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Counts the atoms (leaves) of a parsed query.
|
||||
/// </summary>
|
||||
/// <param name="node">The node to count.</param>
|
||||
/// <returns>The number of atoms under the node.</returns>
|
||||
private static int CountAtoms(SearchNode node) => node switch
|
||||
{
|
||||
SearchNode.And and => and.Terms.Sum(CountAtoms),
|
||||
SearchNode.Or or => or.Terms.Sum(CountAtoms),
|
||||
_ => 1,
|
||||
};
|
||||
|
||||
#region Atom construction
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -8,6 +8,15 @@ namespace YKanBan.Search;
|
||||
/// </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>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Diagnostics;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
@@ -49,9 +50,45 @@ public sealed class AppServices : IDisposable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the configuration when this session changed a setting; called once at shutdown.
|
||||
/// Initializes a workspace with its preset columns and opens it, holding
|
||||
/// the lock from the creation of .ykanban onwards.
|
||||
/// </summary>
|
||||
public void SaveConfiguration() => ConfigStore.SaveIfChanged(Config);
|
||||
/// <param name="folderPath">The existing folder to initialize.</param>
|
||||
/// <returns>The open session.</returns>
|
||||
/// <exception cref="YKanBan.Storage.WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
||||
/// <exception cref="YKanBan.Storage.WorkspaceLockException">Another instance already holds the lock.</exception>
|
||||
public WorkspaceSession InitializeWorkspace(string folderPath)
|
||||
{
|
||||
Session = WorkspaceSession.Initialize(folderPath);
|
||||
return Session;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the open workspace session, if any, so its lock and connection
|
||||
/// do not outlive a workspace that could not be shown.
|
||||
/// </summary>
|
||||
public void CloseWorkspace()
|
||||
{
|
||||
Session?.Dispose();
|
||||
Session = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the configuration when this session changed a setting; called
|
||||
/// once at shutdown. A write failure only loses this session's settings
|
||||
/// changes, the same accepted loss as a crash, so it is logged and ignored.
|
||||
/// </summary>
|
||||
public void SaveConfiguration()
|
||||
{
|
||||
try
|
||||
{
|
||||
ConfigStore.SaveIfDirty(Config);
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Debug.WriteLine(exception);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the workspace session, if any.
|
||||
|
||||
@@ -62,65 +62,101 @@ public enum ThemeOption
|
||||
FollowSystem,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Base of the app.json sections: records whether any setting was changed
|
||||
/// since the last load or save (the dirty flag). Assigning the value a setting
|
||||
/// already holds is not a change; changing a setting and changing it back is.
|
||||
/// </summary>
|
||||
public abstract class ConfigSection
|
||||
{
|
||||
private bool _changed;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether a setting of this section, or of a nested section, was changed.
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public virtual bool IsDirty => _changed;
|
||||
|
||||
/// <summary>
|
||||
/// Clears the dirty flag of this section and its nested sections.
|
||||
/// </summary>
|
||||
public virtual void AcceptChanges() => _changed = false;
|
||||
|
||||
/// <summary>
|
||||
/// Stores a setting and marks the section dirty when the value differs.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The setting type.</typeparam>
|
||||
/// <param name="field">The backing field.</param>
|
||||
/// <param name="value">The new value.</param>
|
||||
protected void Set<T>(ref T field, T value)
|
||||
{
|
||||
if (!EqualityComparer<T>.Default.Equals(field, value))
|
||||
{
|
||||
field = value;
|
||||
_changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Card ordering settings. The chosen order is global, not per workspace.
|
||||
/// </summary>
|
||||
public sealed class SortSettings
|
||||
public sealed class SortSettings : ConfigSection
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the order used by the board.
|
||||
/// </summary>
|
||||
[JsonProperty("card")]
|
||||
public CardSortOption Card { get; set; } = CardSortOption.Id;
|
||||
public CardSortOption Card { get; set => Set(ref field, value); } = CardSortOption.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Board column width settings, applied globally.
|
||||
/// </summary>
|
||||
public sealed class ColumnWidthSettings
|
||||
public sealed class ColumnWidthSettings : ConfigSection
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the active width preset.
|
||||
/// </summary>
|
||||
[JsonProperty("preset")]
|
||||
public ColumnWidthPreset Preset { get; set; } = ColumnWidthPreset.Standard;
|
||||
public ColumnWidthPreset Preset { get; set => Set(ref field, value); } = ColumnWidthPreset.Standard;
|
||||
|
||||
/// <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;
|
||||
public int CustomPixels { get; set => Set(ref field, value); } = 320;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Confirmation-dialog toggles for the destructive actions.
|
||||
/// </summary>
|
||||
public sealed class ConfirmationSettings
|
||||
public sealed class ConfirmationSettings : ConfigSection
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets whether deleting a card asks for confirmation.
|
||||
/// </summary>
|
||||
[JsonProperty("delete-card")]
|
||||
public bool DeleteCard { get; set; } = true;
|
||||
public bool DeleteCard { get; set => Set(ref field, value); } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether deleting a column asks for confirmation.
|
||||
/// </summary>
|
||||
[JsonProperty("delete-column")]
|
||||
public bool DeleteColumn { get; set; } = true;
|
||||
public bool DeleteColumn { get; set => Set(ref field, value); } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether deleting a tag asks for confirmation.
|
||||
/// </summary>
|
||||
[JsonProperty("delete-tag")]
|
||||
public bool DeleteTag { get; set; } = true;
|
||||
public bool DeleteTag { get; set => Set(ref field, value); } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether discarding card edits asks for confirmation.
|
||||
/// </summary>
|
||||
[JsonProperty("discard-edit")]
|
||||
public bool DiscardEdit { get; set; } = true;
|
||||
public bool DiscardEdit { get; set => Set(ref field, value); } = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -129,7 +165,7 @@ public sealed class ConfirmationSettings
|
||||
/// <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
|
||||
public sealed class AppConfig : ConfigSection
|
||||
{
|
||||
/// <summary>
|
||||
/// Current configuration format version.
|
||||
@@ -165,35 +201,47 @@ public sealed class AppConfig
|
||||
/// Gets or sets the configuration format version of this file.
|
||||
/// </summary>
|
||||
[JsonProperty("version")]
|
||||
public int Version { get; set; } = CurrentFormatVersion;
|
||||
public int Version { get; set => Set(ref field, value); } = CurrentFormatVersion;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the UI language code ("en" default or "zh-Hans").
|
||||
/// </summary>
|
||||
[JsonProperty("language")]
|
||||
public string Language { get; set; } = DefaultLanguage;
|
||||
public string Language { get; set => Set(ref field, value); } = DefaultLanguage;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the UI theme selection (default: follow the system).
|
||||
/// </summary>
|
||||
[JsonProperty("theme")]
|
||||
public ThemeOption Theme { get; set; } = ThemeOption.FollowSystem;
|
||||
public ThemeOption Theme { get; set => Set(ref field, value); } = ThemeOption.FollowSystem;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the card ordering settings.
|
||||
/// </summary>
|
||||
[JsonProperty("sort")]
|
||||
public SortSettings Sort { get; set; } = new();
|
||||
public SortSettings Sort { get; set => Set(ref field, value); } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the board column width settings.
|
||||
/// </summary>
|
||||
[JsonProperty("column-width")]
|
||||
public ColumnWidthSettings ColumnWidth { get; set; } = new();
|
||||
public ColumnWidthSettings ColumnWidth { get; set => Set(ref field, value); } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the confirmation-dialog settings.
|
||||
/// </summary>
|
||||
[JsonProperty("confirmations")]
|
||||
public ConfirmationSettings Confirmations { get; set; } = new();
|
||||
public ConfirmationSettings Confirmations { get; set => Set(ref field, value); } = new();
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override bool IsDirty => base.IsDirty || Sort.IsDirty || ColumnWidth.IsDirty || Confirmations.IsDirty;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void AcceptChanges()
|
||||
{
|
||||
base.AcceptChanges();
|
||||
Sort.AcceptChanges();
|
||||
ColumnWidth.AcceptChanges();
|
||||
Confirmations.AcceptChanges();
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Newtonsoft.Json.Linq;
|
||||
@@ -8,9 +9,10 @@ namespace YKanBan.Storage.AppData;
|
||||
/// Loads and saves app.json with graceful degradation: a missing file yields
|
||||
/// defaults; a file that is not a JSON object is backed up to app.json.bak and
|
||||
/// then defaults are used; an individual invalid field (unknown enum value or
|
||||
/// language, out-of-range width, wrong type) falls back to its own default while
|
||||
/// the other fields are kept. Saving happens only when the configuration differs
|
||||
/// from what was loaded, and writes the file directly (no atomic replace) —
|
||||
/// language, out-of-range width, wrong JSON type — no implicit conversion) falls back to its own default while
|
||||
/// the other fields are kept; a file that exists but cannot be read (I/O or
|
||||
/// permission error) also yields defaults. Saving happens only when this session
|
||||
/// changed a setting (<see cref="ConfigSection.IsDirty"/>), and 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
|
||||
@@ -28,16 +30,13 @@ public sealed class AppConfigStore
|
||||
private static readonly JsonSerializer FieldTolerantSerializer = JsonSerializer.Create(new JsonSerializerSettings
|
||||
{
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
Converters = { new StringEnumConverter { AllowIntegerValues = false } },
|
||||
Converters = { new StringEnumConverter { AllowIntegerValues = false }, new StrictPrimitiveConverter() },
|
||||
|
||||
// The JSON text is already known to be well formed here, so every error is a
|
||||
// single member that fails to convert: skip it and keep that member's default.
|
||||
Error = (_, args) => args.ErrorContext.Handled = true,
|
||||
});
|
||||
|
||||
/// <summary>The serialized form of the configuration as last loaded or saved.</summary>
|
||||
private string _persistedSnapshot = Serialize(new AppConfig());
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a store bound to a specific app.json path.
|
||||
/// </summary>
|
||||
@@ -50,50 +49,49 @@ public sealed class AppConfigStore
|
||||
public string FilePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Loads the configuration and records it as the persisted baseline for
|
||||
/// <see cref="SaveIfChanged"/>. A missing file yields defaults; a file that
|
||||
/// is not a JSON object is backed up to app.json.bak and then defaults are
|
||||
/// used; invalid fields fall back to their defaults individually.
|
||||
/// Loads the configuration with a clear dirty flag, the baseline for
|
||||
/// <see cref="SaveIfDirty"/>. A missing file yields defaults; a file that
|
||||
/// is not a JSON object is backed up to app.json.bak (best effort) and then
|
||||
/// defaults are used; invalid fields fall back to their defaults
|
||||
/// individually; a file that cannot be read yields defaults. Never throws for
|
||||
/// file-system reasons, because a bad app.json must not stop the app.
|
||||
/// </summary>
|
||||
/// <returns>The loaded configuration, or defaults when none could be read.</returns>
|
||||
/// <exception cref="IOException">The file exists but cannot be read.</exception>
|
||||
public AppConfig Load()
|
||||
{
|
||||
AppConfig config = Read();
|
||||
|
||||
// The baseline is the effective configuration, so field fallbacks alone never trigger a write.
|
||||
_persistedSnapshot = Serialize(config);
|
||||
// Deserializing and field fallbacks go through the setters; neither is a change by this session.
|
||||
config.AcceptChanges();
|
||||
return config;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the configuration only when it differs from the loaded or last
|
||||
/// saved one, i.e. when this session changed a setting.
|
||||
/// Writes the configuration only when a setting was changed since it was
|
||||
/// loaded or last saved, even if it was later changed back.
|
||||
/// </summary>
|
||||
/// <param name="config">The live configuration.</param>
|
||||
/// <returns><see langword="true"/> when the file was written.</returns>
|
||||
public bool SaveIfChanged(AppConfig config)
|
||||
public bool SaveIfDirty(AppConfig config)
|
||||
{
|
||||
string json = Serialize(config);
|
||||
if (json == _persistedSnapshot)
|
||||
if (!config.IsDirty)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Write(json);
|
||||
_persistedSnapshot = json;
|
||||
Save(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the configuration directly to disk (no atomic replace), unconditionally.
|
||||
/// Writes the configuration directly to disk (no atomic replace),
|
||||
/// unconditionally, and clears its dirty flag.
|
||||
/// </summary>
|
||||
/// <param name="config">The configuration to serialize.</param>
|
||||
public void Save(AppConfig config)
|
||||
{
|
||||
string json = Serialize(config);
|
||||
Write(json);
|
||||
_persistedSnapshot = json;
|
||||
Write(Serialize(config));
|
||||
config.AcceptChanges();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -108,7 +106,16 @@ public sealed class AppConfigStore
|
||||
return new AppConfig();
|
||||
}
|
||||
|
||||
string json = File.ReadAllText(FilePath);
|
||||
string json;
|
||||
try
|
||||
{
|
||||
json = File.ReadAllText(FilePath);
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return new AppConfig();
|
||||
}
|
||||
|
||||
JToken root;
|
||||
try
|
||||
{
|
||||
@@ -137,12 +144,20 @@ public sealed class AppConfigStore
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps a copy of an unusable file for inspection, then continues with defaults.
|
||||
/// Keeps a copy of an unusable file for inspection, then continues with
|
||||
/// defaults; a backup that cannot be written is skipped.
|
||||
/// </summary>
|
||||
/// <returns>The default configuration.</returns>
|
||||
private AppConfig BackUpAndUseDefaults()
|
||||
{
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -197,6 +212,41 @@ public sealed class AppConfigStore
|
||||
File.WriteAllText(FilePath, json);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads booleans, integers and strings only from JSON tokens of exactly that
|
||||
/// type, so a wrong type is an invalid field (falling back to its default)
|
||||
/// instead of being converted: <c>0</c> or <c>"false"</c> is not a boolean,
|
||||
/// <c>"500"</c> or <c>500.0</c> is not an integer, <c>5</c> is not a string.
|
||||
/// </summary>
|
||||
private sealed class StrictPrimitiveConverter : JsonConverter
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override bool CanWrite => false;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override bool CanConvert(Type objectType) =>
|
||||
objectType == typeof(bool) || objectType == typeof(int) || objectType == typeof(string);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
|
||||
{
|
||||
JsonToken expected = objectType == typeof(bool) ? JsonToken.Boolean
|
||||
: objectType == typeof(int) ? JsonToken.Integer
|
||||
: JsonToken.String;
|
||||
if (reader.TokenType != expected)
|
||||
{
|
||||
throw new JsonSerializationException($"Expected a {expected} token for {objectType.Name}, got {reader.TokenType}.");
|
||||
}
|
||||
|
||||
// Integer tokens are read as Int64 (or BigInteger); a value outside the Int32 range is invalid too.
|
||||
return objectType == typeof(int) ? checked((int)Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture)) : reader.Value;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serializes a configuration in the on-disk format.
|
||||
/// </summary>
|
||||
|
||||
@@ -33,16 +33,7 @@ public static class SqliteDatabase
|
||||
/// <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
|
||||
{
|
||||
DataSource = databasePath,
|
||||
Mode = SqliteOpenMode.ReadWriteCreate,
|
||||
|
||||
// Each process holds its own single connection; a pool would only add noise.
|
||||
Pooling = false,
|
||||
}.ToString());
|
||||
|
||||
connection.Open();
|
||||
SqliteConnection connection = OpenConnection(databasePath);
|
||||
try
|
||||
{
|
||||
ApplyPragmas(connection);
|
||||
@@ -57,6 +48,74 @@ public static class SqliteDatabase
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new database file with the mandatory PRAGMAs, then applies
|
||||
/// every migration and the optional seed in one transaction, so the file
|
||||
/// ends up either fully built and seeded or still at version 0.
|
||||
/// </summary>
|
||||
/// <param name="databasePath">Path of the SQLite database file; it must not exist yet.</param>
|
||||
/// <param name="migrations">Contiguous migration list ordered by version, starting at 1.</param>
|
||||
/// <param name="seed">Initial content written in the same transaction, when any.</param>
|
||||
/// <returns>An open connection with all PRAGMAs applied and the schema migrated.</returns>
|
||||
/// <exception cref="ArgumentException">The migration list is not contiguous from version 1.</exception>
|
||||
/// <exception cref="InvalidOperationException">The database file already exists.</exception>
|
||||
public static SqliteConnection Create(
|
||||
string databasePath,
|
||||
IReadOnlyList<SchemaMigration> migrations,
|
||||
Action<SqliteConnection, SqliteTransaction>? seed = null)
|
||||
{
|
||||
ValidateMigrations(migrations);
|
||||
if (File.Exists(databasePath))
|
||||
{
|
||||
throw new InvalidOperationException($"The database already exists: {databasePath}");
|
||||
}
|
||||
|
||||
SqliteConnection connection = OpenConnection(databasePath);
|
||||
try
|
||||
{
|
||||
ApplyPragmas(connection);
|
||||
RegisterFunctions(connection);
|
||||
|
||||
using var transaction = connection.BeginTransaction();
|
||||
foreach (SchemaMigration migration in migrations)
|
||||
{
|
||||
Execute(connection, migration.Sql, transaction);
|
||||
Execute(connection, $"PRAGMA user_version={migration.Version};", transaction);
|
||||
}
|
||||
seed?.Invoke(connection, transaction);
|
||||
transaction.Commit();
|
||||
return connection;
|
||||
}
|
||||
catch
|
||||
{
|
||||
connection.Dispose();
|
||||
|
||||
// Leave no empty version-0 file behind that a later open would migrate into an empty board.
|
||||
DeleteDatabaseFilesBestEffort(databasePath);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a database file together with its WAL and shared-memory files,
|
||||
/// ignoring failures.
|
||||
/// </summary>
|
||||
/// <param name="databasePath">Path of the SQLite database file.</param>
|
||||
private static void DeleteDatabaseFilesBestEffort(string databasePath)
|
||||
{
|
||||
foreach (string path in new[] { databasePath, databasePath + "-wal", databasePath + "-shm", databasePath + "-journal" })
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Best effort: the original failure is what gets reported.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the stored <c>PRAGMA user_version</c> value.
|
||||
/// </summary>
|
||||
@@ -105,14 +164,7 @@ public static class SqliteDatabase
|
||||
/// <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));
|
||||
}
|
||||
}
|
||||
ValidateMigrations(migrations);
|
||||
|
||||
long current = ReadUserVersion(connection);
|
||||
int latest = migrations.Count;
|
||||
@@ -138,6 +190,42 @@ public static class SqliteDatabase
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a connection to the file, creating it if needed, without any configuration.
|
||||
/// </summary>
|
||||
/// <param name="databasePath">Path of the SQLite database file.</param>
|
||||
/// <returns>The open connection.</returns>
|
||||
private static SqliteConnection OpenConnection(string databasePath)
|
||||
{
|
||||
var connection = new SqliteConnection(new SqliteConnectionStringBuilder
|
||||
{
|
||||
DataSource = databasePath,
|
||||
Mode = SqliteOpenMode.ReadWriteCreate,
|
||||
|
||||
// Each process holds its own single connection; a pool would only add noise.
|
||||
Pooling = false,
|
||||
}.ToString());
|
||||
|
||||
connection.Open();
|
||||
return connection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks that the migration list is ordered, contiguous and starts at version 1.
|
||||
/// </summary>
|
||||
/// <param name="migrations">The migration list.</param>
|
||||
/// <exception cref="ArgumentException">The list breaks the contract.</exception>
|
||||
private static void ValidateMigrations(IReadOnlyList<SchemaMigration> migrations)
|
||||
{
|
||||
for (int index = 0; index < migrations.Count; index++)
|
||||
{
|
||||
if (migrations[index].Version != index + 1)
|
||||
{
|
||||
throw new ArgumentException("Migrations must be contiguous and start at version 1.", nameof(migrations));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes a non-query SQL script, optionally inside an explicit transaction.
|
||||
/// </summary>
|
||||
|
||||
@@ -61,6 +61,28 @@ public sealed class WorkspaceNotInitializedException : YKanBanException
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signals that .ykanban exists but its database file does not, so the
|
||||
/// workspace data is missing; a new empty database is never created silently.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceDatabaseMissingException : YKanBanException
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the database file that was expected to exist.
|
||||
/// </summary>
|
||||
public string DatabasePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the exception for a missing workspace database.
|
||||
/// </summary>
|
||||
/// <param name="databasePath">The missing database file path.</param>
|
||||
public WorkspaceDatabaseMissingException(string databasePath)
|
||||
: base($"The workspace database is missing: {databasePath}")
|
||||
{
|
||||
DatabasePath = databasePath;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signals that another instance already holds the workspace lock, so this
|
||||
/// process must not touch the workspace.
|
||||
|
||||
@@ -3,10 +3,10 @@ using Microsoft.Data.Sqlite;
|
||||
namespace YKanBan.Storage.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the .ykanban structure for a folder: the folder itself and an
|
||||
/// 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.
|
||||
/// Creates the .ykanban structure for a folder in the mandated order: the
|
||||
/// .ykanban folder, then the exclusive lock, then the database. The database
|
||||
/// schema and the optional preset content are written in one transaction, so a
|
||||
/// failure never leaves a half-built database behind.
|
||||
/// </summary>
|
||||
public static class WorkspaceInitializer
|
||||
{
|
||||
@@ -19,27 +19,50 @@ public static class WorkspaceInitializer
|
||||
public static bool IsWorkspace(string folderPath) => Directory.Exists(WorkspacePaths.Root(folderPath));
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a fresh workspace: creates .ykanban and an empty migrated
|
||||
/// database, without adding any preset content.
|
||||
/// Initializes a fresh workspace without any preset content and releases
|
||||
/// the lock again.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The existing folder to initialize.</param>
|
||||
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
||||
/// <exception cref="WorkspaceLockException">Another instance holds the workspace lock.</exception>
|
||||
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
|
||||
public static void Initialize(string folderPath)
|
||||
{
|
||||
using WorkspaceLock workspaceLock = InitializeLocked(folderPath, addPresetColumns: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a fresh workspace and returns the lock still held, so the
|
||||
/// caller can open the workspace without ever releasing it.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The existing folder to initialize.</param>
|
||||
/// <param name="addPresetColumns">Whether to add the preset columns in the schema transaction.</param>
|
||||
/// <returns>The held workspace lock.</returns>
|
||||
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
||||
/// <exception cref="WorkspaceLockException">Another instance holds the workspace lock.</exception>
|
||||
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
|
||||
internal static WorkspaceLock InitializeLocked(string folderPath, bool addPresetColumns)
|
||||
{
|
||||
if (!Directory.Exists(folderPath))
|
||||
{
|
||||
throw new WorkspaceDirectoryMissingException(folderPath);
|
||||
}
|
||||
|
||||
string databasePath = WorkspacePaths.Database(folderPath);
|
||||
if (File.Exists(databasePath))
|
||||
{
|
||||
throw new InvalidOperationException($"The workspace database already exists: {databasePath}");
|
||||
}
|
||||
|
||||
// Create the .ykanban folder, then the migrated but still empty database.
|
||||
// .ykanban first: the lock file lives inside it.
|
||||
Directory.CreateDirectory(WorkspacePaths.Root(folderPath));
|
||||
using SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations);
|
||||
WorkspaceLock workspaceLock = WorkspaceLock.Acquire(folderPath);
|
||||
try
|
||||
{
|
||||
using SqliteConnection connection = SqliteDatabase.Create(
|
||||
WorkspacePaths.Database(folderPath),
|
||||
WorkspaceSchema.Migrations,
|
||||
addPresetColumns ? WorkspacePreset.AddPresetColumns : null);
|
||||
return workspaceLock;
|
||||
}
|
||||
catch
|
||||
{
|
||||
workspaceLock.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,15 +12,14 @@ public static class WorkspacePreset
|
||||
{
|
||||
/// <summary>
|
||||
/// Inserts the three preset columns (the current language's equivalents of
|
||||
/// To Do / In Progress / Done) in a single transaction.
|
||||
/// To Do / In Progress / Done) inside the caller's transaction, so the
|
||||
/// presets land together with the schema or not at all.
|
||||
/// </summary>
|
||||
/// <param name="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)
|
||||
/// <param name="connection">The connection to the freshly created database.</param>
|
||||
/// <param name="transaction">The transaction that also builds the schema.</param>
|
||||
/// <exception cref="SqliteException">A title collides with an existing column.</exception>
|
||||
public static void AddPresetColumns(SqliteConnection connection, SqliteTransaction transaction)
|
||||
{
|
||||
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.
|
||||
@@ -31,8 +30,6 @@ public static class WorkspacePreset
|
||||
Resources.PresetColumn_Done,
|
||||
];
|
||||
|
||||
// Insert all three atomically so a partially populated workspace can never exist.
|
||||
using var transaction = connection.BeginTransaction();
|
||||
foreach (string title in titles)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
@@ -45,6 +42,5 @@ public static class WorkspacePreset
|
||||
command.Parameters.AddWithValue("$now", now);
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
transaction.Commit();
|
||||
}
|
||||
}
|
||||
@@ -41,9 +41,43 @@ public sealed class WorkspaceSession : IDisposable
|
||||
/// <returns>The opened session; dispose it to release the lock and connection.</returns>
|
||||
/// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
|
||||
/// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception>
|
||||
/// <exception cref="WorkspaceDatabaseMissingException">.ykanban exists but its database file does not.</exception>
|
||||
public static WorkspaceSession Open(string folderPath)
|
||||
{
|
||||
WorkspaceLock workspaceLock = WorkspaceLock.Acquire(folderPath);
|
||||
|
||||
// Opening would otherwise create an empty database and show an empty board as if nothing was lost.
|
||||
string databasePath = WorkspacePaths.Database(folderPath);
|
||||
if (!File.Exists(databasePath))
|
||||
{
|
||||
workspaceLock.Dispose();
|
||||
throw new WorkspaceDatabaseMissingException(databasePath);
|
||||
}
|
||||
|
||||
return OpenLocked(folderPath, workspaceLock);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a workspace with its preset columns and opens it. The lock
|
||||
/// is taken right after .ykanban is created and is never released in
|
||||
/// between, so no other instance can interleave with the initialization.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The existing folder to initialize.</param>
|
||||
/// <returns>The opened session; dispose it to release the lock and connection.</returns>
|
||||
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
||||
/// <exception cref="WorkspaceLockException">Another instance holds the workspace lock.</exception>
|
||||
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
|
||||
public static WorkspaceSession Initialize(string folderPath) =>
|
||||
OpenLocked(folderPath, WorkspaceInitializer.InitializeLocked(folderPath, addPresetColumns: true));
|
||||
|
||||
/// <summary>
|
||||
/// Opens the repository under an already held lock; the lock is released if that fails.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder.</param>
|
||||
/// <param name="workspaceLock">The held workspace lock.</param>
|
||||
/// <returns>The opened session.</returns>
|
||||
private static WorkspaceSession OpenLocked(string folderPath, WorkspaceLock workspaceLock)
|
||||
{
|
||||
try
|
||||
{
|
||||
var repository = new WorkspaceRepository(folderPath);
|
||||
|
||||
+14
-11
@@ -1,31 +1,34 @@
|
||||
using System;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Templates;
|
||||
using YKanBan.ViewModels;
|
||||
|
||||
namespace YKanBan;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the view of a view model by naming convention: the type name with
|
||||
/// "ViewModel" replaced by "View". A missing view is a programming error; it
|
||||
/// shows a localized placeholder naming the type that was looked for.
|
||||
/// </summary>
|
||||
public class ViewLocator : IDataTemplate
|
||||
{
|
||||
|
||||
/// <inheritdoc/>
|
||||
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)
|
||||
string name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
|
||||
Type? type = Type.GetType(name);
|
||||
if (type is not null)
|
||||
{
|
||||
return (Control)Activator.CreateInstance(type)!;
|
||||
}
|
||||
|
||||
return new TextBlock { Text = "Not Found: " + name };
|
||||
return new TextBlock { Text = string.Format(YKanBan.Resources.Culture, YKanBan.Resources.Error_ViewNotFound, name) };
|
||||
}
|
||||
|
||||
public bool Match(object? data)
|
||||
{
|
||||
return data is ViewModelBase;
|
||||
}
|
||||
/// <inheritdoc/>
|
||||
public bool Match(object? data) => data is ViewModelBase;
|
||||
}
|
||||
@@ -107,10 +107,25 @@ public sealed partial class BoardViewModel : ViewModelBase
|
||||
/// <summary>
|
||||
/// Reloads the columns and the cards matching <see cref="ActiveFilter"/>.
|
||||
/// </summary>
|
||||
public void Refresh()
|
||||
/// <exception cref="Exception">Reading the workspace failed; the board is left unchanged.</exception>
|
||||
public void Refresh() => Load(ActiveFilter);
|
||||
|
||||
/// <summary>
|
||||
/// Reloads like <see cref="Refresh"/>, but reports a read failure in a
|
||||
/// message dialog instead of throwing.
|
||||
/// </summary>
|
||||
/// <returns><see langword="true"/> when the board was reloaded.</returns>
|
||||
public Task<bool> RefreshOrReportAsync() => TryLoadAsync(ActiveFilter);
|
||||
|
||||
/// <summary>
|
||||
/// Reloads the board with the given filter; the columns are only replaced
|
||||
/// once both queries have succeeded.
|
||||
/// </summary>
|
||||
/// <param name="filter">The search to apply; <see langword="null"/> shows every card.</param>
|
||||
private void Load(CompiledSearch? filter)
|
||||
{
|
||||
IReadOnlyList<ColumnModel> columns = _repository.GetColumns();
|
||||
ILookup<long, CardModel> cardsByColumn = _repository.GetCards(ActiveFilter).ToLookup(card => card.ColumnId);
|
||||
ILookup<long, CardModel> cardsByColumn = _repository.GetCards(filter).ToLookup(card => card.ColumnId);
|
||||
var sort = (CardSortOption)SelectedSort.Value;
|
||||
|
||||
ColumnModels = columns;
|
||||
@@ -121,9 +136,30 @@ public sealed partial class BoardViewModel : ViewModelBase
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reloads the board with the given filter and reports a read failure in a message dialog.
|
||||
/// </summary>
|
||||
/// <param name="filter">The search to apply; <see langword="null"/> shows every card.</param>
|
||||
/// <returns><see langword="true"/> when the board was reloaded.</returns>
|
||||
private async Task<bool> TryLoadAsync(CompiledSearch? filter)
|
||||
{
|
||||
try
|
||||
{
|
||||
Load(filter);
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
await _dialogs.ShowReadFailedAsync(exception);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses and runs the search box text; blank text shows every card. An
|
||||
/// invalid expression only shows the error dialog.
|
||||
/// invalid expression only shows the error dialog. The expression becomes
|
||||
/// <see cref="ActiveFilter"/> only once its query has succeeded, so a failed
|
||||
/// search leaves the previous result and later refreshes untouched.
|
||||
/// </summary>
|
||||
/// <returns>A task completing after the refresh or the error dialog.</returns>
|
||||
[RelayCommand]
|
||||
@@ -143,19 +179,24 @@ public sealed partial class BoardViewModel : ViewModelBase
|
||||
return;
|
||||
}
|
||||
|
||||
if (await TryLoadAsync(filter))
|
||||
{
|
||||
ActiveFilter = filter;
|
||||
Refresh();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Empties the search box and shows every card again.
|
||||
/// </summary>
|
||||
/// <returns>A task completing after the refresh.</returns>
|
||||
[RelayCommand]
|
||||
private void ClearSearch()
|
||||
private async Task ClearSearchAsync()
|
||||
{
|
||||
SearchText = "";
|
||||
if (await TryLoadAsync(null))
|
||||
{
|
||||
ActiveFilter = null;
|
||||
Refresh();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -168,7 +209,7 @@ public sealed partial class BoardViewModel : ViewModelBase
|
||||
var dialog = new ColumnEditorDialogViewModel(null, (title, description) => _repository.AddColumn(title, description));
|
||||
if (await _dialogs.ShowAsync(dialog))
|
||||
{
|
||||
RefreshAfterWrite();
|
||||
await RefreshAfterWriteAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,7 +237,7 @@ public sealed partial class BoardViewModel : ViewModelBase
|
||||
column, (title, description) => _repository.UpdateColumn(column.Id, title, description));
|
||||
if (await _dialogs.ShowAsync(dialog))
|
||||
{
|
||||
RefreshAfterWrite();
|
||||
await RefreshAfterWriteAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,9 +274,7 @@ public sealed partial class BoardViewModel : ViewModelBase
|
||||
var editor = CardEditorDialogViewModel.ForNewCard(
|
||||
_repository, _dialogs, columnId, _config.Confirmations.DiscardEdit);
|
||||
await _dialogs.ShowAsync(editor);
|
||||
|
||||
// Refresh even after a cancel: the nested picker may have created tags.
|
||||
RefreshAfterWrite();
|
||||
await RefreshAfterEditorAsync(editor);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -245,19 +284,40 @@ public sealed partial class BoardViewModel : ViewModelBase
|
||||
/// <returns>A task completing when the editor closes.</returns>
|
||||
internal async Task EditCardAsync(long cardId)
|
||||
{
|
||||
CardModel? card = _repository.GetCard(cardId);
|
||||
CardModel? card;
|
||||
try
|
||||
{
|
||||
card = _repository.GetCard(cardId);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
await _dialogs.ShowReadFailedAsync(exception);
|
||||
return;
|
||||
}
|
||||
|
||||
if (card is null)
|
||||
{
|
||||
Refresh();
|
||||
await RefreshOrReportAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
var editor = CardEditorDialogViewModel.ForExistingCard(
|
||||
_repository, _dialogs, card, _config.Confirmations.DiscardEdit);
|
||||
await _dialogs.ShowAsync(editor);
|
||||
RefreshAfterWrite();
|
||||
await RefreshAfterEditorAsync(editor);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes after the card editor closes, but only when it wrote something:
|
||||
/// a saved card, or a tag created in the nested picker even if the edit was
|
||||
/// cancelled. An editor that wrote nothing leaves the columns, and so their
|
||||
/// scroll positions, untouched.
|
||||
/// </summary>
|
||||
/// <param name="editor">The closed editor.</param>
|
||||
/// <returns>A task completing after the refresh, if any.</returns>
|
||||
private Task RefreshAfterEditorAsync(CardEditorDialogViewModel editor) =>
|
||||
editor.WroteToWorkspace ? RefreshAfterWriteAsync() : Task.CompletedTask;
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a card, asking first when that confirmation is enabled.
|
||||
/// </summary>
|
||||
@@ -314,17 +374,21 @@ public sealed partial class BoardViewModel : ViewModelBase
|
||||
await _dialogs.ShowMessageAsync(
|
||||
Resources.Error_Operation_Title, Resources.Error_Operation_Message, exception.Message);
|
||||
}
|
||||
RefreshAfterWrite();
|
||||
await RefreshAfterWriteAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes after a write and announces it.
|
||||
/// Refreshes after a write and announces it; a failed refresh is reported
|
||||
/// and not announced, so a broken workspace yields one read-failure dialog.
|
||||
/// </summary>
|
||||
private void RefreshAfterWrite()
|
||||
/// <returns>A task completing after the refresh.</returns>
|
||||
private async Task RefreshAfterWriteAsync()
|
||||
{
|
||||
if (await RefreshOrReportAsync())
|
||||
{
|
||||
Refresh();
|
||||
DataWritten?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the sort option and re-sorts the board.
|
||||
@@ -333,6 +397,8 @@ public sealed partial class BoardViewModel : ViewModelBase
|
||||
partial void OnSelectedSortChanged(OptionItem value)
|
||||
{
|
||||
_config.Sort.Card = (CardSortOption)value.Value;
|
||||
Refresh();
|
||||
|
||||
// A property setter cannot await; the refresh reports its own failures.
|
||||
_ = RefreshOrReportAsync();
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,12 @@ public sealed class TagBadgeViewModel : ViewModelBase
|
||||
/// </summary>
|
||||
public string Description => Tag.Description;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the badge tooltip: the description, or <see langword="null"/> (no
|
||||
/// tooltip at all) when the description is empty.
|
||||
/// </summary>
|
||||
public string? ToolTip => Tag.Description.Length > 0 ? Tag.Description : null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the badge fill: the tag's own color.
|
||||
/// </summary>
|
||||
|
||||
@@ -12,8 +12,8 @@ namespace YKanBan.ViewModels.Dialogs;
|
||||
/// The card editor — one unit of work. Title, content and the tag assignment
|
||||
/// are edited in memory and written together in a single transaction on
|
||||
/// confirmation; cancelling writes nothing about the card or its assignment.
|
||||
/// Confirming an existing card without effective changes writes nothing and
|
||||
/// keeps its timestamps. The only immediate write is the creation of a new tag
|
||||
/// Confirming without effective changes writes nothing: an existing card keeps
|
||||
/// its timestamps, and a new card left empty is not created. The only immediate write is the creation of a new tag
|
||||
/// in the nested tag picker (see <see cref="TagPickerDialogViewModel"/>).
|
||||
/// </summary>
|
||||
public sealed partial class CardEditorDialogViewModel : DialogViewModelBase
|
||||
@@ -113,10 +113,17 @@ public sealed partial class CardEditorDialogViewModel : DialogViewModelBase
|
||||
public ObservableCollection<TagBadgeViewModel> Tags { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the card written on confirmation; <see langword="null"/> until then.
|
||||
/// Gets the card written on confirmation; <see langword="null"/> until then,
|
||||
/// and after confirming a new card that was left empty.
|
||||
/// </summary>
|
||||
public CardModel? SavedCard { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether this edit session wrote anything: the card on confirmation,
|
||||
/// or a tag created in the nested picker (kept even when the edit is cancelled).
|
||||
/// </summary>
|
||||
public bool WroteToWorkspace { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the card title; the empty string means "no title".
|
||||
/// </summary>
|
||||
@@ -156,10 +163,23 @@ public sealed partial class CardEditorDialogViewModel : DialogViewModelBase
|
||||
[RelayCommand]
|
||||
private async Task AddTagAsync()
|
||||
{
|
||||
var picker = new TagPickerDialogViewModel(_repository, Tags.Select(tag => tag.Tag.Id).ToHashSet());
|
||||
if (await _dialogs.ShowAsync(picker) && picker.PickedTag is { } picked)
|
||||
TagPickerDialogViewModel picker;
|
||||
try
|
||||
{
|
||||
Tags.Add(new TagBadgeViewModel(picked));
|
||||
picker = new TagPickerDialogViewModel(_repository, Tags.Select(tag => tag.Tag.Id).ToHashSet());
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// The picker lists the tags as it opens; a read failure must not escape the command.
|
||||
await _dialogs.ShowReadFailedAsync(exception);
|
||||
return;
|
||||
}
|
||||
|
||||
bool picked = await _dialogs.ShowAsync(picker);
|
||||
WroteToWorkspace |= picker.CreatedTag;
|
||||
if (picked && picker.PickedTag is { } tag)
|
||||
{
|
||||
Tags.Add(new TagBadgeViewModel(tag));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,13 +191,13 @@ public sealed partial class CardEditorDialogViewModel : DialogViewModelBase
|
||||
private void RemoveTag(TagBadgeViewModel tag) => Tags.Remove(tag);
|
||||
|
||||
/// <summary>
|
||||
/// Writes the card in one transaction and closes; an unchanged existing card
|
||||
/// is not written at all.
|
||||
/// Writes the card in one transaction and closes; an unchanged card is not
|
||||
/// written at all, so a new card left empty is not created.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Confirm()
|
||||
{
|
||||
if (_existing is not null && !IsDirty)
|
||||
if (!IsDirty)
|
||||
{
|
||||
SavedCard = _existing;
|
||||
Close(true);
|
||||
@@ -190,6 +210,7 @@ public sealed partial class CardEditorDialogViewModel : DialogViewModelBase
|
||||
SavedCard = _existing is null
|
||||
? _repository.AddCard(_columnId, CardTitle, Content, tagIds)
|
||||
: _repository.UpdateCard(_existing.Id, CardTitle, Content, tagIds);
|
||||
WroteToWorkspace = true;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
@@ -18,8 +20,12 @@ public interface IDialogService
|
||||
/// Shows the system save-file dialog for a Markdown file.
|
||||
/// </summary>
|
||||
/// <param name="suggestedFileName">The proposed file name.</param>
|
||||
/// <returns>The chosen local path, or <see langword="null"/> when the user cancelled.</returns>
|
||||
Task<string?> PickSaveFilePathAsync(string suggestedFileName);
|
||||
/// <returns>
|
||||
/// A function opening the chosen file for writing, emptied first, or
|
||||
/// <see langword="null"/> when the user cancelled. Nothing is created or
|
||||
/// truncated until the function is called.
|
||||
/// </returns>
|
||||
Task<Func<Task<Stream>>?> PickSaveFileAsync(string suggestedFileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -47,4 +53,16 @@ public static class DialogServiceExtensions
|
||||
/// <returns>A task completing when the dialog closes.</returns>
|
||||
public static Task ShowMessageAsync(this IDialogService dialogs, string title, string message, string? details = null) =>
|
||||
dialogs.ShowAsync(new MessageDialogViewModel(title, message, details));
|
||||
|
||||
/// <summary>
|
||||
/// Reports that reading from the workspace failed, so the view may be stale.
|
||||
/// </summary>
|
||||
/// <param name="dialogs">The dialog service.</param>
|
||||
/// <param name="exception">The read failure; its untranslated message is shown as details.</param>
|
||||
/// <returns>A task completing when the dialog closes.</returns>
|
||||
public static Task ShowReadFailedAsync(this IDialogService dialogs, Exception exception)
|
||||
{
|
||||
Debug.WriteLine(exception);
|
||||
return dialogs.ShowMessageAsync(Resources.Error_Read_Title, Resources.Error_Read_Message, exception.Message);
|
||||
}
|
||||
}
|
||||
@@ -5,23 +5,27 @@ 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.
|
||||
/// confirmation-dialog toggles. A theme selection is previewed immediately;
|
||||
/// everything else waits until the user accepts. Cancelling or closing the
|
||||
/// window discards the changes and restores the theme the dialog opened with.
|
||||
/// </summary>
|
||||
public sealed partial class SettingsDialogViewModel : ViewModelBase
|
||||
{
|
||||
private readonly AppConfig _config;
|
||||
private readonly string _startupLanguage;
|
||||
private readonly Action<ThemeOption> _applyTheme;
|
||||
|
||||
/// <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)
|
||||
/// <param name="applyTheme">Applies a theme to the running app; defaults to <see cref="App.ApplyTheme"/>.</param>
|
||||
public SettingsDialogViewModel(AppConfig config, string startupLanguage, Action<ThemeOption>? applyTheme = null)
|
||||
{
|
||||
_config = config;
|
||||
_startupLanguage = startupLanguage;
|
||||
_applyTheme = applyTheme ?? App.ApplyTheme;
|
||||
|
||||
Languages =
|
||||
[
|
||||
@@ -63,7 +67,8 @@ public sealed partial class SettingsDialogViewModel : ViewModelBase
|
||||
private OptionItem? selectedLanguage;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the selected theme; applied when the dialog is accepted.
|
||||
/// Gets or sets the selected theme; applied to the running app as soon as it
|
||||
/// changes, and saved to the configuration when the dialog is accepted.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private OptionItem? selectedTheme;
|
||||
@@ -110,7 +115,6 @@ public sealed partial class SettingsDialogViewModel : ViewModelBase
|
||||
if (SelectedTheme is not null)
|
||||
{
|
||||
_config.Theme = (ThemeOption)SelectedTheme.Value;
|
||||
App.ApplyTheme(_config.Theme);
|
||||
}
|
||||
|
||||
_config.Confirmations.DeleteCard = ConfirmDeleteCard;
|
||||
@@ -119,6 +123,23 @@ public sealed partial class SettingsDialogViewModel : ViewModelBase
|
||||
_config.Confirmations.DiscardEdit = ConfirmDiscardEdit;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Discards the working values and restores the theme the dialog opened with.
|
||||
/// </summary>
|
||||
public void Cancel() => _applyTheme(_config.Theme);
|
||||
|
||||
/// <summary>
|
||||
/// Previews a theme selection on the running app.
|
||||
/// </summary>
|
||||
/// <param name="value">The new selection.</param>
|
||||
partial void OnSelectedThemeChanged(OptionItem? value)
|
||||
{
|
||||
if (value is not null)
|
||||
{
|
||||
_applyTheme((ThemeOption)value.Value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes the restart notice after a language selection change.
|
||||
/// </summary>
|
||||
|
||||
@@ -48,6 +48,11 @@ public sealed partial class TagPickerDialogViewModel : DialogViewModelBase
|
||||
/// </summary>
|
||||
public TagModel? PickedTag { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether <see cref="PickedTag"/> was newly created, i.e. written to the workspace.
|
||||
/// </summary>
|
||||
public bool CreatedTag { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the available tags matching <see cref="FilterText"/>.
|
||||
/// </summary>
|
||||
@@ -127,6 +132,7 @@ public sealed partial class TagPickerDialogViewModel : DialogViewModelBase
|
||||
try
|
||||
{
|
||||
PickedTag = _repository.AddTag(NewName, color, NewDescription);
|
||||
CreatedTag = true;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
|
||||
@@ -6,7 +6,7 @@ namespace YKanBan.ViewModels.ErrorPages;
|
||||
|
||||
/// <summary>
|
||||
/// The full-window page shown when a workspace cannot be opened or initialized:
|
||||
/// a schema newer than this build, an unopenable or damaged database, an I/O or
|
||||
/// 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.
|
||||
@@ -55,6 +55,7 @@ public sealed class OpenFailedPageViewModel : ViewModelBase
|
||||
{
|
||||
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),
|
||||
|
||||
@@ -105,15 +105,31 @@ public sealed partial class MainWindowViewModel : ViewModelBase
|
||||
/// 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)
|
||||
private void OpenWorkspace(string folderPath) => ShowWorkspace(folderPath, _services.OpenWorkspace(folderPath));
|
||||
|
||||
/// <summary>
|
||||
/// Switches the content to the normal view of an opened workspace.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder.</param>
|
||||
/// <param name="session">The opened workspace session.</param>
|
||||
private void ShowWorkspace(string folderPath, WorkspaceSession session)
|
||||
{
|
||||
try
|
||||
{
|
||||
WorkspaceSession session = _services.OpenWorkspace(folderPath);
|
||||
Content = new WorkspaceViewModel(session, ShowSettings, ShowAbout, _services.Config, _dialogs);
|
||||
}
|
||||
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
|
||||
/// Initializes the folder shown by the not-initialized page with its preset
|
||||
/// columns and opens the resulting workspace.
|
||||
/// </summary>
|
||||
/// <returns>A completed task once initialization has been attempted.</returns>
|
||||
@@ -126,9 +142,12 @@ public sealed partial class MainWindowViewModel : ViewModelBase
|
||||
|
||||
try
|
||||
{
|
||||
WorkspaceInitializer.Initialize(page.FolderPath);
|
||||
WorkspacePreset.AddPresetColumns(page.FolderPath);
|
||||
OpenWorkspace(page.FolderPath);
|
||||
ShowWorkspace(page.FolderPath, _services.InitializeWorkspace(page.FolderPath));
|
||||
}
|
||||
catch (WorkspaceLockException)
|
||||
{
|
||||
// Another instance got there first and holds the workspace: same page as at startup.
|
||||
Content = new LockConflictPageViewModel(page.FolderPath);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
|
||||
@@ -57,10 +57,12 @@ public sealed partial class TagsViewModel : ViewModelBase
|
||||
/// <summary>
|
||||
/// Reloads the tags with their usage counts.
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">Reading the workspace failed; the list is left unchanged.</exception>
|
||||
public void Refresh()
|
||||
{
|
||||
IReadOnlyList<(TagModel Tag, long UsageCount)> tags = _repository.GetTagsWithUsage();
|
||||
Tags.Clear();
|
||||
foreach ((TagModel tag, long usage) in _repository.GetTagsWithUsage())
|
||||
foreach ((TagModel tag, long usage) in tags)
|
||||
{
|
||||
Tags.Add(new TagRowViewModel(this, tag, usage));
|
||||
}
|
||||
@@ -68,6 +70,25 @@ public sealed partial class TagsViewModel : ViewModelBase
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reloads like <see cref="Refresh"/>, but reports a read failure in a
|
||||
/// message dialog instead of throwing.
|
||||
/// </summary>
|
||||
/// <returns><see langword="true"/> when the list was reloaded.</returns>
|
||||
public async Task<bool> RefreshOrReportAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
Refresh();
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
await _dialogs.ShowReadFailedAsync(exception);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the new-tag dialog.
|
||||
/// </summary>
|
||||
@@ -81,7 +102,7 @@ public sealed partial class TagsViewModel : ViewModelBase
|
||||
(name, color, description) => _repository.AddTag(name, color, description));
|
||||
if (await _dialogs.ShowAsync(dialog))
|
||||
{
|
||||
AfterWrite();
|
||||
await AfterWriteAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,7 +119,7 @@ public sealed partial class TagsViewModel : ViewModelBase
|
||||
(name, color, description) => _repository.UpdateTag(tag.Id, name, color, description));
|
||||
if (await _dialogs.ShowAsync(dialog))
|
||||
{
|
||||
AfterWrite();
|
||||
await AfterWriteAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,15 +151,19 @@ public sealed partial class TagsViewModel : ViewModelBase
|
||||
await _dialogs.ShowMessageAsync(
|
||||
Resources.Error_Operation_Title, Resources.Error_Operation_Message, exception.Message);
|
||||
}
|
||||
AfterWrite();
|
||||
await AfterWriteAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reloads the list and tells the board that tags changed.
|
||||
/// Reloads the list and tells the board that tags changed; a failed reload
|
||||
/// is reported and not announced.
|
||||
/// </summary>
|
||||
private void AfterWrite()
|
||||
/// <returns>A task completing after the reload.</returns>
|
||||
private async Task AfterWriteAsync()
|
||||
{
|
||||
if (await RefreshOrReportAsync())
|
||||
{
|
||||
Refresh();
|
||||
TagsChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,8 +45,8 @@ public sealed partial class WorkspaceViewModel : ViewModelBase
|
||||
_dialogs = dialogs;
|
||||
Board = new BoardViewModel(session.Repository, config, dialogs);
|
||||
Tags = new TagsViewModel(session.Repository, config, dialogs);
|
||||
Board.DataWritten += (_, _) => Tags.Refresh();
|
||||
Tags.TagsChanged += (_, _) => Board.Refresh();
|
||||
Board.DataWritten += async (_, _) => await Tags.RefreshOrReportAsync();
|
||||
Tags.TagsChanged += async (_, _) => await Board.RefreshOrReportAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -96,18 +96,22 @@ public sealed partial class WorkspaceViewModel : ViewModelBase
|
||||
private async Task ExportAsync()
|
||||
{
|
||||
DateTimeOffset exportedAt = DateTimeOffset.Now;
|
||||
string? path = await _dialogs.PickSaveFilePathAsync(MarkdownExporter.BuildFileName(WorkspaceName, exportedAt));
|
||||
if (path is null)
|
||||
try
|
||||
{
|
||||
Func<Task<Stream>>? openTarget =
|
||||
await _dialogs.PickSaveFileAsync(MarkdownExporter.BuildFileName(WorkspaceName, exportedAt));
|
||||
if (openTarget is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Read everything before opening the target, so a failed read leaves an existing file untouched.
|
||||
WorkspaceRepository repository = Session.Repository;
|
||||
string markdown = MarkdownExporter.Export(
|
||||
WorkspaceName, repository.GetColumns(), repository.GetCards(), repository.GetTagsWithUsage(), exportedAt);
|
||||
await File.WriteAllTextAsync(path, markdown, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
await using Stream stream = await openTarget();
|
||||
await using var writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
await writer.WriteAsync(markdown);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
|
||||
@@ -52,7 +52,7 @@ public sealed class DialogService : IDialogService
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task<string?> PickSaveFilePathAsync(string suggestedFileName)
|
||||
public async Task<Func<Task<Stream>>?> PickSaveFileAsync(string suggestedFileName)
|
||||
{
|
||||
if (!_owners.TryPeek(out Window? owner))
|
||||
{
|
||||
@@ -69,7 +69,28 @@ public sealed class DialogService : IDialogService
|
||||
new FilePickerFileType(YKanBan.Resources.Export_FileTypeMarkdown) { Patterns = ["*.md"] },
|
||||
],
|
||||
});
|
||||
return file?.TryGetLocalPath();
|
||||
if (file is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// A local file is replaced through the file system; a target without a
|
||||
// local path (a sandboxed or virtual location) is written through the
|
||||
// storage provider, emptied first because it may already have content.
|
||||
string? localPath = file.TryGetLocalPath();
|
||||
if (localPath is not null)
|
||||
{
|
||||
return () => Task.FromResult<Stream>(new FileStream(localPath, FileMode.Create, FileAccess.Write));
|
||||
}
|
||||
return async () =>
|
||||
{
|
||||
Stream stream = await file.OpenWriteAsync();
|
||||
if (stream.CanSeek)
|
||||
{
|
||||
stream.SetLength(0);
|
||||
}
|
||||
return stream;
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -45,7 +45,7 @@
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="board:TagBadgeViewModel">
|
||||
<Border Background="{Binding Background}" CornerRadius="10" Padding="8,2,4,2"
|
||||
Margin="0,0,6,6" ToolTip.Tip="{Binding Description}">
|
||||
Margin="0,0,6,6" ToolTip.Tip="{Binding ToolTip}">
|
||||
<StackPanel Orientation="Horizontal" Spacing="2">
|
||||
<TextBlock Text="{Binding Name}" Foreground="{Binding Foreground}"
|
||||
VerticalAlignment="Center" FontSize="12"/>
|
||||
|
||||
@@ -11,11 +11,12 @@
|
||||
|
||||
<StackPanel Margin="20" Spacing="16">
|
||||
<TextBlock Text="{Binding Message}" TextWrapping="Wrap"/>
|
||||
<!-- Every confirmation guards a destructive action, so Enter answers with the safe choice. -->
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||
<Button Content="{Binding ConfirmLabel}" Command="{Binding ConfirmCommand}"
|
||||
Classes="Danger" MinWidth="90" IsDefault="True"/>
|
||||
Classes="Danger" MinWidth="90"/>
|
||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Command="{Binding CancelCommand}"
|
||||
MinWidth="90" IsCancel="True"/>
|
||||
MinWidth="90" IsDefault="True" IsCancel="True"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</dialogs:DialogWindow>
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Diagnostics;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
@@ -85,6 +86,12 @@ public class DialogWindow : Window
|
||||
{
|
||||
await _viewModel.RequestCancelAsync();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// An async void handler must not let a failure escape and end the
|
||||
// process; the dialog simply stays open.
|
||||
Debug.WriteLine(exception);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_cancelPending = false;
|
||||
|
||||
@@ -6,6 +6,8 @@ namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class SettingsDialog : Window
|
||||
{
|
||||
private bool _accepted;
|
||||
|
||||
public SettingsDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
@@ -15,9 +17,24 @@ public partial class SettingsDialog : Window
|
||||
private void OnOkClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
(DataContext as SettingsDialogViewModel)?.Accept();
|
||||
_accepted = true;
|
||||
Close(true);
|
||||
}
|
||||
|
||||
/// <summary>Closes without applying anything.</summary>
|
||||
private void OnCancelClick(object? sender, RoutedEventArgs e) => Close(false);
|
||||
|
||||
/// <summary>
|
||||
/// Restores the previewed theme on every close that did not accept,
|
||||
/// including the title-bar close button and Escape.
|
||||
/// </summary>
|
||||
/// <param name="e">The event arguments.</param>
|
||||
protected override void OnClosed(EventArgs e)
|
||||
{
|
||||
if (!_accepted)
|
||||
{
|
||||
(DataContext as SettingsDialogViewModel)?.Cancel();
|
||||
}
|
||||
base.OnClosed(e);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
mc:Ignorable="d" d:DesignWidth="1000" d:DesignHeight="640"
|
||||
x:Class="YKanBan.Views.MainWindow"
|
||||
x:DataType="vm:MainWindowViewModel"
|
||||
Icon="/Assets/avalonia-logo.ico"
|
||||
Icon="/Assets/ykanban.ico"
|
||||
Title="{Binding Title}"
|
||||
Width="1000" Height="640" MinWidth="720" MinHeight="480">
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<ApplicationIcon>Assets\ykanban.ico</ApplicationIcon>
|
||||
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -39,7 +40,6 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="11.3.22" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="11.3.22" />
|
||||
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.22" />
|
||||
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.3.22" />
|
||||
<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
|
||||
<PackageReference Include="Avalonia.Diagnostics" Version="11.3.22">
|
||||
|
||||
+11
-5
@@ -14,7 +14,7 @@
|
||||
### A1 语言切换重启生效
|
||||
|
||||
- [ ] 设置 → 语言改为简体中文 → 显示"重启后生效"提示;当前界面**不**变化
|
||||
- [ ] 确认关闭后,退出程序 → `app.json` 中 `Language` 为 `zh-Hans`
|
||||
- [ ] 确认关闭后,退出程序 → `app.json` 中 `"language"` 为 `"zh-Hans"`
|
||||
- [ ] 重启 → 全部界面文本(顶部区、两个 tab、各模态、错误页、排序项、确认对话框)为中文,无残留英文硬编码
|
||||
- [ ] 切回英文 → 重启后恢复英文
|
||||
- [ ] 中文下新初始化的工作区预置列为 待办 / 进行中 / 已完成;切回英文后这些列名**不变**(已是数据)
|
||||
@@ -30,7 +30,8 @@
|
||||
|
||||
### A3 主题三态切换
|
||||
|
||||
- [ ] 设置 → 主题 亮色 / 暗色 / 跟随系统 依次切换:**即时生效**,无重启提示
|
||||
- [ ] 设置 → 主题 亮色 / 暗色 / 跟随系统 依次切换:下拉框一选中就**即时生效**(无需点确认),无重启提示
|
||||
- [ ] 切换主题后点取消、按 Esc 或点标题栏关闭:恢复为打开设置时的主题;重启后仍是原主题
|
||||
- [ ] 每种主题下检查:主窗口、看板列与卡片、标签 tab、全部模态、全部错误页颜色完整切换,无亮底暗字/暗底亮字残留
|
||||
- [ ] 标签徽章在两种主题下均显示原色(§5.9 例外),文字颜色保持可读
|
||||
- [ ] 跟随系统:程序运行中切换 Windows 深浅色 → 程序跟随变化
|
||||
@@ -40,13 +41,14 @@
|
||||
|
||||
- [ ] 同时打开两个实例(不同工作区)。实例 1 改排序,实例 2 改列宽;先关实例 1、后关实例 2 → `app.json` 为实例 2 的完整设置(后退出者覆盖,实例 1 的排序改动丢失——已接受)
|
||||
- [ ] 打开两个实例,只在实例 1 改设置;先关实例 1,再关**未改过设置**的实例 2 → `app.json` 保持实例 1 写入的内容(未改设置的实例不写盘)
|
||||
- [ ] 删除 `app.json`,打开设置、不改任何项直接确认后退出 → `app.json` 不被创建;改一项再改回原值后退出 → `app.json` 被写出(脏标记按"改动过"判定)
|
||||
- [ ] 处于错误页(例如参数错误页)的实例退出时不写 `app.json`(可先删除 `app.json`,退出后确认文件未被创建)
|
||||
- [ ] `app.json` 写成非法 JSON → 启动正常、使用默认值,生成 `app.json.bak`;改一次设置退出后 `app.json` 恢复为合法内容
|
||||
- [ ] `app.json` 中单个字段非法(如 `"Theme": "pink"`、列宽 `9999`)→ 仅该字段回退默认,其余设置保留,不生成 `.bak`
|
||||
- [ ] `app.json` 中单个字段非法(如 `"theme": "pink"`、列宽 `"custom-pixels": 9999`、类型不符如 `"delete-card": 0`、`"custom-pixels": "500"`)→ 仅该字段回退默认,其余设置保留,不生成 `.bak`
|
||||
|
||||
## B. 启动与错误页(M4 / M4R)
|
||||
|
||||
- [ ] 无参数、两个参数、`--help`、`-x`、空字符串参数 → 参数错误页,显示 `Usage: ykanban <path>`
|
||||
- [ ] 无参数、两个参数、`--help`、`-x`、空字符串参数、纯空格参数 → 参数错误页,显示 `Usage: ykanban <path>`
|
||||
- [ ] 不存在的路径、指向文件的路径 → 目录不存在页
|
||||
- [ ] 相对路径(如 `ykanban .`)按当前目录解析
|
||||
- [ ] 无 `.ykanban` 的文件夹 → 未初始化页;点"初始化"后进入看板,预置三列
|
||||
@@ -54,6 +56,7 @@
|
||||
- [ ] 同一工作区开第二个实例 → 锁冲突页,无任何操作按钮;关闭第一个实例后可正常打开
|
||||
- [ ] 工作区数据库 `user_version` 改为更高值 → 打开失败页,提示版本过新,英文详情可选中复制
|
||||
- [ ] 把 `ykanban.db` 换成垃圾内容 → 打开失败页(数据库无法打开/损坏)
|
||||
- [ ] 关闭程序后删除 `.ykanban/ykanban.db`(及 -wal / -shm)→ 打开失败页,提示数据库缺失;`.ykanban` 中**不会**出现新建的空库
|
||||
- [ ] 窗口标题:正常时 `工作区名 - YKanBan`,错误页时仅 `YKanBan`
|
||||
- [ ] 顶部区:工作区名 + 小一号完整路径;右侧 导出 / 设置 / 关于 同排
|
||||
|
||||
@@ -61,7 +64,9 @@
|
||||
|
||||
- [ ] 新建列、编辑列(标题 + 描述);空标题、重名(含仅大小写不同,如 `Done` / `done`)→ 模态内提示错误,模态不关、输入保留
|
||||
- [ ] 删除列:确认框提示将删除 N 张卡片;确认后列与卡片一并删除
|
||||
- [ ] 各类确认框(删除卡片 / 列 / 标签、丢弃编辑)弹出后直接按回车 → 等同取消,不执行删除或丢弃
|
||||
- [ ] 新建卡片、点击卡片编辑:标题可空;内容多行;`#id` / 创建时间 / 修改时间只读显示(新建时不显示)
|
||||
- [ ] 新建卡片什么都不填(标题、内容、标签均空)直接确认:不产生卡片;只加一个标签再确认:产生无标题卡片
|
||||
- [ ] 编辑确认但内容未变 → 修改时间不变;改动后确认 → 修改时间刷新
|
||||
- [ ] 有未保存改动时取消或点标题栏关闭 → 丢弃确认(开关开启时)
|
||||
- [ ] 卡片菜单"移动到列":卡片移动,修改时间**不**变
|
||||
@@ -71,6 +76,7 @@
|
||||
- [ ] 列宽:窄 240 / 标准 320 / 宽 480 / 手动 160–720;全局生效,重启保持
|
||||
- [ ] 排序:id 升序 / 最后修改时间降序 / 标题升序(空标题在前);只影响卡片,列始终 id 序;重启保持
|
||||
- [ ] 大数据量:用脚本向一列灌入约 10000 张卡片,滚动流畅、打开工作区无明显卡顿(虚拟化)
|
||||
- [ ] 长列滚动到中部后打开某张卡片,不改动就取消或确认 → 各列滚动位置不变(未写库不刷新看板)
|
||||
- [ ] 所有模态在父窗口居中;使用系统原生标题栏
|
||||
- [ ] 打开带输入框的模态时,第一个输入框自动获得焦点并全选
|
||||
|
||||
@@ -98,5 +104,5 @@
|
||||
- [ ] 产物:`YKanBan-<版本>-win-x64.zip`、`-linux-x64.tar.gz`、`-osx-x64.tar.gz`、`-osx-arm64.tar.gz`
|
||||
- [ ] Windows:解压后 `YKanBan.exe <path>` 可直接运行(自包含,无需安装 .NET)
|
||||
- [ ] Linux:解压后 `./YKanBan <path>` 可运行(可执行位保留)
|
||||
- [ ] macOS:解除隔离后 `open -a YKanBan --args <path>` 与直接运行包内可执行文件均可用;双击 `.app` 只显示参数错误页
|
||||
- [ ] macOS:解除隔离后 `open -n -a YKanBan --args <绝对路径>` 与直接运行包内可执行文件均可用;双击 `.app` 只显示参数错误页
|
||||
- [ ] 故意让某平台测试失败 → 该 RID 无产物,其余 RID 不受影响
|
||||
+21
-13
@@ -16,6 +16,7 @@
|
||||
- 网络共享明确不支持;命令行参数边界;macOS 无参启动行为写入文档(§2.3、§4.1、附录)
|
||||
- 补充:导出转义规则、卡片列表虚拟化、模态窗口 FlowDirection、`Resources` 类名使用规则、CI osx-x64 运行器(§5、§7、§8)
|
||||
- 依赖:Avalonia 11.3.6 → 11.3.22,Semi.Avalonia 11.2.1.10 → 11.3.22(§7)
|
||||
- 实现回补:搜索括号嵌套上限 64 层、单个表达式至多 256 个原子,空短语、短语紧贴文本、`key:` 后空白均为非法(§6.1、§6.2);导出表格单元格转义 `\`、默认文件名剔除非法字符(§5.8);初始化中途锁冲突进锁冲突页、数据库文件缺失不静默新建(§4.4);app.json 读不出 / 备份写不出 / 退出写盘失败均不阻断启动与退出(§4.3);主题下拉选中即预览、取消恢复(§5.6);空白新卡片确认不创建(§5.4);app.json 脏标记按"改动过"判定(改回原值仍写盘),字段类型不符不做隐式转换(§4.3);确认对话框回车默认取消(§5.5)
|
||||
- 里程碑:标注 M0–M4 已完成,新增 **M4R(v1.9 回补)**(§9)
|
||||
|
||||
## 1. 项目概述
|
||||
@@ -122,7 +123,7 @@ card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
- 恰好一个位置参数为合法;相对路径以进程当前工作目录解析为绝对路径
|
||||
- 无参数、多于一个参数、或参数以 `-` 开头(含 `--help` 等任何选项形式)→ **参数错误页**
|
||||
- 路径不存在或存在但不是目录 → 目录不存在页
|
||||
- macOS 双击 `.app` 时无参数,只会显示参数错误页——已接受(纯命令行定位);USAGE.md 说明 macOS 启动方式(`open -a YKanBan --args <path>` 或直接运行包内可执行文件)
|
||||
- macOS 双击 `.app` 时无参数,只会显示参数错误页——已接受(纯命令行定位);USAGE.md 说明 macOS 启动方式:`open -n -a YKanBan --args <绝对路径>` 或直接运行包内可执行文件(`-n` 保证已有实例运行时仍另起实例;经 `open` 启动时当前目录为 `/`,故须绝对路径)
|
||||
- 窗口标题:`工作区名 - YKanBan`;无有效工作区(错误页状态)时仅 `YKanBan`
|
||||
|
||||
### 4.2 连接管理
|
||||
@@ -136,11 +137,13 @@ card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
|
||||
- 强类型根对象 `AppConfig` 整体序列化,根含 `"version": 1` 迁移钩子
|
||||
- 字段:语言(`Language`:`"en"` 默认 / `"zh-Hans"`)、主题(`Theme`:`"follow-system"` 默认 / `"light"` / `"dark"`)、卡片排序选择(`"id"` 默认 / `"updated-at"` / `"title"`)、列宽、四类确认开关;枚举值序列化为 kebab-case 字符串
|
||||
- 写入时机:**应用退出时,仅当本实例在会话内修改过任一设置(脏标记)才整体写盘**(直接写,不做原子替换);错误页状态的实例、未改过设置的实例退出时不写。多实例均改过设置时后退出者覆盖(已接受);崩溃/断电丢失当次会话的设置变更(已接受:配置低价值)
|
||||
- 写入时机:**应用退出时,仅当本实例在会话内修改过任一设置(脏标记)才整体写盘**(直接写,不做原子替换);脏标记按"是否改动过"判定:设置项被赋予与当前不同的值即置脏,改后又改回原值仍为脏;赋予相同值(如设置模态未改任何项直接确认)不置脏;读取时的字段回退不置脏;错误页状态的实例、未改过设置的实例退出时不写。多实例均改过设置时后退出者覆盖(已接受);崩溃/断电丢失当次会话的设置变更(已接受:配置低价值)
|
||||
- 读取:
|
||||
- 文件缺失 → 默认值启动照常运行(下次脏退出时自然创建)
|
||||
- JSON 本身无法解析 → 备份为 `app.json.bak`(覆盖旧备份)→ 以默认值启动
|
||||
- JSON 完好但个别字段非法(未知枚举值、未知语言、列宽越界 160–720、类型不符等)→ **仅该字段回退默认值**,其余字段保留,不生成备份
|
||||
- JSON 完好但个别字段非法(未知枚举值、未知语言、列宽越界 160–720、类型不符等;类型须严格匹配,不做隐式转换——如布尔字段写 `0` / `"false"`、整数字段写 `"500"` / `500.0` 均视为非法)→ **仅该字段回退默认值**,其余字段保留,不生成备份
|
||||
- 文件存在但无法读取(IO / 权限错误)→ 以默认值启动;`.bak` 备份写不出时跳过备份,照常以默认值启动
|
||||
- 退出写盘失败(IO / 权限错误)→ 忽略,等同丢失当次会话的设置变更;无论写盘成败都释放工作区锁与连接
|
||||
|
||||
### 4.4 全窗口错误页体系
|
||||
|
||||
@@ -151,10 +154,11 @@ card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
| 参数错误页 | 参数不合法(见 §4.1) | 参数错误提示 + 正确用法说明(`ykanban <path>`) |
|
||||
| 目录不存在页 | 参数路径不存在或不是目录 | 提示 |
|
||||
| 未初始化页 | 路径存在但无 `.ykanban` | 提示 + 初始化按钮(唯一带操作的错误页) |
|
||||
| 锁冲突页 | 锁文件被占用 | 仅提示,无任何操作 |
|
||||
| 工作区打开失败页 | schema 版本高于程序支持版本;数据库无法打开/损坏;IO 或权限错误(含初始化失败) | 按异常类型显示本地化提示 + 只读可复制的英文异常详情;无其他操作 |
|
||||
| 锁冲突页 | 锁文件被占用(含点击初始化时锁已被其他实例抢先持有) | 仅提示,无任何操作 |
|
||||
| 工作区打开失败页 | schema 版本高于程序支持版本;`.ykanban` 存在但 `ykanban.db` 缺失;数据库无法打开/损坏;IO 或权限错误(含初始化失败) | 按异常类型显示本地化提示 + 只读可复制的英文异常详情;无其他操作 |
|
||||
|
||||
- 未初始化页点击初始化失败 → 切换至工作区打开失败页
|
||||
- 未初始化页点击初始化失败 → 切换至工作区打开失败页;例外:失败原因为锁冲突(其他实例抢先持有锁)→ 切换至锁冲突页
|
||||
- `.ykanban` 存在但 `ykanban.db` 缺失 → 工作区打开失败页,提示从备份恢复或删除 `.ykanban` 后重新初始化;**绝不静默新建空库**
|
||||
- 未被识别的异常类型归入工作区打开失败页的通用提示
|
||||
|
||||
正常视图 = 顶部显示区域 + TabControl(见 §5)。
|
||||
@@ -197,20 +201,20 @@ card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
- 字段:标题(可空,空串 = 无标题)、内容(多行)、标签区、只读 `#id` / 创建时间 / 修改时间(新增时未生成则不显示)
|
||||
- 底部:确认(当前数据一次性写入数据库)/ 取消(丢弃更改)
|
||||
- 编辑对话框是一个工作单元:确认时一次性落库(单事务,见 §3),取消不产生任何卡片/指派写入;其余操作(删除、移动等)仍即时写库
|
||||
- 确认时内容无变化 → 不写库、不刷新时间戳
|
||||
- 确认时内容无变化 → 不写库、不刷新时间戳;新建卡片时即标题、内容、标签均为空 → 确认不创建卡片(等同取消)
|
||||
- 标签指派:编辑模态标签区显示已指派标签(各带 × 移除),"添加标签"按钮弹**嵌套模态** = 已有标签搜索/列表 + 新建标签入口,选中即添加,可反复打开继续添加下一个
|
||||
- **例外**:嵌套模态中新建的标签**立即写入 `tags` 表**(标签是全局实体);外层编辑取消时仅丢弃指派关系,新建的标签保留(与"tag 永不自动清理"一致)
|
||||
|
||||
### 5.5 确认对话框开关
|
||||
|
||||
按类型分设独立开关:删除卡片 / 删除列 / 删除标签 / 丢弃编辑确认,承载于设置模态,存 app.json。
|
||||
按类型分设独立开关:删除卡片 / 删除列 / 删除标签 / 丢弃编辑确认,承载于设置模态,存 app.json。确认对话框的默认按钮(回车)为"取消",执行操作须显式点击确认按钮。
|
||||
|
||||
### 5.6 设置模态
|
||||
|
||||
入口 = 顶部显示区域右侧"设置"按钮,承载各类全局设置:
|
||||
|
||||
- 语言选择(英文 / 简体中文),切换后显示"重启后生效"提示(提示文本本身为资源键)
|
||||
- 主题选择(亮色 / 暗色 / 跟随系统),切换后**即时生效**,无重启提示(与语言项的行为差异)
|
||||
- 主题选择(亮色 / 暗色 / 跟随系统),下拉框选中即**即时生效**(预览),无重启提示(与语言项的行为差异);点确认才写入配置,取消或关闭设置模态则恢复打开时的主题
|
||||
- 四类确认开关(见 §5.5)
|
||||
|
||||
### 5.7 关于模态
|
||||
@@ -219,7 +223,7 @@ card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
|
||||
### 5.8 导出
|
||||
|
||||
- 点击后弹系统保存文件对话框,默认文件名按当前语言生成(模式为资源键,**精确到秒**):英文 `MyRepo-export-20260930-142537.md`;中文 `MyRepo-导出-20260930-142537.md`
|
||||
- 点击后弹系统保存文件对话框,默认文件名按当前语言生成(模式为资源键,**精确到秒**):英文 `MyRepo-export-20260930-142537.md`;中文 `MyRepo-导出-20260930-142537.md`;工作区名中任一平台的文件名非法字符(`<>:"/\|?*` 与控制字符)剔除,剔除后为空(如工作区位于 `/`)则用 `YKanBan`
|
||||
- 人类可读格式,无回导需求;模板文本直接读取 ResX 资源(见 §8),导出语言跟随当前界面语言
|
||||
- 导出范围为工作区全量数据,不受当前搜索筛选与卡片排序选项影响:列按 id 升序,列内卡片按 id 升序
|
||||
- 全文时间戳(导出时间与卡片创建/修改时间)格式随语言:英文 `yyyy-MM-dd HH:mm:ss`;中文 `yyyy年M月d日 HH:mm`
|
||||
@@ -244,7 +248,7 @@ card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
- 空列也保留(体现看板结构);无标题卡片以 `### #61` 呈现
|
||||
- 转义规则:
|
||||
- 标签名以行内代码呈现,定界反引号数量 = 名称内最长连续反引号串长度 + 1(名称以反引号开头/结尾时两侧加空格)
|
||||
- 标签总表单元格内 `|` → `\|`,换行 → `<br>`
|
||||
- 标签总表单元格内 `\` → `\\`(先于 `|` 处理,否则 `a\|b` 中的 `|` 会被当成列分隔符),`|` → `\|`,换行 → `<br>`
|
||||
- 卡片正文与列 description **原样输出**(接受其中 Markdown 结构干扰文档层级,已接受)
|
||||
|
||||
### 5.9 主题(亮 / 暗 / 跟随系统)
|
||||
@@ -277,10 +281,11 @@ key := tag | title | content | id | column
|
||||
value := word | phrase (tag/title/content/column)
|
||||
| '#'? digit+ (id:十进制正整数,可带前缀 #)
|
||||
word := 一个或多个字符,不含空白及 ( ) " : \ ;且不等于 AND / OR
|
||||
phrase := '"' 任意文本 '"' (内部支持转义:\" → 字面引号,\\ → 字面反斜杠)
|
||||
phrase := '"' 一个或多个字符 '"' (内部支持转义:\" → 字面引号,\\ → 字面反斜杠)
|
||||
```
|
||||
|
||||
- 裸词中出现 `:` 时其左侧必须是合法 key,否则为"未知限定符"错误;含 `:` `(` `)` `\` 等字符的搜索值须用引号(如 `"http://x"`)
|
||||
- 短语不得为空(`""`);短语与相邻裸词/短语之间须有空白或括号(`a"b"`、`"a"b`、`"a""b"` 非法),唯一例外是紧贴 key 的限定符值 `key:"…"`;`key:` 与短语值之间不得有空白(`tag: "x"` 非法)
|
||||
|
||||
### 6.2 语义
|
||||
|
||||
@@ -291,9 +296,12 @@ phrase := '"' 任意文本 '"' (内部支持转义:\" → 字面引号,
|
||||
- 短语内部转义:`\"` → 字面引号,`\\` → 字面反斜杠;搜索含空格/保留字符/字面 `AND` 等特殊标签名时,用(必要时转义的)引号值(写入文档)
|
||||
- **严格校验**:非法表达式弹出错误对话框,不执行搜索。非法集合:
|
||||
- 括号不配对
|
||||
- 括号嵌套超过 64 层(防止递归解析栈溢出;顺序并列的括号组不计入深度)
|
||||
- 原子(裸词、短语、限定符)超过 256 个(编译出的 SQL 把全部原子串成一个表达式,SQLite 表达式深度上限为 1000)
|
||||
- 运算符悬空(`bug AND`)、连续运算符(`a AND OR b`)
|
||||
- 限定符无值(`tag:`)、限定符值为裸 `AND`/`OR`(`tag:AND`,须写 `tag:"AND"`)
|
||||
- 短语引号未闭合、无效转义(`tag:"a\x"`)、裸词中出现 `\`
|
||||
- 空短语(`""`、`tag:""`);短语紧贴其他文本(`a"b"`、`"a"b`);`key:` 与短语值之间有空白(`tag: "x"`)
|
||||
- 未知限定符 key(合法 key 仅 tag / title / content / id / column)
|
||||
- `id:` 值不是十进制正整数(`id:abc`、`id:0`、`id:"61"`)
|
||||
- 错误对话框:模态、父窗口居中;文案 = 资源模板"查询表达式有误,详情:{0}"(i18n),{0} 处拼接解析器返回的**非 i18n 英文错误描述串**(对位置信息无要求)
|
||||
@@ -398,4 +406,4 @@ phrase := '"' 任意文本 '"' (内部支持转义:\" → 字面引号,
|
||||
2. 备份/迁移必须同时复制 `ykanban.db`、`ykanban.db-wal`、`ykanban.db-shm` 三个文件;不支持将工作区放在网络共享(SMB/NFS)上
|
||||
3. 搜索语法全文(文法、语义、`word` 字符集、转义规则、保留字、大小写折叠、严格校验与非法表达式清单、错误对话框行为,见 §6)
|
||||
4. 命令行启动规则(`ykanban <path>`;参数规则与各错误页,见 §4.1)
|
||||
5. macOS 启动方式(`open -a YKanBan --args <path>` 或直接运行包内可执行文件;双击 `.app` 只会显示参数错误页)
|
||||
5. macOS 启动方式(`open -n -a YKanBan --args <绝对路径>` 或直接运行包内可执行文件;`-n` 保证另起实例,`open` 启动时当前目录为 `/` 故须绝对路径;双击 `.app` 只会显示参数错误页)
|
||||
@@ -8,6 +8,8 @@
|
||||
<string>YKanBan</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>cn.blumia.code.yyc12345.ykanban</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>ykanban.icns</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>YKanBan</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
|
||||
Binary file not shown.
+18
-7
@@ -5,7 +5,7 @@
|
||||
#
|
||||
# win-x64 -> YKanBan-<version>-win-x64.zip (folder YKanBan-<version>-win-x64/)
|
||||
# linux-x64 -> YKanBan-<version>-linux-x64.tar.gz (folder YKanBan-<version>-linux-x64/)
|
||||
# osx-* -> YKanBan-<version>-<rid>.tar.gz (YKanBan.app bundle, ad-hoc signed when codesign exists)
|
||||
# osx-* -> YKanBan-<version>-<rid>.tar.gz (YKanBan.app bundle, ad-hoc signed when possible)
|
||||
#
|
||||
# tar.gz keeps the executable bit, which a plain zip artifact upload would lose.
|
||||
set -euo pipefail
|
||||
@@ -28,9 +28,15 @@ trap 'rm -rf "$staging"' EXIT
|
||||
case "$rid" in
|
||||
win-*)
|
||||
cp -R "$publish_dir" "$staging/$name"
|
||||
# Compress-Archive is available on every Windows host, unlike zip.
|
||||
powershell -NoProfile -Command \
|
||||
"Compress-Archive -Path '$(cygpath -w "$staging/$name" 2>/dev/null || echo "$staging/$name")' -DestinationPath '$(cygpath -w "$output_dir/$name.zip" 2>/dev/null || echo "$output_dir/$name.zip")' -Force"
|
||||
rm -f "$output_dir/$name.zip"
|
||||
# 7-Zip ships on the Windows runners and writes '/' entry separators;
|
||||
# Windows PowerShell 5.1's Compress-Archive writes '\', which breaks
|
||||
# extraction outside Windows.
|
||||
if ! command -v 7z > /dev/null 2>&1; then
|
||||
echo "7z not found" >&2
|
||||
exit 1
|
||||
fi
|
||||
(cd "$staging" && 7z a -tzip -bso0 -bsp0 "$output_dir/$name.zip" "$name")
|
||||
;;
|
||||
linux-*)
|
||||
cp -R "$publish_dir" "$staging/$name"
|
||||
@@ -39,13 +45,18 @@ case "$rid" in
|
||||
;;
|
||||
osx-*)
|
||||
app="$staging/YKanBan.app"
|
||||
mkdir -p "$app/Contents/MacOS"
|
||||
mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources"
|
||||
cp -R "$publish_dir/." "$app/Contents/MacOS/"
|
||||
cp "$script_dir/macos/ykanban.icns" "$app/Contents/Resources/"
|
||||
chmod +x "$app/Contents/MacOS/YKanBan"
|
||||
sed "s/@VERSION@/${version}/g" "$script_dir/macos/Info.plist" > "$app/Contents/Info.plist"
|
||||
if command -v codesign > /dev/null 2>&1; then
|
||||
# Ad-hoc signature: unsigned arm64 code does not run at all.
|
||||
codesign --force --deep --sign - "$app"
|
||||
# Ad-hoc signature for the bundle. Not fatal: the SDK already ad-hoc
|
||||
# signs the apphost, which is all arm64 needs to run, and --deep may
|
||||
# trip over the non-Mach-O files in Contents/MacOS.
|
||||
if ! codesign --force --deep --sign - "$app"; then
|
||||
echo "warning: ad-hoc signing of YKanBan.app failed; packing it unsigned" >&2
|
||||
fi
|
||||
fi
|
||||
tar -C "$staging" -czf "$output_dir/$name.tar.gz" YKanBan.app
|
||||
;;
|
||||
|
||||
Reference in new issue
Block a user