Repository navigation
Expand file tree
/
Copy pathDictionaryService.cs
More file actions
82 lines (70 loc) · 2.8 KB
/
Copy pathDictionaryService.cs
File metadata and controls
82 lines (70 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System.IO;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace WhisperTyper
{
public class DictionaryEntry
{
public string Trigger { get; set; } = "";
public string Replacement { get; set; } = "";
}
public class DictionaryService
{
private static readonly string _path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"WhisperTyper", "dictionary.json");
private record CompiledEntry(Regex Pattern, string Replacement);
private List<CompiledEntry> _compiled = [];
public List<DictionaryEntry> Entries { get; private set; } = [];
/// <summary>Ensures every sentence-ending period is followed by a space (e.g. "one.Two" → "one. Two").</summary>
public bool FixPeriodSpacing { get; set; } = true;
private static readonly Regex _periodFix = new(@"\.(?=[^\s])", RegexOptions.Compiled);
public DictionaryService() => Load();
public void Load()
{
try
{
if (File.Exists(_path))
Entries = JsonSerializer.Deserialize<List<DictionaryEntry>>(File.ReadAllText(_path)) ?? [];
}
catch { Entries = []; }
Compile();
}
public void Save()
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(_path)!);
File.WriteAllText(_path, JsonSerializer.Serialize(Entries, new JsonSerializerOptions { WriteIndented = true }));
}
catch { }
}
public void Compile()
{
_compiled = Entries
.Where(e => !string.IsNullOrWhiteSpace(e.Trigger))
.Select(e => new CompiledEntry(
new Regex($@"(?<!\w){Regex.Escape(e.Trigger.Trim())}(?!\w)",
RegexOptions.IgnoreCase | RegexOptions.Compiled),
e.Replacement))
.ToList();
}
public string Apply(string text)
{
if (string.IsNullOrEmpty(text)) return text;
if (FixPeriodSpacing)
text = _periodFix.Replace(text, ". ");
foreach (var entry in _compiled)
text = entry.Pattern.Replace(text, m => MatchCase(m.Value, entry.Replacement));
return text;
}
// Preserve casing style of the matched text.
private static string MatchCase(string matched, string replacement)
{
if (string.IsNullOrEmpty(replacement)) return replacement;
if (matched == matched.ToUpper()) return replacement.ToUpper();
if (char.IsUpper(matched[0])) return char.ToUpper(replacement[0]) + replacement[1..];
return replacement;
}
}
}