fasdfsa commited on
Commit
38cc2e9
·
1 Parent(s): 6cdc5ca

加入完整 mdict 查询功能

Browse files
imradv3.sln CHANGED
@@ -21,6 +21,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ScreenGrab", "src\ScreenGra
21
  EndProject
22
  Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ScreenGrab.Sample", "src\ScreenGrab.Sample\ScreenGrab.Sample.csproj", "{34691787-AE69-7042-FB4F-9EE5535A4D5A}"
23
  EndProject
 
 
24
  Global
25
  GlobalSection(SolutionConfigurationPlatforms) = preSolution
26
  Debug|Any CPU = Debug|Any CPU
@@ -139,6 +141,18 @@ Global
139
  {34691787-AE69-7042-FB4F-9EE5535A4D5A}.Release|x64.Build.0 = Release|Any CPU
140
  {34691787-AE69-7042-FB4F-9EE5535A4D5A}.Release|x86.ActiveCfg = Release|Any CPU
141
  {34691787-AE69-7042-FB4F-9EE5535A4D5A}.Release|x86.Build.0 = Release|Any CPU
 
 
 
 
 
 
 
 
 
 
 
 
142
  EndGlobalSection
143
  GlobalSection(SolutionProperties) = preSolution
144
  HideSolutionNode = FALSE
 
21
  EndProject
22
  Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ScreenGrab.Sample", "src\ScreenGrab.Sample\ScreenGrab.Sample.csproj", "{34691787-AE69-7042-FB4F-9EE5535A4D5A}"
23
  EndProject
24
+ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EchoDictLib", "src\EchoDictLib\EchoDictLib.csproj", "{014E5B08-E0B3-44D3-9AE3-510EE0691604}"
25
+ EndProject
26
  Global
27
  GlobalSection(SolutionConfigurationPlatforms) = preSolution
28
  Debug|Any CPU = Debug|Any CPU
 
141
  {34691787-AE69-7042-FB4F-9EE5535A4D5A}.Release|x64.Build.0 = Release|Any CPU
142
  {34691787-AE69-7042-FB4F-9EE5535A4D5A}.Release|x86.ActiveCfg = Release|Any CPU
143
  {34691787-AE69-7042-FB4F-9EE5535A4D5A}.Release|x86.Build.0 = Release|Any CPU
144
+ {014E5B08-E0B3-44D3-9AE3-510EE0691604}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
145
+ {014E5B08-E0B3-44D3-9AE3-510EE0691604}.Debug|Any CPU.Build.0 = Debug|Any CPU
146
+ {014E5B08-E0B3-44D3-9AE3-510EE0691604}.Debug|x64.ActiveCfg = Debug|Any CPU
147
+ {014E5B08-E0B3-44D3-9AE3-510EE0691604}.Debug|x64.Build.0 = Debug|Any CPU
148
+ {014E5B08-E0B3-44D3-9AE3-510EE0691604}.Debug|x86.ActiveCfg = Debug|Any CPU
149
+ {014E5B08-E0B3-44D3-9AE3-510EE0691604}.Debug|x86.Build.0 = Debug|Any CPU
150
+ {014E5B08-E0B3-44D3-9AE3-510EE0691604}.Release|Any CPU.ActiveCfg = Release|Any CPU
151
+ {014E5B08-E0B3-44D3-9AE3-510EE0691604}.Release|Any CPU.Build.0 = Release|Any CPU
152
+ {014E5B08-E0B3-44D3-9AE3-510EE0691604}.Release|x64.ActiveCfg = Release|Any CPU
153
+ {014E5B08-E0B3-44D3-9AE3-510EE0691604}.Release|x64.Build.0 = Release|Any CPU
154
+ {014E5B08-E0B3-44D3-9AE3-510EE0691604}.Release|x86.ActiveCfg = Release|Any CPU
155
+ {014E5B08-E0B3-44D3-9AE3-510EE0691604}.Release|x86.Build.0 = Release|Any CPU
156
  EndGlobalSection
157
  GlobalSection(SolutionProperties) = preSolution
158
  HideSolutionNode = FALSE
reame.txt CHANGED
@@ -1,4 +1,7 @@
1
 
 
 
 
2
  see github\echodict\cut\wpf\ScreenGrab\ScreenGrabber.cs
3
 
4
 
 
1
 
2
+ see E:\huggingface\goldendict-ng\wpfmdict
3
+ # mdict 的 C# 版是用 trae + gemini 3 pro 从 goldendict-ng 项目仿的
4
+
5
  see github\echodict\cut\wpf\ScreenGrab\ScreenGrabber.cs
6
 
7
 
src/EchoDictLib/Adler32.cs ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System;
2
+
3
+ namespace Echodict
4
+ {
5
+ public class Adler32
6
+ {
7
+ private uint _checksum;
8
+
9
+ public Adler32()
10
+ {
11
+ _checksum = 1;
12
+ }
13
+
14
+ public void Update(byte[] data, int offset, int length)
15
+ {
16
+ uint s1 = _checksum & 0xFFFF;
17
+ uint s2 = (_checksum >> 16) & 0xFFFF;
18
+
19
+ for (int i = 0; i < length; i++)
20
+ {
21
+ s1 = (s1 + data[offset + i]) % 65521;
22
+ s2 = (s2 + s1) % 65521;
23
+ }
24
+
25
+ _checksum = (s2 << 16) | s1;
26
+ }
27
+
28
+ public void Update(byte[] data)
29
+ {
30
+ Update(data, 0, data.Length);
31
+ }
32
+
33
+ public uint Value => _checksum;
34
+
35
+ public static uint Compute(byte[] data)
36
+ {
37
+ var adler = new Adler32();
38
+ adler.Update(data);
39
+ return adler.Value;
40
+ }
41
+
42
+ public static uint Compute(byte[] data, int offset, int length)
43
+ {
44
+ var adler = new Adler32();
45
+ adler.Update(data, offset, length);
46
+ return adler.Value;
47
+ }
48
+ }
49
+ }
src/EchoDictLib/DictGroup.cs ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ using System.Collections.Generic;
2
+
3
+ namespace Echodict
4
+ {
5
+ public class DictGroup
6
+ {
7
+ public string Name { get; set; } = string.Empty;
8
+ public List<string> DictionaryPaths { get; set; } = new List<string>();
9
+ }
10
+ }
src/EchoDictLib/DictRequestHandler.cs ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using CefSharp;
2
+ using CefSharp.Handler;
3
+ using System;
4
+ using System.Collections.Generic;
5
+ using System.IO;
6
+
7
+ namespace Echodict
8
+ {
9
+ public class DictRequestHandler : RequestHandler
10
+ {
11
+ private DictResourceRequestHandler _resourceRequestHandler;
12
+ private Action<string> _searchAction;
13
+
14
+ public DictRequestHandler(List<Dictionary> dicts, Action<string> searchAction = null)
15
+ {
16
+ _resourceRequestHandler = new DictResourceRequestHandler(dicts);
17
+ _searchAction = searchAction;
18
+ }
19
+
20
+ public void SetSearchHtml(string html)
21
+ {
22
+ _resourceRequestHandler.SearchHtml = html;
23
+ }
24
+
25
+ protected override bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
26
+ {
27
+ if (request.Url.StartsWith("entry://", StringComparison.OrdinalIgnoreCase))
28
+ {
29
+ string word = request.Url.Substring(8);
30
+ // Remove trailing slash if present
31
+ if (word.EndsWith("/")) word = word.Substring(0, word.Length - 1);
32
+
33
+ word = Uri.UnescapeDataString(word);
34
+
35
+ _searchAction?.Invoke(word);
36
+ return true;
37
+ }
38
+ return base.OnBeforeBrowse(chromiumWebBrowser, browser, frame, request, userGesture, isRedirect);
39
+ }
40
+
41
+ protected override IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling)
42
+ {
43
+ return _resourceRequestHandler;
44
+ }
45
+ }
46
+
47
+ public class DictResourceRequestHandler : ResourceRequestHandler
48
+ {
49
+ private List<Dictionary> _dicts;
50
+ public string? SearchHtml { get; set; }
51
+
52
+ public DictResourceRequestHandler(List<Dictionary> dicts)
53
+ {
54
+ _dicts = dicts;
55
+ }
56
+
57
+ protected override IResourceHandler GetResourceHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request)
58
+ {
59
+ if (request.Url.StartsWith("http://custom-rendering/", StringComparison.OrdinalIgnoreCase))
60
+ {
61
+ // Serve the search result page
62
+ if (request.Url.Equals("http://custom-rendering/result.html", StringComparison.OrdinalIgnoreCase) ||
63
+ request.Url.Equals("http://custom-rendering/", StringComparison.OrdinalIgnoreCase))
64
+ {
65
+ if (SearchHtml != null)
66
+ {
67
+ return ResourceHandler.FromByteArray(System.Text.Encoding.UTF8.GetBytes(SearchHtml), "text/html");
68
+ }
69
+ }
70
+
71
+ if (!Uri.TryCreate(request.Url, UriKind.Absolute, out Uri? uri))
72
+ {
73
+ var handler = ResourceHandler.FromByteArray(System.Text.Encoding.UTF8.GetBytes("Invalid URL"), "text/plain");
74
+ return handler;
75
+ }
76
+
77
+ // Parse path to extract dictionary ID if present
78
+ // Expected format: /<dictId>/path/to/resource
79
+ string path = Uri.UnescapeDataString(uri.AbsolutePath);
80
+ string? dictId = null;
81
+ string resourcePath = path;
82
+
83
+ // Check if the first segment is a dictionary ID (32 hex chars)
84
+ var segments = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
85
+ if (segments.Length > 0 && segments[0].Length == 32 && System.Text.RegularExpressions.Regex.IsMatch(segments[0], "^[a-fA-F0-9]{32}$"))
86
+ {
87
+ dictId = segments[0];
88
+ // Reconstruct path without the ID
89
+ resourcePath = string.Join("/", segments, 1, segments.Length - 1);
90
+ }
91
+
92
+ if (dictId != null)
93
+ {
94
+ // Search in specific dictionary
95
+ var dict = _dicts.Find(d => d.Id.Equals(dictId, StringComparison.OrdinalIgnoreCase));
96
+ if (dict != null)
97
+ {
98
+ var data = dict.GetResource(resourcePath);
99
+ if (data != null)
100
+ {
101
+ string mime = GetMimeType(resourcePath);
102
+ return ResourceHandler.FromByteArray(data, mime);
103
+ }
104
+ }
105
+ }
106
+ else
107
+ {
108
+ // Fallback: Search in all dictionaries (legacy/global lookup)
109
+ foreach (var dict in _dicts)
110
+ {
111
+ var data = dict.GetResource(path);
112
+ if (data != null)
113
+ {
114
+ string mime = GetMimeType(path);
115
+ return ResourceHandler.FromByteArray(data, mime);
116
+ }
117
+ }
118
+ }
119
+
120
+ // Resource not found: return 404 to avoid network/DNS lookup which causes "Site can't be reached"
121
+ // We return 200 OK with "Not Found" body because setting StatusCode on IResourceHandler is tricky in some versions
122
+ var notFoundHandler = ResourceHandler.FromByteArray(System.Text.Encoding.UTF8.GetBytes("Not Found"), "text/plain");
123
+ return notFoundHandler;
124
+ }
125
+ return base.GetResourceHandler(chromiumWebBrowser, browser, frame, request);
126
+ }
127
+
128
+ private string GetMimeType(string path)
129
+ {
130
+ string ext = Path.GetExtension(path).ToLower();
131
+ switch (ext)
132
+ {
133
+ case ".css": return "text/css";
134
+ case ".js": return "text/javascript";
135
+ case ".png": return "image/png";
136
+ case ".jpg": return "image/jpeg";
137
+ case ".jpeg": return "image/jpeg";
138
+ case ".gif": return "image/gif";
139
+ case ".bmp": return "image/bmp";
140
+ case ".svg": return "image/svg+xml";
141
+ case ".wav": return "audio/wav";
142
+ case ".mp3": return "audio/mpeg";
143
+ case ".ttf": return "font/ttf";
144
+ case ".woff": return "font/woff";
145
+ case ".woff2": return "font/woff2";
146
+ default: return "application/octet-stream";
147
+ }
148
+ }
149
+ }
150
+ }
src/EchoDictLib/Dictionary.cs ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System;
2
+ using System.Collections.Generic;
3
+ using System.IO;
4
+ using System.Linq;
5
+
6
+ namespace Echodict
7
+ {
8
+ public class Dictionary : IDisposable
9
+ {
10
+ public string Id { get; private set; }
11
+ public string Name { get; private set; }
12
+ public MdxReader Mdx { get; private set; }
13
+ public List<MdxReader> Mdds { get; private set; } = new List<MdxReader>();
14
+
15
+ public Dictionary(string mdxPath, string? cacheDir = null, bool forceRebuild = false)
16
+ {
17
+ if (!File.Exists(mdxPath))
18
+ throw new FileNotFoundException("MDX file not found", mdxPath);
19
+
20
+ // Generate ID first (needed for cache filename)
21
+ Id = CreateId(mdxPath);
22
+ Name = Path.GetFileNameWithoutExtension(mdxPath);
23
+
24
+ // Prepare Cache Path
25
+ string? mdxCachePath = null;
26
+ if (!string.IsNullOrEmpty(cacheDir))
27
+ {
28
+ if (!Directory.Exists(cacheDir)) Directory.CreateDirectory(cacheDir);
29
+ mdxCachePath = Path.Combine(cacheDir, Id + ".idx");
30
+ }
31
+
32
+ // Load MDX
33
+ Mdx = new MdxReader(mdxPath);
34
+ if (!Mdx.Open())
35
+ throw new Exception("Failed to open MDX file");
36
+
37
+ Mdx.LoadIndex(mdxCachePath, forceRebuild);
38
+
39
+ // Load associated MDDs
40
+ LoadMdds(mdxPath, cacheDir, forceRebuild);
41
+ }
42
+
43
+ private void LoadMdds(string mdxPath, string? cacheDir, bool forceRebuild)
44
+ {
45
+ string baseName = Path.Combine(Path.GetDirectoryName(mdxPath)!, Path.GetFileNameWithoutExtension(mdxPath));
46
+
47
+ // 1. Check base.mdd
48
+ string mddPath = baseName + ".mdd";
49
+ if (File.Exists(mddPath))
50
+ {
51
+ AddMdd(mddPath, cacheDir, forceRebuild);
52
+ }
53
+
54
+ // 2. Check base.1.mdd, base.2.mdd, etc.
55
+ int vol = 1;
56
+ while (true)
57
+ {
58
+ string volPath = $"{baseName}.{vol}.mdd";
59
+ if (File.Exists(volPath))
60
+ {
61
+ AddMdd(volPath, cacheDir, forceRebuild);
62
+ vol++;
63
+ }
64
+ else
65
+ {
66
+ break;
67
+ }
68
+ }
69
+ }
70
+
71
+ private void AddMdd(string path, string? cacheDir, bool forceRebuild)
72
+ {
73
+ try
74
+ {
75
+ var reader = new MdxReader(path);
76
+ if (reader.Open())
77
+ {
78
+ // Calculate cache path for MDD
79
+ string? mddCachePath = null;
80
+ if (!string.IsNullOrEmpty(cacheDir))
81
+ {
82
+ string id = CreateId(path);
83
+ mddCachePath = Path.Combine(cacheDir, id + ".idx");
84
+ }
85
+
86
+ reader.LoadIndex(mddCachePath, forceRebuild);
87
+ Mdds.Add(reader);
88
+ }
89
+ }
90
+ catch (Exception)
91
+ {
92
+ // Log or ignore broken MDDs
93
+ }
94
+ }
95
+
96
+ private string CreateId(string path)
97
+ {
98
+ // Simple ID generation
99
+ using (var md5 = System.Security.Cryptography.MD5.Create())
100
+ {
101
+ byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(path.ToLowerInvariant());
102
+ byte[] hashBytes = md5.ComputeHash(inputBytes);
103
+ return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
104
+ }
105
+ }
106
+
107
+ public byte[]? GetResource(string path)
108
+ {
109
+ // Normalize path (remove leading /)
110
+ string relPath = path.TrimStart('/', '\\');
111
+
112
+ // 1. Check File System (Relative to MDX)
113
+ string dictDir = Path.GetDirectoryName(Mdx.Filename)!;
114
+ string localPath = Path.Combine(dictDir, relPath);
115
+
116
+ if (File.Exists(localPath))
117
+ {
118
+ try
119
+ {
120
+ return File.ReadAllBytes(localPath);
121
+ }
122
+ catch { /* Ignore read errors */ }
123
+ }
124
+
125
+ // 2. Check MDDs
126
+ // MDict keys usually use backslash or forward slash. MdxReader.GetResource handles variations.
127
+ foreach (var mdd in Mdds)
128
+ {
129
+ var data = mdd.GetResource(relPath);
130
+ if (data != null) return data;
131
+ }
132
+
133
+ return null;
134
+ }
135
+
136
+ public void Dispose()
137
+ {
138
+ Mdx?.Dispose();
139
+ foreach (var mdd in Mdds)
140
+ {
141
+ mdd.Dispose();
142
+ }
143
+ }
144
+ }
145
+ }
src/EchoDictLib/EchoDictLib.csproj ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <Project Sdk="Microsoft.NET.Sdk">
2
+
3
+ <PropertyGroup>
4
+ <TargetFramework>net8.0-windows</TargetFramework>
5
+ <ImplicitUsings>enable</ImplicitUsings>
6
+ <Nullable>enable</Nullable>
7
+ </PropertyGroup>
8
+
9
+ <ItemGroup>
10
+ <PackageReference Include="CefSharp.Wpf.NETCore" Version="141.0.110" />
11
+ <PackageReference Include="System.Text.Encoding.CodePages" Version="10.0.1" />
12
+ </ItemGroup>
13
+
14
+ </Project>
src/EchoDictLib/EchodictConfig.cs ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System.Collections.Generic;
2
+
3
+ namespace Echodict
4
+ {
5
+ public class EchodictConfig
6
+ {
7
+ public List<string> SourcePaths { get; set; } = new List<string>();
8
+ public List<DictGroup> Groups { get; set; } = new List<DictGroup>();
9
+ public string LastSelectedDictId { get; set; } = "ALL";
10
+ public List<string> History { get; set; } = new List<string>();
11
+ }
12
+ }
src/EchoDictLib/Lzo.cs ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System;
2
+
3
+ namespace Echodict
4
+ {
5
+ public static class Lzo
6
+ {
7
+ public static byte[] Decompress(byte[] src, int decompressedSize)
8
+ {
9
+ byte[] dst = new byte[decompressedSize];
10
+ int srcLen = src.Length;
11
+ int dstLen = decompressedSize;
12
+ int result = Decompress(src, 0, srcLen, dst, 0, ref dstLen);
13
+
14
+ if (result != 0)
15
+ {
16
+ throw new Exception($"LZO decompression failed with error code {result}");
17
+ }
18
+ return dst;
19
+ }
20
+
21
+ private static int Decompress(byte[] inBuf, int inPos, int inLen, byte[] outBuf, int outPos, ref int outLen)
22
+ {
23
+ int ip = inPos;
24
+ int op = outPos;
25
+ int inEnd = inPos + inLen;
26
+ int outEnd = outPos + outLen;
27
+
28
+ int t = 0;
29
+ int mPos = 0;
30
+
31
+ bool firstRun = true;
32
+
33
+ while (true)
34
+ {
35
+ if (firstRun)
36
+ {
37
+ firstRun = false;
38
+ if (inLen > 17 && inBuf[ip] <= 17)
39
+ {
40
+ t = inBuf[ip++] - 17;
41
+ if (t < 4)
42
+ {
43
+ do {
44
+ outBuf[op++] = inBuf[ip++];
45
+ } while (--t > 0);
46
+ t = inBuf[ip++];
47
+ goto match_done;
48
+ }
49
+ else
50
+ {
51
+ do {
52
+ outBuf[op++] = inBuf[ip++];
53
+ } while (--t > 0);
54
+ goto first_literal_run;
55
+ }
56
+ }
57
+ }
58
+
59
+ t = inBuf[ip++];
60
+ if (t >= 16)
61
+ {
62
+ goto match;
63
+ }
64
+
65
+ if (t == 0)
66
+ {
67
+ while (inBuf[ip] == 0)
68
+ {
69
+ t += 255;
70
+ ip++;
71
+ }
72
+ t += 15 + inBuf[ip++];
73
+ }
74
+
75
+ t += 3;
76
+ if (op + t > outEnd || ip + t > inEnd) return -1;
77
+
78
+ do
79
+ {
80
+ outBuf[op++] = inBuf[ip++];
81
+ } while (--t > 0);
82
+
83
+ first_literal_run:
84
+ t = inBuf[ip++];
85
+ if (t >= 16)
86
+ {
87
+ goto match;
88
+ }
89
+
90
+ // M = 0
91
+ mPos = op - (1 + 0x0800);
92
+ mPos -= t >> 2;
93
+ mPos -= inBuf[ip++] << 2;
94
+
95
+ if (mPos < outPos || mPos >= op) return -2;
96
+
97
+ outBuf[op++] = outBuf[mPos++];
98
+ outBuf[op++] = outBuf[mPos++];
99
+ outBuf[op++] = outBuf[mPos];
100
+
101
+ goto match_done;
102
+
103
+ match:
104
+ if (t >= 64)
105
+ {
106
+ // M = 1
107
+ mPos = op - 1;
108
+ mPos -= (t >> 2) & 7;
109
+ mPos -= inBuf[ip++] << 3;
110
+ t = (t >> 5) - 1;
111
+
112
+ if (mPos < outPos || mPos >= op) return -2;
113
+
114
+ // Copy match inline
115
+ outBuf[op++] = outBuf[mPos++];
116
+ outBuf[op++] = outBuf[mPos++];
117
+ do {
118
+ outBuf[op++] = outBuf[mPos++];
119
+ } while (--t > 0);
120
+ goto match_done;
121
+ }
122
+ else if (t >= 32)
123
+ {
124
+ // M = 2
125
+ t &= 31;
126
+ if (t == 0)
127
+ {
128
+ while (inBuf[ip] == 0)
129
+ {
130
+ t += 255;
131
+ ip++;
132
+ }
133
+ t += 31 + inBuf[ip++];
134
+ }
135
+
136
+ mPos = op - 1;
137
+ mPos -= (inBuf[ip] >> 2) + (inBuf[ip+1] << 6);
138
+ ip += 2;
139
+ }
140
+ else if (t >= 16)
141
+ {
142
+ // M = 3
143
+ mPos = op;
144
+ mPos -= (t & 8) << 11;
145
+ t &= 7;
146
+ if (t == 0)
147
+ {
148
+ while (inBuf[ip] == 0)
149
+ {
150
+ t += 255;
151
+ ip++;
152
+ }
153
+ t += 7 + inBuf[ip++];
154
+ }
155
+
156
+ mPos -= (inBuf[ip] >> 2) + (inBuf[ip+1] << 6);
157
+ ip += 2;
158
+
159
+ if (mPos == op)
160
+ {
161
+ outLen = op - outPos;
162
+ return 0; // EOF
163
+ }
164
+ mPos -= 0x4000;
165
+ }
166
+ else
167
+ {
168
+ return -3;
169
+ }
170
+
171
+ if (mPos < outPos || mPos >= op) return -2;
172
+
173
+ if (t >= 6 && (op - mPos) >= 4)
174
+ {
175
+ outBuf[op++] = outBuf[mPos++];
176
+ outBuf[op++] = outBuf[mPos++];
177
+ outBuf[op++] = outBuf[mPos++];
178
+ outBuf[op++] = outBuf[mPos++];
179
+ t -= 2;
180
+ do {
181
+ outBuf[op++] = outBuf[mPos++];
182
+ } while (--t > 0);
183
+ }
184
+ else
185
+ {
186
+ outBuf[op++] = outBuf[mPos++];
187
+ outBuf[op++] = outBuf[mPos++];
188
+ do {
189
+ outBuf[op++] = outBuf[mPos++];
190
+ } while (--t > 0);
191
+ }
192
+
193
+ match_done:
194
+ t = inBuf[ip++] & 3;
195
+ if (t == 0) continue;
196
+
197
+ outBuf[op++] = inBuf[ip++];
198
+ if (t > 1) {
199
+ outBuf[op++] = inBuf[ip++];
200
+ if (t > 2) {
201
+ outBuf[op++] = inBuf[ip++];
202
+ }
203
+ }
204
+
205
+ t = inBuf[ip++];
206
+ }
207
+ }
208
+ }
209
+ }
src/EchoDictLib/MdxReader.cs ADDED
@@ -0,0 +1,765 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System;
2
+ using System.Collections.Generic;
3
+ using System.IO;
4
+ using System.IO.Compression;
5
+ using System.Text;
6
+ using System.Text.RegularExpressions;
7
+ using System.Xml;
8
+ using System.Linq;
9
+
10
+ namespace Echodict
11
+ {
12
+ public class MdxReader : IDisposable
13
+ {
14
+ private FileStream _fs;
15
+ private BinaryReader _reader;
16
+ public string Filename { get; private set; }
17
+
18
+ public string Encoding { get; private set; } = "UTF-16LE";
19
+ public double Version { get; private set; }
20
+ private int _numberWidth;
21
+ public bool IsEncrypted { get; private set; }
22
+ private int _encryptedFlag;
23
+ public List<string> Headwords { get; private set; } = new List<string>();
24
+ public Dictionary<string, long> Index { get; private set; } = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
25
+
26
+ // Basic stats
27
+ public long NumHeadWordBlocks;
28
+ public long WordCount;
29
+
30
+ public MdxReader(string filename)
31
+ {
32
+ Filename = filename;
33
+ }
34
+
35
+ // Record Block Infos
36
+ private List<RecordBlockInfo> _recordBlocks = new List<RecordBlockInfo>();
37
+ private long _totalRecordSize;
38
+
39
+ // Parser state
40
+ private long _headWordBlockInfoPos;
41
+ private long _headWordBlockInfoSize;
42
+ private long _headWordBlockSize;
43
+ private long _headWordPos;
44
+ private List<Tuple<long, long>> _headWordBlockInfos;
45
+
46
+ public struct RecordBlockInfo
47
+ {
48
+ public long CompressedSize;
49
+ public long DecompressedSize;
50
+ public long StartPos; // File Position
51
+ public long EndPos;
52
+ public long ShadowStartPos; // Global Decompressed Offset Start
53
+ public long ShadowEndPos;
54
+ }
55
+
56
+ public bool Open()
57
+ {
58
+ try
59
+ {
60
+ if (_fs != null)
61
+ {
62
+ _fs.Close();
63
+ _fs.Dispose();
64
+ }
65
+
66
+ _fs = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read);
67
+ _reader = new BinaryReader(_fs);
68
+
69
+ ReadHeader();
70
+
71
+ // Adjust Encoding based on header info if needed
72
+ // Sometimes Encoding is not explicitly set in header but inferred.
73
+ // But let's rely on Header "Encoding" attribute first.
74
+
75
+ ReadHeadWordBlockInfos();
76
+ ReadRecordBlockInfos();
77
+
78
+ return true;
79
+ }
80
+ catch
81
+ {
82
+ return false;
83
+ }
84
+ }
85
+
86
+ public bool LoadIndex(string? cachePath = null, bool forceRebuild = false)
87
+ {
88
+ if (_headWordBlockInfos == null) return false;
89
+
90
+ // Try to load from cache
91
+ if (!forceRebuild && !string.IsNullOrEmpty(cachePath) && File.Exists(cachePath))
92
+ {
93
+ // Check timestamp: Cache must be newer than MDX file
94
+ try
95
+ {
96
+ var mdxTime = File.GetLastWriteTimeUtc(Filename);
97
+ var cacheTime = File.GetLastWriteTimeUtc(cachePath);
98
+
99
+ if (cacheTime > mdxTime)
100
+ {
101
+ if (LoadIndexFromCache(cachePath))
102
+ {
103
+ return true;
104
+ }
105
+ }
106
+ }
107
+ catch (Exception ex)
108
+ {
109
+ System.Diagnostics.Debug.WriteLine($"Error checking cache timestamp: {ex.Message}");
110
+ }
111
+ }
112
+
113
+ _fs.Seek(_headWordPos, SeekOrigin.Begin);
114
+
115
+ bool v2 = Version >= 2.0;
116
+
117
+ foreach (var block in _headWordBlockInfos)
118
+ {
119
+ long compressedSize = block.Item1;
120
+ long decompressedSize = block.Item2;
121
+
122
+ byte[] compressedBlock = _reader.ReadBytes((int)compressedSize);
123
+ byte[] decompressedBlock = Decompress(compressedBlock, (int)decompressedSize);
124
+
125
+ SplitHeadBlock(decompressedBlock, v2);
126
+ }
127
+
128
+ // Save to cache if path provided
129
+ if (!string.IsNullOrEmpty(cachePath))
130
+ {
131
+ SaveIndexToCache(cachePath);
132
+ }
133
+
134
+ return true;
135
+ }
136
+
137
+ private bool LoadIndexFromCache(string path)
138
+ {
139
+ try
140
+ {
141
+ using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
142
+ using (var br = new BinaryReader(fs))
143
+ {
144
+ string magic = new string(br.ReadChars(8));
145
+ if (magic != "MDXIDX01") return false;
146
+
147
+ long savedWordCount = br.ReadInt64();
148
+ Headwords = new List<string>((int)savedWordCount);
149
+ Index = new Dictionary<string, long>((int)savedWordCount, StringComparer.OrdinalIgnoreCase);
150
+
151
+ for (int i = 0; i < savedWordCount; i++)
152
+ {
153
+ string headword = br.ReadString();
154
+ long offset = br.ReadInt64();
155
+
156
+ Headwords.Add(headword);
157
+ if (!Index.ContainsKey(headword))
158
+ {
159
+ Index[headword] = offset;
160
+ }
161
+ }
162
+ return true;
163
+ }
164
+ }
165
+ catch (Exception)
166
+ {
167
+ // Cache corrupted or incompatible
168
+ return false;
169
+ }
170
+ }
171
+
172
+ private void SaveIndexToCache(string path)
173
+ {
174
+ try
175
+ {
176
+ using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
177
+ using (var bw = new BinaryWriter(fs))
178
+ {
179
+ bw.Write("MDXIDX01".ToCharArray());
180
+ bw.Write((long)Headwords.Count);
181
+
182
+ // We iterate Headwords list because it preserves order (important for GetRecordData size calc)
183
+ foreach (var hw in Headwords)
184
+ {
185
+ bw.Write(hw);
186
+ if (Index.TryGetValue(hw, out long offset))
187
+ {
188
+ bw.Write(offset);
189
+ }
190
+ else
191
+ {
192
+ bw.Write((long)0); // Should not happen
193
+ }
194
+ }
195
+ }
196
+ }
197
+ catch (Exception ex)
198
+ {
199
+ System.Diagnostics.Debug.WriteLine($"Failed to save cache: {ex.Message}");
200
+ }
201
+ }
202
+
203
+ private void ReadRecordBlockInfos()
204
+ {
205
+ // Position should be at the end of HeadWordBlockInfos (or we need to seek)
206
+ // C++: file_->seek( headWordBlockInfoPos_ + headWordBlockInfoSize_ + headWordBlockSize_ );
207
+
208
+ long targetPos = _headWordBlockInfoPos + _headWordBlockInfoSize + _headWordBlockSize;
209
+ _fs.Seek(targetPos, SeekOrigin.Begin);
210
+
211
+ long numRecordBlocks = ReadNumber(_reader, Version >= 2.0);
212
+ long numEntries = ReadNumber(_reader, Version >= 2.0);
213
+ long recordInfoSize = ReadNumber(_reader, Version >= 2.0);
214
+ _totalRecordSize = ReadNumber(_reader, Version >= 2.0);
215
+
216
+ long startOfIndex = _fs.Position;
217
+ long startOfData = startOfIndex + recordInfoSize;
218
+
219
+ long currentShadow = 0;
220
+ long currentFilePos = startOfData;
221
+
222
+ for (int i = 0; i < numRecordBlocks; i++)
223
+ {
224
+ long comp = GetRecordBlockCompressedSize();
225
+ long decomp = ReadNumber(_reader, Version >= 2.0);
226
+
227
+ _recordBlocks.Add(new RecordBlockInfo
228
+ {
229
+ CompressedSize = comp,
230
+ DecompressedSize = decomp,
231
+ StartPos = currentFilePos,
232
+ EndPos = currentFilePos + comp,
233
+ ShadowStartPos = currentShadow,
234
+ ShadowEndPos = currentShadow + decomp
235
+ });
236
+
237
+ currentShadow += decomp;
238
+ currentFilePos += comp;
239
+ }
240
+ }
241
+
242
+ public byte[]? GetResource(string key)
243
+ {
244
+ // Try exact match
245
+ if (Index.ContainsKey(key)) return GetRecordData(key);
246
+
247
+ // Try with backslash
248
+ if (!key.StartsWith("\\") && !key.StartsWith("/"))
249
+ {
250
+ string k = "\\" + key;
251
+ if (Index.ContainsKey(k)) return GetRecordData(k);
252
+
253
+ k = "/" + key;
254
+ if (Index.ContainsKey(k)) return GetRecordData(k);
255
+ }
256
+
257
+ // Try replacing / with \
258
+ string k2 = key.Replace("/", "\\");
259
+ if (Index.ContainsKey(k2)) return GetRecordData(k2);
260
+
261
+ // Try replacing \ with /
262
+ string k3 = key.Replace("\\", "/");
263
+ if (Index.ContainsKey(k3)) return GetRecordData(k3);
264
+
265
+ return null;
266
+ }
267
+
268
+ public byte[]? GetRecordData(string key)
269
+ {
270
+ if (!Index.ContainsKey(key)) return null;
271
+ long offset = Index[key];
272
+
273
+ // Find size
274
+ long size = -1;
275
+ int idx = Headwords.IndexOf(key);
276
+
277
+ if (idx != -1 && idx < Headwords.Count - 1)
278
+ {
279
+ string nextKey = Headwords[idx + 1];
280
+ long nextOffset = Index[nextKey];
281
+ size = nextOffset - offset;
282
+ }
283
+
284
+ return GetRecordData(offset, size);
285
+ }
286
+
287
+ public string? GetDefinition(string key)
288
+ {
289
+ return GetDefinitionInternal(key, new HashSet<string>());
290
+ }
291
+
292
+ private string? GetDefinitionInternal(string key, HashSet<string> visited)
293
+ {
294
+ if (visited.Contains(key)) return null; // Cycle detection
295
+ visited.Add(key);
296
+
297
+ var data = GetRecordData(key);
298
+ if (data == null) return null;
299
+
300
+ // Try to detect encoding or use the one from header
301
+ Encoding enc;
302
+ try
303
+ {
304
+ enc = System.Text.Encoding.GetEncoding(Encoding == "GB18030" ? "GB18030" : "UTF-8");
305
+ }
306
+ catch
307
+ {
308
+ enc = System.Text.Encoding.UTF8;
309
+ }
310
+
311
+ // If header says UTF-16LE, we should use it.
312
+ if (Encoding == "UTF-16LE")
313
+ {
314
+ enc = System.Text.Encoding.Unicode;
315
+ }
316
+
317
+ string text;
318
+ try {
319
+ text = enc.GetString(data);
320
+ } catch {
321
+ // Fallback
322
+ text = System.Text.Encoding.UTF8.GetString(data);
323
+ }
324
+
325
+ // Handle internal redirects
326
+ if (text.StartsWith("@@@LINK="))
327
+ {
328
+ // Check for multiple links
329
+ if (text.IndexOf("@@@LINK=", 1) != -1)
330
+ {
331
+ return text;
332
+ }
333
+
334
+ string target = text.Substring(8).Trim();
335
+ // Remove null terminator if present
336
+ int nullIndex = target.IndexOf('\0');
337
+ if (nullIndex != -1) target = target.Substring(0, nullIndex);
338
+ target = target.Trim();
339
+
340
+ var targetDef = GetDefinitionInternal(target, visited);
341
+ if (targetDef != null) return targetDef;
342
+ } else if (text.Contains("@@@LINK=")) {
343
+ int a = 1;
344
+ }
345
+
346
+ return text;
347
+ }
348
+
349
+ public byte[] GetRecordData(long offset, long size)
350
+ {
351
+ // Find Block
352
+ var block = _recordBlocks.FirstOrDefault(b => offset >= b.ShadowStartPos && offset < b.ShadowEndPos);
353
+ if (block.DecompressedSize == 0) return new byte[0];
354
+
355
+ // Read Block
356
+ // In a real app, we should cache the last accessed block to avoid re-reading/decompressing for every word if they are in same block.
357
+ _fs.Seek(block.StartPos, SeekOrigin.Begin);
358
+ byte[] compressed = _reader.ReadBytes((int)block.CompressedSize);
359
+ byte[] decompressed = Decompress(compressed, (int)block.DecompressedSize);
360
+
361
+ // Extract Record
362
+ long localOffset = offset - block.ShadowStartPos;
363
+ if (localOffset >= decompressed.Length) return new byte[0];
364
+
365
+ int readLen = (int)size;
366
+ if (readLen <= 0 || localOffset + readLen > decompressed.Length)
367
+ {
368
+ readLen = decompressed.Length - (int)localOffset;
369
+ }
370
+
371
+ byte[] result = new byte[readLen];
372
+ Array.Copy(decompressed, localOffset, result, 0, readLen);
373
+ return result;
374
+ }
375
+
376
+ private void ReadHeader()
377
+ {
378
+ int headerTextSize = _reader.ReadInt32(); // Little Endian by default in C# BinaryReader? Wait.
379
+ // MDX is Big Endian usually. The C++ code says: in.setByteOrder( QDataStream::BigEndian );
380
+ // So we need to read Big Endian.
381
+
382
+ // Let's reset and read properly.
383
+ _fs.Position = 0;
384
+ headerTextSize = ReadInt32BE();
385
+
386
+ byte[] headerBytes = _reader.ReadBytes(headerTextSize);
387
+
388
+ // Calculate Checksum
389
+ uint checksum = ReadInt32LE(); // Checksum is Little Endian per code: in.setByteOrder( QDataStream::LittleEndian );
390
+
391
+ // Verify checksum (Adler32) - Skipped for MVP to ensure we just load valid files.
392
+
393
+ string headerText = System.Text.Encoding.Unicode.GetString(headerBytes); // UTF-16LE
394
+
395
+ // Parse Attributes
396
+ var attrs = ParseXmlAttributes(headerText);
397
+
398
+ if (attrs.ContainsKey("Encoding"))
399
+ {
400
+ Encoding = attrs["Encoding"];
401
+ if (Encoding == "GBK" || Encoding == "GB2312") Encoding = "GB18030";
402
+ if (string.IsNullOrEmpty(Encoding) || Encoding == "UTF-16") Encoding = "UTF-16LE";
403
+ }
404
+
405
+ if (attrs.ContainsKey("GeneratedByEngineVersion"))
406
+ {
407
+ Version = double.Parse(attrs["GeneratedByEngineVersion"]);
408
+ }
409
+
410
+ if (attrs.ContainsKey("Encrypted"))
411
+ {
412
+ string enc = attrs["Encrypted"];
413
+ if (enc == "Yes")
414
+ {
415
+ _encryptedFlag |= 1;
416
+ }
417
+ else
418
+ {
419
+ int val;
420
+ if (int.TryParse(enc, out val))
421
+ _encryptedFlag |= val;
422
+ }
423
+ IsEncrypted = _encryptedFlag != 0;
424
+ }
425
+
426
+ _numberWidth = Version >= 2.0 ? 8 : 4;
427
+ }
428
+
429
+ private void ReadHeadWordBlockInfos()
430
+ {
431
+ // Read Header of Block Infos
432
+ // version >= 2.0 uses 8 bytes for numbers, otherwise 4.
433
+ bool v2 = Version >= 2.0;
434
+ int numBytes = v2 ? 8 : 4;
435
+
436
+ // Just skip the block info header for a moment to see structure...
437
+ // C++: QByteArray header = file_->read( version_ >= 2.0 ? ( numberTypeSize_ * 5 ) : ( numberTypeSize_ * 4 ) );
438
+ int headerLen = v2 ? 40 : 16; // 8*5 vs 4*4
439
+ byte[] infoHeader = _reader.ReadBytes(headerLen);
440
+
441
+ using (var ms = new MemoryStream(infoHeader))
442
+ using (var br = new BinaryReader(ms))
443
+ {
444
+ NumHeadWordBlocks = ReadNumber(br, v2);
445
+ WordCount = ReadNumber(br, v2);
446
+ long decompressedInfoSize = 0;
447
+ if (v2) decompressedInfoSize = ReadNumber(br, v2);
448
+ _headWordBlockInfoSize = ReadNumber(br, v2);
449
+ _headWordBlockSize = ReadNumber(br, v2);
450
+
451
+ // If v2, checksum follows (4 bytes)
452
+ if (v2) _reader.ReadInt32();
453
+
454
+ _headWordBlockInfoPos = _fs.Position;
455
+
456
+ // Read HeadWord Block Info (Compressed)
457
+ byte[] blockInfoCompressed = _reader.ReadBytes((int)_headWordBlockInfoSize);
458
+
459
+ byte[] debugBefore = new byte[Math.Min(32, blockInfoCompressed.Length)];
460
+ Array.Copy(blockInfoCompressed, debugBefore, debugBefore.Length);
461
+
462
+ // Decrypt if needed
463
+ if ((_encryptedFlag & 2) == 2)
464
+ {
465
+ // For debugging, we can calculate the key here to show in exception if needed
466
+ // But DecryptHeadWordIndex will do it internally
467
+ DecryptHeadWordIndex(blockInfoCompressed);
468
+ }
469
+
470
+ // Decompress Block Info
471
+ // It contains the list of (CompressedSize, DecompressedSize) for each block.
472
+ byte[] blockInfoDecompressed;
473
+ try
474
+ {
475
+ blockInfoDecompressed = Decompress(blockInfoCompressed, (int)decompressedInfoSize);
476
+ }
477
+ catch (Exception ex)
478
+ {
479
+ // Recalculate key for debug info
480
+ var ripemd = new Ripemd128();
481
+ ripemd.Update(debugBefore, 4, 4); // use saved original bytes
482
+ ripemd.Update(new byte[] { 0x95, 0x36, 0x00, 0x00 }, 0, 4);
483
+ byte[] key = ripemd.Digest();
484
+ string keyHex = BitConverter.ToString(key);
485
+
486
+ string beforeHex = BitConverter.ToString(debugBefore);
487
+ string afterHex = BitConverter.ToString(blockInfoCompressed.Take(32).ToArray());
488
+
489
+ throw new Exception($"Decompression failed. Version={Version}, EncryptedFlag={_encryptedFlag}, InfoSize={_headWordBlockInfoSize}. \nBefore: {beforeHex}\nAfter: {afterHex}\nKey: {keyHex}\nEx: {ex.Message}");
490
+ }
491
+
492
+ // Decode Block Info
493
+ _headWordBlockInfos = DecodeBlockInfo(blockInfoDecompressed, v2);
494
+
495
+ _headWordPos = _fs.Position;
496
+ }
497
+ }
498
+
499
+ private void DecryptHeadWordIndex(byte[] buffer)
500
+ {
501
+ var ripemd = new Ripemd128();
502
+ ripemd.Update(buffer, 4, 4);
503
+ ripemd.Update(new byte[] { 0x95, 0x36, 0x00, 0x00 }, 0, 4);
504
+ byte[] key = ripemd.Digest();
505
+
506
+ int len = buffer.Length - 8;
507
+ int offset = 8;
508
+ byte prev = 0x36;
509
+
510
+ for (int i = 0; i < len; i++)
511
+ {
512
+ byte b = buffer[offset + i];
513
+ byte originalB = b;
514
+
515
+ b = (byte)((b >> 4) | (b << 4));
516
+ b = (byte)(b ^ prev ^ (i & 0xFF) ^ key[i % 16]);
517
+
518
+ prev = originalB;
519
+ buffer[offset + i] = b;
520
+ }
521
+ }
522
+
523
+ private List<Tuple<long, long>> DecodeBlockInfo(byte[] data, bool v2)
524
+ {
525
+ var list = new List<Tuple<long, long>>();
526
+ int numberTypeSize = v2 ? 8 : 4;
527
+ bool isU16 = v2;
528
+ int textTermSize = v2 ? 1 : 0; // C++: if version >= 2.0 textTermSize = 1; else 0.
529
+
530
+ using (var ms = new MemoryStream(data))
531
+ using (var br = new BinaryReader(ms))
532
+ {
533
+ while (ms.Position < ms.Length)
534
+ {
535
+ // Number of keywords in the block (Skip)
536
+ ms.Seek(numberTypeSize, SeekOrigin.Current);
537
+
538
+ // Size of first headword
539
+ int textHeadSize = ReadU8OrU16(br, isU16);
540
+
541
+ // Skip first headword
542
+ int skipLen = 0;
543
+ if (Encoding == "UTF-16LE")
544
+ skipLen = (textHeadSize + textTermSize) * 2;
545
+ else
546
+ skipLen = (textHeadSize + textTermSize);
547
+ ms.Seek(skipLen, SeekOrigin.Current);
548
+
549
+ // Size of last headword
550
+ int textTailSize = ReadU8OrU16(br, isU16);
551
+
552
+ // Skip last headword
553
+ if (Encoding == "UTF-16LE")
554
+ skipLen = (textTailSize + textTermSize) * 2;
555
+ else
556
+ skipLen = (textTailSize + textTermSize);
557
+ ms.Seek(skipLen, SeekOrigin.Current);
558
+
559
+ // Sizes
560
+ long comp = ReadNumber(br, v2);
561
+ long decomp = ReadNumber(br, v2);
562
+
563
+ list.Add(new Tuple<long, long>(comp, decomp));
564
+ }
565
+ }
566
+ return list;
567
+ }
568
+
569
+ private int ReadU8OrU16(BinaryReader br, bool isU16)
570
+ {
571
+ if (isU16)
572
+ {
573
+ var b = br.ReadBytes(2);
574
+ Array.Reverse(b);
575
+ return BitConverter.ToUInt16(b, 0);
576
+ }
577
+ else
578
+ return br.ReadByte();
579
+ }
580
+
581
+ private void SplitHeadBlock(byte[] data, bool v2)
582
+ {
583
+ int numberTypeSize = v2 ? 8 : 4;
584
+ int offset = 0;
585
+
586
+ while (offset < data.Length)
587
+ {
588
+ // Read Offset
589
+ long recordOffset = 0;
590
+ if (numberTypeSize == 8)
591
+ {
592
+ if (offset + 8 > data.Length) break;
593
+ // BigEndian
594
+ recordOffset = BitConverter.ToInt64(data.Skip(offset).Take(8).Reverse().ToArray(), 0);
595
+ offset += 8;
596
+ }
597
+ else
598
+ {
599
+ if (offset + 4 > data.Length) break;
600
+ recordOffset = BitConverter.ToUInt32(data.Skip(offset).Take(4).Reverse().ToArray(), 0);
601
+ offset += 4;
602
+ }
603
+
604
+ // Read Text (Null terminated)
605
+ // If UTF-16LE, null terminator is \0\0
606
+ string text = "";
607
+ if (Encoding == "UTF-16LE")
608
+ {
609
+ int start = offset;
610
+ while (offset + 1 < data.Length)
611
+ {
612
+ if (data[offset] == 0 && data[offset+1] == 0)
613
+ {
614
+ break;
615
+ }
616
+ offset += 2;
617
+ }
618
+ int len = offset - start;
619
+ text = System.Text.Encoding.Unicode.GetString(data, start, len);
620
+ offset += 2; // Skip \0\0
621
+ }
622
+ else
623
+ {
624
+ int start = offset;
625
+ while (offset < data.Length)
626
+ {
627
+ if (data[offset] == 0) break;
628
+ offset++;
629
+ }
630
+ int len = offset - start;
631
+ // Assume encoding
632
+ var enc = System.Text.Encoding.GetEncoding(Encoding == "GB18030" ? "GB18030" : "UTF-8"); // Fallback
633
+ // Note: .NET might not support GB18030 out of the box without registration, using UTF8 as fallback or just GetEncoding if available.
634
+ // For now let's assume standard encodings.
635
+ try {
636
+ text = enc.GetString(data, start, len);
637
+ } catch {
638
+ text = System.Text.Encoding.UTF8.GetString(data, start, len);
639
+ }
640
+ offset++; // Skip \0
641
+ }
642
+
643
+ // Add to Index
644
+ if (!Index.ContainsKey(text))
645
+ {
646
+ Index[text] = recordOffset;
647
+ Headwords.Add(text);
648
+ }
649
+ }
650
+ }
651
+
652
+ private byte[] Decompress(byte[] input, int outputSize)
653
+ {
654
+ // Check type
655
+ // 4 bytes header: type (0=none, 1=lzo, 2=zlib)
656
+ // 4 bytes checksum
657
+ if (input.Length < 8) return input;
658
+
659
+ int type = BitConverter.ToInt32(input.Take(4).Reverse().ToArray(), 0);
660
+ uint checksum = BitConverter.ToUInt32(input.Skip(4).Take(4).Reverse().ToArray(), 0);
661
+
662
+ byte[] result = null;
663
+
664
+ if (type == 0) // No compression
665
+ {
666
+ result = input.Skip(8).ToArray();
667
+ }
668
+ else if (type == 0x02000000) // Zlib
669
+ {
670
+ using (var ms = new MemoryStream(input, 8, input.Length - 8))
671
+ using (var zs = new ZLibStream(ms, CompressionMode.Decompress))
672
+ using (var outMs = new MemoryStream(outputSize))
673
+ {
674
+ zs.CopyTo(outMs);
675
+ result = outMs.ToArray();
676
+ }
677
+ }
678
+ else if (type == 0x01000000) // LZO
679
+ {
680
+ byte[] compressedPayload = new byte[input.Length - 8];
681
+ Array.Copy(input, 8, compressedPayload, 0, input.Length - 8);
682
+ try
683
+ {
684
+ result = Lzo.Decompress(compressedPayload, outputSize);
685
+ }
686
+ catch (Exception ex)
687
+ {
688
+ // Fallback or rethrow
689
+ throw new Exception($"LZO Decompression failed: {ex.Message}");
690
+ }
691
+ }
692
+
693
+ if (result != null)
694
+ {
695
+ var adler = new Adler32();
696
+ adler.Update(result, 0, result.Length);
697
+ if (adler.Value != checksum)
698
+ {
699
+ throw new Exception($"Checksum mismatch. Expected {checksum:X8}, got {adler.Value:X8}");
700
+ }
701
+ return result;
702
+ }
703
+
704
+ return new byte[0];
705
+ }
706
+
707
+ private long GetRecordBlockCompressedSize()
708
+ {
709
+ if (_numberWidth == 8)
710
+ return (long)ReadUInt64BE(_reader);
711
+ else
712
+ return (long)ReadUInt32BE(_reader);
713
+ }
714
+
715
+ private long ReadNumber(BinaryReader br, bool v2)
716
+ {
717
+ if (v2) return (long)ReadUInt64BE(br);
718
+ return (long)ReadUInt32BE(br);
719
+ }
720
+
721
+ private int ReadInt32BE()
722
+ {
723
+ var b = _reader.ReadBytes(4);
724
+ Array.Reverse(b);
725
+ return BitConverter.ToInt32(b, 0);
726
+ }
727
+
728
+ private uint ReadInt32LE()
729
+ {
730
+ return _reader.ReadUInt32();
731
+ }
732
+
733
+ private uint ReadUInt32BE(BinaryReader br)
734
+ {
735
+ var b = br.ReadBytes(4);
736
+ Array.Reverse(b);
737
+ return BitConverter.ToUInt32(b, 0);
738
+ }
739
+
740
+ private ulong ReadUInt64BE(BinaryReader br)
741
+ {
742
+ var b = br.ReadBytes(8);
743
+ Array.Reverse(b);
744
+ return BitConverter.ToUInt64(b, 0);
745
+ }
746
+
747
+ private Dictionary<string, string> ParseXmlAttributes(string xml)
748
+ {
749
+ var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
750
+ // Regex to find attributes key="value"
751
+ var matches = Regex.Matches(xml, "(\\w+)=\"([^\"]*)\"");
752
+ foreach (Match m in matches)
753
+ {
754
+ dict[m.Groups[1].Value] = m.Groups[2].Value;
755
+ }
756
+ return dict;
757
+ }
758
+
759
+ public void Dispose()
760
+ {
761
+ _reader?.Close();
762
+ _fs?.Close();
763
+ }
764
+ }
765
+ }
src/EchoDictLib/Ripemd128.cs ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System;
2
+
3
+ namespace Echodict
4
+ {
5
+ public class Ripemd128
6
+ {
7
+ private static readonly uint[] KA = { 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e };
8
+ private static readonly uint[] KB = { 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9 };
9
+
10
+ private static readonly int[] ROTA = {
11
+ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13,
12
+ 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15,
13
+ 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6,
14
+ 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
15
+ };
16
+
17
+ private static readonly int[] ROTB = {
18
+ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7,
19
+ 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14,
20
+ 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9,
21
+ 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
22
+ };
23
+
24
+ private static readonly int[] WA = {
25
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1,
26
+ 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1,
27
+ 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15,
28
+ 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
29
+ };
30
+
31
+ private static readonly int[] WB = {
32
+ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7,
33
+ 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9,
34
+ 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13,
35
+ 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
36
+ };
37
+
38
+ private ulong _count;
39
+ private byte[] _buffer = new byte[64];
40
+ private uint[] _state = new uint[4];
41
+
42
+ public Ripemd128()
43
+ {
44
+ _state[0] = 0x67452301;
45
+ _state[1] = 0xEFCDAB89;
46
+ _state[2] = 0x98BADCFE;
47
+ _state[3] = 0x10325476;
48
+ _count = 0;
49
+ }
50
+
51
+ private static uint Rol(uint value, int bits)
52
+ {
53
+ return (value << bits) | (value >> (32 - bits));
54
+ }
55
+
56
+ private void Transform(byte[] buffer, int offset = 0)
57
+ {
58
+ uint a = _state[0];
59
+ uint b = _state[1];
60
+ uint c = _state[2];
61
+ uint d = _state[3];
62
+ uint e = _state[0];
63
+ uint f = _state[1];
64
+ uint g = _state[2];
65
+ uint h = _state[3];
66
+
67
+ uint[] block = new uint[16];
68
+ for (int i = 0; i < 16; i++)
69
+ {
70
+ block[i] = BitConverter.ToUInt32(buffer, offset + 4 * i);
71
+ }
72
+
73
+ int n = 0;
74
+ // Round 1 (0-15)
75
+ // R128_0
76
+ for (int k = 0; k < 4; k++)
77
+ {
78
+ // Round0To15(a, b, c, d, e, f, g, h)
79
+ a = Rol(a + ((b ^ c ^ d) + block[WA[n]]), ROTA[n]);
80
+ e = Rol(e + ((((f ^ g) & h) ^ g) + block[WB[n]] + KB[0]), ROTB[n]);
81
+ n++;
82
+
83
+ // Round0To15(d, a, b, c, h, e, f, g)
84
+ d = Rol(d + ((a ^ b ^ c) + block[WA[n]]), ROTA[n]);
85
+ h = Rol(h + ((((e ^ f) & g) ^ f) + block[WB[n]] + KB[0]), ROTB[n]);
86
+ n++;
87
+
88
+ // Round0To15(c, d, a, b, g, h, e, f)
89
+ c = Rol(c + ((d ^ a ^ b) + block[WA[n]]), ROTA[n]);
90
+ g = Rol(g + ((((h ^ e) & f) ^ e) + block[WB[n]] + KB[0]), ROTB[n]);
91
+ n++;
92
+
93
+ // Round0To15(b, c, d, a, f, g, h, e)
94
+ b = Rol(b + ((c ^ d ^ a) + block[WA[n]]), ROTA[n]);
95
+ f = Rol(f + ((((g ^ h) & e) ^ h) + block[WB[n]] + KB[0]), ROTB[n]);
96
+ n++;
97
+ }
98
+
99
+ // Round 2 (16-31)
100
+ // R128_16
101
+ for (int k = 0; k < 4; k++)
102
+ {
103
+ // Round16To31(a, b, c, d, e, f, g, h)
104
+ // f1 = ((c^d)&b)^d; f2 = (~g|f)^h
105
+ a = Rol(a + ((((c ^ d) & b) ^ d) + block[WA[n]] + KA[0]), ROTA[n]);
106
+ e = Rol(e + (((~g | f) ^ h) + block[WB[n]] + KB[1]), ROTB[n]);
107
+ n++;
108
+
109
+ // Round16To31(d, a, b, c, h, e, f, g)
110
+ // f1 = ((b^c)&a)^c; f2 = (~f|e)^g
111
+ d = Rol(d + ((((b ^ c) & a) ^ c) + block[WA[n]] + KA[0]), ROTA[n]);
112
+ h = Rol(h + (((~f | e) ^ g) + block[WB[n]] + KB[1]), ROTB[n]);
113
+ n++;
114
+
115
+ // Round16To31(c, d, a, b, g, h, e, f)
116
+ // f1 = ((a^b)&d)^b; f2 = (~e|h)^f
117
+ c = Rol(c + ((((a ^ b) & d) ^ b) + block[WA[n]] + KA[0]), ROTA[n]);
118
+ g = Rol(g + (((~e | h) ^ f) + block[WB[n]] + KB[1]), ROTB[n]);
119
+ n++;
120
+
121
+ // Round16To31(b, c, d, a, f, g, h, e)
122
+ // f1 = ((d^a)&c)^a; f2 = (~h|g)^e
123
+ b = Rol(b + ((((d ^ a) & c) ^ a) + block[WA[n]] + KA[0]), ROTA[n]);
124
+ f = Rol(f + (((~h | g) ^ e) + block[WB[n]] + KB[1]), ROTB[n]);
125
+ n++;
126
+ }
127
+
128
+ // Round 3 (32-47)
129
+ // R128_32
130
+ for (int k = 0; k < 4; k++)
131
+ {
132
+ // Round32To47(a, b, c, d, e, f, g, h)
133
+ // f1 = (~c|b)^d; f2 = ((g^h)&f)^h
134
+ a = Rol(a + (((~c | b) ^ d) + block[WA[n]] + KA[1]), ROTA[n]);
135
+ e = Rol(e + ((((g ^ h) & f) ^ h) + block[WB[n]] + KB[2]), ROTB[n]);
136
+ n++;
137
+
138
+ // Round32To47(d, a, b, c, h, e, f, g)
139
+ // f1 = (~b|a)^c; f2 = ((f^g)&e)^g
140
+ d = Rol(d + (((~b | a) ^ c) + block[WA[n]] + KA[1]), ROTA[n]);
141
+ h = Rol(h + ((((f ^ g) & e) ^ g) + block[WB[n]] + KB[2]), ROTB[n]);
142
+ n++;
143
+
144
+ // Round32To47(c, d, a, b, g, h, e, f)
145
+ // f1 = (~a|d)^b; f2 = ((e^f)&h)^f
146
+ c = Rol(c + (((~a | d) ^ b) + block[WA[n]] + KA[1]), ROTA[n]);
147
+ g = Rol(g + ((((e ^ f) & h) ^ f) + block[WB[n]] + KB[2]), ROTB[n]);
148
+ n++;
149
+
150
+ // Round32To47(b, c, d, a, f, g, h, e)
151
+ // f1 = (~d|c)^a; f2 = ((h^e)&g)^e
152
+ b = Rol(b + (((~d | c) ^ a) + block[WA[n]] + KA[1]), ROTA[n]);
153
+ f = Rol(f + ((((h ^ e) & g) ^ e) + block[WB[n]] + KB[2]), ROTB[n]);
154
+ n++;
155
+ }
156
+
157
+ // Round 4 (48-63)
158
+ // R128_48
159
+ for (int k = 0; k < 4; k++)
160
+ {
161
+ // Round48To63(a, b, c, d, e, f, g, h)
162
+ // f1 = ((b^c)&d)^c; f2 = f^g^h
163
+ a = Rol(a + ((((b ^ c) & d) ^ c) + block[WA[n]] + KA[2]), ROTA[n]);
164
+ e = Rol(e + ((f ^ g ^ h) + block[WB[n]]), ROTB[n]);
165
+ n++;
166
+
167
+ // Round48To63(d, a, b, c, h, e, f, g)
168
+ // f1 = ((a^b)&c)^b; f2 = e^f^g
169
+ d = Rol(d + ((((a ^ b) & c) ^ b) + block[WA[n]] + KA[2]), ROTA[n]);
170
+ h = Rol(h + ((e ^ f ^ g) + block[WB[n]]), ROTB[n]);
171
+ n++;
172
+
173
+ // Round48To63(c, d, a, b, g, h, e, f)
174
+ // f1 = ((d^a)&b)^a; f2 = h^e^f
175
+ c = Rol(c + ((((d ^ a) & b) ^ a) + block[WA[n]] + KA[2]), ROTA[n]);
176
+ g = Rol(g + ((h ^ e ^ f) + block[WB[n]]), ROTB[n]);
177
+ n++;
178
+
179
+ // Round48To63(b, c, d, a, f, g, h, e)
180
+ // f1 = ((c^d)&a)^d; f2 = g^h^e
181
+ b = Rol(b + ((((c ^ d) & a) ^ d) + block[WA[n]] + KA[2]), ROTA[n]);
182
+ f = Rol(f + ((g ^ h ^ e) + block[WB[n]]), ROTB[n]);
183
+ n++;
184
+ }
185
+
186
+ h += c + _state[1];
187
+ _state[1] = _state[2] + d + e;
188
+ _state[2] = _state[3] + a + f;
189
+ _state[3] = _state[0] + b + g;
190
+ _state[0] = h;
191
+ }
192
+
193
+ public void Update(byte[] data, int offset, int len)
194
+ {
195
+ int i, j;
196
+ j = (int)(_count & 63);
197
+ _count += (ulong)len;
198
+
199
+ if ((j + len) > 63)
200
+ {
201
+ Array.Copy(data, offset, _buffer, j, 64 - j);
202
+ Transform(_buffer);
203
+ i = 64 - j;
204
+ for (; i + 63 < len; i += 64)
205
+ {
206
+ Transform(data, offset + i);
207
+ }
208
+ j = 0;
209
+ }
210
+ else
211
+ {
212
+ i = 0;
213
+ }
214
+ Array.Copy(data, offset + i, _buffer, j, len - i);
215
+ }
216
+
217
+ public void Update(byte[] data)
218
+ {
219
+ Update(data, 0, data.Length);
220
+ }
221
+
222
+ public byte[] Digest()
223
+ {
224
+ ulong finalcount = _count << 3;
225
+ Update(new byte[] { 0x80 }, 0, 1);
226
+ while ((_count & 63) != 56)
227
+ {
228
+ Update(new byte[] { 0 }, 0, 1);
229
+ }
230
+
231
+ byte[] countBytes = BitConverter.GetBytes(finalcount); // Little endian
232
+ Update(countBytes, 0, 8);
233
+
234
+ byte[] digest = new byte[16];
235
+ for (int i = 0; i < 4; i++)
236
+ {
237
+ byte[] b = BitConverter.GetBytes(_state[i]);
238
+ Array.Copy(b, 0, digest, i * 4, 4);
239
+ }
240
+ return digest;
241
+ }
242
+ }
243
+ }
src/WpfEditor/EchoDictWindow.xaml CHANGED
@@ -1,8 +1,157 @@
1
- <Window x:Class="WpfEditor.EchoDictWindow"
2
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4
- Title="Echodict" Height="200" Width="400">
5
- <Grid>
6
- <TextBlock x:Name="textBlock" TextWrapping="Wrap" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="16" />
7
- </Grid>
8
- </Window>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <Window x:Class="Echodict.EchodictWindow"
2
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4
+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
5
+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
6
+ xmlns:cef="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
7
+ xmlns:local="clr-namespace:Echodict"
8
+ mc:Ignorable="d"
9
+ Title="EchoDict" Height="538" Width="800">
10
+ <DockPanel>
11
+ <!-- Menu Bar -->
12
+ <Menu DockPanel.Dock="Top">
13
+ <MenuItem Header="_File">
14
+ <MenuItem Header="New Tab" InputGestureText="Ctrl+T" />
15
+ <Separator />
16
+ <MenuItem Header="Page Setup..." />
17
+ <MenuItem Header="Print Preview..." />
18
+ <MenuItem Header="Print..." InputGestureText="Ctrl+P" />
19
+ <Separator />
20
+ <MenuItem Header="Save Article..." InputGestureText="F2" />
21
+ <Separator />
22
+ <MenuItem Header="Rescan Files" InputGestureText="Ctrl+F5" Click="BtnRescan_Click"/>
23
+ <Separator />
24
+ <MenuItem Header="Close To Tray" InputGestureText="Ctrl+F4" />
25
+ <MenuItem Header="Quit" InputGestureText="Ctrl+Q" Click="BtnQuit_Click"/>
26
+ </MenuItem>
27
+ <MenuItem Header="_Edit">
28
+ <MenuItem Header="Dictionaries..." InputGestureText="F3" Click="BtnAddDict_Click"/>
29
+ <MenuItem Header="Preferences..." InputGestureText="F4" />
30
+ </MenuItem>
31
+ <MenuItem Header="_View">
32
+ <MenuItem Header="Zoom">
33
+ <MenuItem Header="Zoom In" InputGestureText="Ctrl++" />
34
+ <MenuItem Header="Zoom Out" InputGestureText="Ctrl+-" />
35
+ <MenuItem Header="Normal Size" InputGestureText="Ctrl+0" />
36
+ </MenuItem>
37
+ <Separator />
38
+ <MenuItem Header="Show Small Icons in Toolbars" IsCheckable="True" />
39
+ <MenuItem Header="Show Large Icons in Toolbars" IsCheckable="True" />
40
+ <MenuItem Header="Show Normal Icons in Toolbars" IsCheckable="True" IsChecked="True" />
41
+ </MenuItem>
42
+ <MenuItem Header="_History">
43
+ <MenuItem Header="Show" InputGestureText="Ctrl+H" />
44
+ <MenuItem Header="Export" />
45
+ <MenuItem Header="Import" />
46
+ <Separator />
47
+ <MenuItem Header="Clear" Click="BtnClearHistory_Click"/>
48
+ </MenuItem>
49
+ <MenuItem Header="S_earch">
50
+ <MenuItem Header="Search in page" InputGestureText="Ctrl+F" />
51
+ <MenuItem Header="Full-text search" InputGestureText="Ctrl+Shift+F" />
52
+ </MenuItem>
53
+ <MenuItem Header="Favo_rites">
54
+ <MenuItem Header="Show" InputGestureText="Ctrl+I" />
55
+ <MenuItem Header="Export" />
56
+ <MenuItem Header="Import" />
57
+ <Separator />
58
+ <MenuItem Header="Add" InputGestureText="Ctrl+E" />
59
+ </MenuItem>
60
+ <MenuItem Header="_Help">
61
+ <MenuItem Header="EchoDict reference" InputGestureText="F1" />
62
+ <Separator />
63
+ <MenuItem Header="Homepage" />
64
+ <MenuItem Header="Forum" />
65
+ <Separator />
66
+ <MenuItem Header="Configuration Folder" InputGestureText="F11" />
67
+ <Separator />
68
+ <MenuItem Header="About" />
69
+ </MenuItem>
70
+ </Menu>
71
+
72
+ <!-- Toolbar -->
73
+ <ToolBarTray DockPanel.Dock="Top">
74
+ <ToolBar>
75
+ <Button Content="Back" ToolTip="Back" Click="BtnBack_Click" />
76
+ <Button Content="Forward" ToolTip="Forward" Click="BtnForward_Click" />
77
+ <Separator />
78
+ <ComboBox x:Name="DictSelector" Width="150" IsEditable="False" SelectionChanged="DictSelector_SelectionChanged">
79
+ </ComboBox>
80
+ <Separator />
81
+ <Button Content="Scan" ToolTip="Toggle clipboard monitoring" />
82
+ <Separator />
83
+ <Button Content="Pronounce" ToolTip="Pronounce Word (Alt+S)" IsEnabled="False" />
84
+ <Separator />
85
+ <Button Content="In" ToolTip="Zoom In" />
86
+ <Button Content="Out" ToolTip="Zoom Out" />
87
+ <Button Content="1:1" ToolTip="Normal Size" />
88
+ <Separator />
89
+ <Button Content="Save" ToolTip="Save Article" />
90
+ <Button Content="Print" ToolTip="Print" />
91
+ <Separator />
92
+ <Button Content="Fav" ToolTip="Add current tab to Favorites" />
93
+ </ToolBar>
94
+ </ToolBarTray>
95
+
96
+ <!-- Main Content Grid -->
97
+ <Grid>
98
+ <Grid.ColumnDefinitions>
99
+ <ColumnDefinition Width="200" MinWidth="100" />
100
+ <ColumnDefinition Width="Auto" />
101
+ <ColumnDefinition Width="*" />
102
+ <ColumnDefinition Width="Auto" />
103
+ <ColumnDefinition Width="200" MinWidth="100" />
104
+ </Grid.ColumnDefinitions>
105
+
106
+ <!-- Left Pane: Search Pane -->
107
+ <Grid Grid.Column="0">
108
+ <Grid.RowDefinitions>
109
+ <RowDefinition Height="Auto" />
110
+ <RowDefinition Height="*" />
111
+ </Grid.RowDefinitions>
112
+ <!-- Title Bar Simulation -->
113
+ <Border Background="{DynamicResource {x:Static SystemColors.ActiveCaptionBrushKey}}" Padding="2">
114
+ <TextBlock Text="Search Pane" Foreground="{DynamicResource {x:Static SystemColors.ActiveCaptionTextBrushKey}}" FontWeight="Bold"/>
115
+ </Border>
116
+
117
+ <DockPanel Grid.Row="1" LastChildFill="True">
118
+ <TextBox DockPanel.Dock="Top" x:Name="SideSearchBox" Margin="2" KeyUp="TxtSearch_KeyUp" />
119
+ <ListBox x:Name="WordList" Margin="2" SelectionChanged="WordList_SelectionChanged" />
120
+ </DockPanel>
121
+ </Grid>
122
+
123
+ <!-- Splitter 1 -->
124
+ <GridSplitter Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Stretch" Width="3" Background="LightGray" />
125
+
126
+ <!-- Center Pane: Tab Widget -->
127
+ <TabControl Grid.Column="2" x:Name="MainTabControl">
128
+ <TabItem Header="New Tab">
129
+ <cef:ChromiumWebBrowser x:Name="Browser" />
130
+ </TabItem>
131
+ </TabControl>
132
+
133
+ <!-- Splitter 2 -->
134
+ <GridSplitter Grid.Column="3" HorizontalAlignment="Center" VerticalAlignment="Stretch" Width="3" Background="LightGray" />
135
+
136
+ <!-- Right Pane: Results/Favorites/History -->
137
+ <Grid Grid.Column="4">
138
+ <TabControl>
139
+ <TabItem Header="Results">
140
+ <DockPanel>
141
+ <Border DockPanel.Dock="Top" Background="{DynamicResource {x:Static SystemColors.ActiveCaptionBrushKey}}" Padding="2">
142
+ <TextBlock Text="Found in Dictionaries:" Foreground="{DynamicResource {x:Static SystemColors.ActiveCaptionTextBrushKey}}" FontWeight="Bold"/>
143
+ </Border>
144
+ <ListBox x:Name="DictsList" Margin="2" />
145
+ </DockPanel>
146
+ </TabItem>
147
+ <TabItem Header="Favorites">
148
+ <TreeView x:Name="FavoritesTree" Margin="2" />
149
+ </TabItem>
150
+ <TabItem Header="History">
151
+ <ListBox x:Name="HistoryList" Margin="2" SelectionChanged="HistoryList_SelectionChanged" />
152
+ </TabItem>
153
+ </TabControl>
154
+ </Grid>
155
+ </Grid>
156
+ </DockPanel>
157
+ </Window>
src/WpfEditor/EchoDictWindow.xaml.cs CHANGED
@@ -1,13 +1,509 @@
 
 
1
  using System.Windows;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- namespace WpfEditor
4
  {
5
- public partial class EchoDictWindow : Window
 
 
 
6
  {
7
- public EchoDictWindow(string text)
 
 
 
 
 
 
8
  {
9
  InitializeComponent();
10
- textBlock.Text = text;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  }
12
  }
13
- }
 
1
+ using System;
2
+ using System.Text;
3
  using System.Windows;
4
+ using System.Windows.Controls;
5
+ using System.Windows.Data;
6
+ using System.Windows.Documents;
7
+ using System.Windows.Input;
8
+ using System.Windows.Media;
9
+ using System.Windows.Media.Imaging;
10
+ using System.Windows.Navigation;
11
+ using System.Windows.Shapes;
12
+ using Microsoft.Win32;
13
+ using System.Collections.Generic;
14
+ using System.Linq;
15
+ using CefSharp;
16
+ using CefSharp.Wpf;
17
+ using System.Text.Json;
18
 
19
+ namespace Echodict
20
  {
21
+ /// <summary>
22
+ /// Interaction logic for EchodictWindow.xaml
23
+ /// </summary>
24
+ public partial class EchodictWindow : Window
25
  {
26
+ private List<Dictionary> _dicts = new List<Dictionary>();
27
+ private List<string> _sourcePaths = new List<string>();
28
+ private List<DictGroup> _groups = new List<DictGroup>();
29
+ private string _currentSelectionId = "ALL";
30
+ private bool _isReady = false;
31
+
32
+ public EchodictWindow()
33
  {
34
  InitializeComponent();
35
+ LoadConfig();
36
+
37
+ // Initial scan if we have paths but no dicts loaded yet
38
+ if (_sourcePaths.Count > 0)
39
+ {
40
+ Loaded += (s, e) => ScanAndLoadDictionaries();
41
+ }
42
+ else
43
+ {
44
+ // Initialize empty selector
45
+ RefreshDictSelector();
46
+ }
47
+
48
+ Browser.RequestHandler = new DictRequestHandler(_dicts, (query) =>
49
+ {
50
+ Dispatcher.Invoke(() =>
51
+ {
52
+ SideSearchBox.Text = query;
53
+ Search(query, true);
54
+ });
55
+ });
56
+
57
+ _isReady = true;
58
+ }
59
+
60
+ private void LoadConfig()
61
+ {
62
+ try
63
+ {
64
+ string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "echodictconfig.json");
65
+ if (System.IO.File.Exists(path))
66
+ {
67
+ string json = System.IO.File.ReadAllText(path);
68
+ var config = JsonSerializer.Deserialize<EchodictConfig>(json);
69
+ if (config != null)
70
+ {
71
+ _sourcePaths = config.SourcePaths ?? new List<string>();
72
+ _groups = config.Groups ?? new List<DictGroup>();
73
+ _currentSelectionId = config.LastSelectedDictId ?? "ALL";
74
+
75
+ if (config.History != null)
76
+ {
77
+ foreach (var item in config.History)
78
+ {
79
+ HistoryList.Items.Add(item);
80
+ }
81
+ }
82
+ }
83
+ }
84
+ }
85
+ catch (Exception ex)
86
+ {
87
+ System.Diagnostics.Debug.WriteLine($"Error loading config: {ex.Message}");
88
+ }
89
+ }
90
+
91
+ private void SaveConfig()
92
+ {
93
+ try
94
+ {
95
+ var config = new EchodictConfig
96
+ {
97
+ SourcePaths = _sourcePaths,
98
+ Groups = _groups,
99
+ LastSelectedDictId = _currentSelectionId,
100
+ History = HistoryList.Items.Cast<string>().ToList()
101
+ };
102
+ var options = new JsonSerializerOptions
103
+ {
104
+ WriteIndented = true,
105
+ Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
106
+ };
107
+ string json = JsonSerializer.Serialize(config, options);
108
+ string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "echodictconfig.json");
109
+ System.IO.File.WriteAllText(path, json, Encoding.UTF8);
110
+ }
111
+ catch (Exception ex)
112
+ {
113
+ System.Diagnostics.Debug.WriteLine($"Error saving config: {ex.Message}");
114
+ }
115
+ }
116
+
117
+ private void BtnAddDict_Click(object sender, RoutedEventArgs e)
118
+ {
119
+ var dlg = new EditDictionaries(_sourcePaths, _groups, _dicts);
120
+ dlg.Owner = this;
121
+ if (dlg.ShowDialog() == true)
122
+ {
123
+ _sourcePaths = dlg.SourcePaths;
124
+ _groups = dlg.Groups;
125
+
126
+ // Save immediately
127
+ SaveConfig();
128
+
129
+ if (dlg.NeedsRescan)
130
+ {
131
+ ScanAndLoadDictionaries();
132
+ }
133
+ else
134
+ {
135
+ // If groups changed but no rescan needed, just refresh selector
136
+ RefreshDictSelector();
137
+ }
138
+ }
139
+ }
140
+
141
+ private void BtnRescan_Click(object sender, RoutedEventArgs e)
142
+ {
143
+ bool force = (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control;
144
+ if (force)
145
+ {
146
+ if (MessageBox.Show("Force rebuild all indexes? This may take time.", "Rebuild Indexes", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
147
+ {
148
+ return;
149
+ }
150
+ }
151
+ ScanAndLoadDictionaries(force);
152
+ }
153
+
154
+ private void ScanAndLoadDictionaries(bool forceRebuild = false)
155
+ {
156
+ // Dispose existing dictionaries
157
+ foreach (var dict in _dicts)
158
+ {
159
+ dict.Dispose();
160
+ }
161
+ _dicts.Clear();
162
+ DictsList.Items.Clear();
163
+
164
+ string cacheDir = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache");
165
+ if (!System.IO.Directory.Exists(cacheDir))
166
+ {
167
+ System.IO.Directory.CreateDirectory(cacheDir);
168
+ }
169
+
170
+ foreach (var path in _sourcePaths)
171
+ {
172
+ if (System.IO.Directory.Exists(path))
173
+ {
174
+ try
175
+ {
176
+ var files = System.IO.Directory.GetFiles(path, "*.mdx", System.IO.SearchOption.AllDirectories);
177
+ foreach (var file in files)
178
+ {
179
+ try
180
+ {
181
+ LoadDictionary(file, cacheDir, forceRebuild);
182
+ }
183
+ catch (Exception ex)
184
+ {
185
+ System.Diagnostics.Debug.WriteLine($"Failed to load {file}: {ex.Message}");
186
+ }
187
+ }
188
+ }
189
+ catch (Exception ex)
190
+ {
191
+ System.Diagnostics.Debug.WriteLine($"Failed to scan {path}: {ex.Message}");
192
+ }
193
+ }
194
+ }
195
+
196
+ RefreshDictSelector();
197
+ SaveConfig(); // Save to persist any state if needed, though mostly redundant here
198
+
199
+ // MessageBox.Show($"Loaded {_dicts.Count} dictionaries.", "Scan Complete");
200
+ }
201
+
202
+ private void RefreshDictSelector()
203
+ {
204
+ // Preserve selection if possible?
205
+ // For now reset to All
206
+ DictSelector.Items.Clear();
207
+
208
+ var allItem = new ComboBoxItem { Content = "All Dictionaries", Tag = "ALL" };
209
+ DictSelector.Items.Add(allItem);
210
+
211
+ // Groups
212
+ foreach (var group in _groups)
213
+ {
214
+ DictSelector.Items.Add(new ComboBoxItem { Content = $"[Group] {group.Name}", Tag = group });
215
+ }
216
+
217
+ // Individual Dictionaries
218
+ foreach (var dict in _dicts)
219
+ {
220
+ DictSelector.Items.Add(new ComboBoxItem { Content = dict.Name, Tag = dict });
221
+ }
222
+
223
+ // Restore selection
224
+ bool matched = false;
225
+ foreach (ComboBoxItem item in DictSelector.Items)
226
+ {
227
+ if (GetItemId(item) == _currentSelectionId)
228
+ {
229
+ DictSelector.SelectedItem = item;
230
+ matched = true;
231
+ break;
232
+ }
233
+ }
234
+
235
+ if (!matched)
236
+ {
237
+ DictSelector.SelectedIndex = 0;
238
+ }
239
+ }
240
+
241
+ private string GetItemId(ComboBoxItem item)
242
+ {
243
+ if (item.Tag is string s && s == "ALL") return "ALL";
244
+ if (item.Tag is DictGroup g) return "GROUP:" + g.Name;
245
+ if (item.Tag is Dictionary d) return "DICT:" + d.Id;
246
+ return "";
247
+ }
248
+
249
+ private void BtnClearHistory_Click(object sender, RoutedEventArgs e)
250
+ {
251
+ if (MessageBox.Show("Are you sure you want to clear the history?", "Clear History", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
252
+ {
253
+ HistoryList.Items.Clear();
254
+ SaveConfig();
255
+ }
256
+ }
257
+
258
+ private void BtnBack_Click(object sender, RoutedEventArgs e)
259
+ {
260
+ if (HistoryList.Items.Count == 0) return;
261
+
262
+ int newIndex = HistoryList.SelectedIndex + 1;
263
+
264
+ // If nothing is selected, we assume we are at the "latest" state (conceptually index 0 is current),
265
+ // so Back should go to index 1.
266
+ // Note: If we just added an item, it is at index 0 but typically not selected.
267
+ if (HistoryList.SelectedIndex == -1)
268
+ {
269
+ newIndex = 1;
270
+ }
271
+
272
+ if (newIndex < HistoryList.Items.Count)
273
+ {
274
+ HistoryList.SelectedIndex = newIndex;
275
+ HistoryList.ScrollIntoView(HistoryList.SelectedItem);
276
+ }
277
+ }
278
+
279
+ private void BtnForward_Click(object sender, RoutedEventArgs e)
280
+ {
281
+ if (HistoryList.Items.Count == 0) return;
282
+
283
+ if (HistoryList.SelectedIndex > 0)
284
+ {
285
+ HistoryList.SelectedIndex = HistoryList.SelectedIndex - 1;
286
+ HistoryList.ScrollIntoView(HistoryList.SelectedItem);
287
+ }
288
+ // If SelectedIndex is -1 or 0, we are already at the latest, so do nothing.
289
+ }
290
+
291
+ private void BtnQuit_Click(object sender, RoutedEventArgs e)
292
+ {
293
+ Close();
294
+ }
295
+
296
+ private void LoadDictionary(string path, string cacheDir, bool forceRebuild)
297
+ {
298
+ Dictionary dict = new Dictionary(path, cacheDir, forceRebuild);
299
+ _dicts.Add(dict);
300
+ }
301
+
302
+ private void TxtSearch_KeyUp(object sender, KeyEventArgs e)
303
+ {
304
+ if (e.Key == Key.Enter)
305
+ {
306
+ Search(SideSearchBox.Text.Trim(), true);
307
+ }
308
+ }
309
+
310
+ private void Search(string query, bool updateWordList, bool updateHistory = true)
311
+ {
312
+ if (string.IsNullOrEmpty(query)) return;
313
+
314
+ if (updateWordList)
315
+ {
316
+ WordList.Items.Clear();
317
+ }
318
+
319
+ // Clear the dictionary list in the result panel
320
+ DictsList.Items.Clear();
321
+
322
+ StringBuilder sb = new StringBuilder();
323
+ sb.Append("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><style>img { max-width: 100%; }</style></head><body>");
324
+
325
+ bool found = false;
326
+
327
+ // Determine which dictionaries to search
328
+ List<Dictionary> targetDicts = new List<Dictionary>();
329
+
330
+ if (DictSelector.SelectedItem is ComboBoxItem selectedItem)
331
+ {
332
+ if (selectedItem.Tag is string s && s == "ALL")
333
+ {
334
+ targetDicts = _dicts;
335
+ }
336
+ else if (selectedItem.Tag is DictGroup group)
337
+ {
338
+ targetDicts = _dicts.Where(d => group.DictionaryPaths.Contains(d.Mdx.Filename)).ToList();
339
+ }
340
+ else if (selectedItem.Tag is Dictionary dict)
341
+ {
342
+ targetDicts = new List<Dictionary> { dict };
343
+ }
344
+ }
345
+ else
346
+ {
347
+ // Fallback
348
+ targetDicts = _dicts;
349
+ }
350
+
351
+ foreach (var dict in targetDicts)
352
+ {
353
+ if (dict.Mdx.Index.ContainsKey(query))
354
+ {
355
+ found = true;
356
+ // Create an anchor name for this dictionary
357
+ string anchorName = $"dict_{dict.Id}";
358
+
359
+ // Add dictionary to the result panel list
360
+ ListBoxItem resultItem = new ListBoxItem();
361
+ resultItem.Content = dict.Name;
362
+ resultItem.Tag = anchorName;
363
+ resultItem.MouseDoubleClick += ResultItem_MouseDoubleClick;
364
+ DictsList.Items.Add(resultItem);
365
+
366
+ string? def = dict.Mdx.GetDefinition(query);
367
+ if (!string.IsNullOrEmpty(def))
368
+ {
369
+ // Check for multiple redirects
370
+ if (def.StartsWith("@@@LINK=") && def.IndexOf("@@@LINK=", 1) != -1)
371
+ {
372
+ if (updateWordList)
373
+ {
374
+ // Parse candidates
375
+ var links = def.Split(new[] { "@@@LINK=" }, StringSplitOptions.RemoveEmptyEntries);
376
+ foreach (var link in links)
377
+ {
378
+ string target = link.Trim();
379
+ int nullIndex = target.IndexOf('\0');
380
+ if (nullIndex != -1) target = target.Substring(0, nullIndex);
381
+ target = target.Trim();
382
+ if (!string.IsNullOrEmpty(target) && !WordList.Items.Contains(target))
383
+ {
384
+ WordList.Items.Add(target);
385
+ }
386
+ }
387
+ }
388
+ sb.Append($"<a name=\"{anchorName}\"></a>");
389
+ sb.Append($"<h3>{query} <small>({dict.Name})</small></h3>");
390
+ sb.Append("<p><i>Multiple candidates found. Please select from the list.</i></p>");
391
+ sb.Append("<hr/>");
392
+ continue;
393
+ }
394
+
395
+ // Rewrite relative links to include dictionary ID for isolation
396
+ // Matches src="..." or href="..." where value doesn't start with http, https, data:, #, or entry:
397
+ string pattern = @"(?i)(src|href)=[""'](?!http|https|data:|#|entry:)([^""']+)[""']";
398
+ string replacement = $"$1=\"http://custom-rendering/{dict.Id}/$2\"";
399
+ def = System.Text.RegularExpressions.Regex.Replace(def, pattern, replacement);
400
+ }
401
+
402
+ sb.Append($"<a name=\"{anchorName}\"></a>");
403
+ sb.Append($"<h3>{query} <small>({dict.Name})</small></h3>");
404
+ sb.Append("<hr/>");
405
+ sb.Append(def);
406
+ sb.Append("<br/><br/>");
407
+ }
408
+ }
409
+
410
+ if (found && updateHistory)
411
+ {
412
+ AddToHistory(query);
413
+ }
414
+
415
+ if (!found)
416
+ {
417
+ sb.Append($"<h3>No results found for '{query}'</h3>");
418
+ }
419
+
420
+ sb.Append("</body></html>");
421
+
422
+ // Use RequestHandler to serve the content
423
+ if (Browser.RequestHandler is DictRequestHandler handler)
424
+ {
425
+ handler.SetSearchHtml(sb.ToString());
426
+ Browser.Load("http://custom-rendering/result.html");
427
+ }
428
+ else
429
+ {
430
+ // Fallback (should not happen if initialized correctly)
431
+ Browser.LoadHtml(sb.ToString(), "http://custom-rendering/");
432
+ }
433
+ }
434
+
435
+ private void DictSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
436
+ {
437
+ if (!_isReady) return;
438
+
439
+ if (DictSelector.SelectedItem is ComboBoxItem item)
440
+ {
441
+ _currentSelectionId = GetItemId(item);
442
+ SaveConfig();
443
+ }
444
+
445
+ // Check if SideSearchBox is initialized (FIX for NRE)
446
+ if (SideSearchBox == null) return;
447
+
448
+ // Re-search if we have a query
449
+ if (!string.IsNullOrEmpty(SideSearchBox.Text))
450
+ {
451
+ Search(SideSearchBox.Text, false);
452
+ }
453
+ }
454
+
455
+ private void WordList_SelectionChanged(object sender, SelectionChangedEventArgs e)
456
+ {
457
+ if (WordList.SelectedItem != null)
458
+ {
459
+ Search(WordList.SelectedItem.ToString(), false);
460
+ }
461
+ }
462
+
463
+ private void ResultItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
464
+ {
465
+ if (sender is ListBoxItem item && item.Tag is string anchorName)
466
+ {
467
+ // Execute JavaScript to scroll to the anchor
468
+ string script = $@"
469
+ var element = document.getElementsByName('{anchorName}')[0];
470
+ if (element) {{
471
+ element.scrollIntoView({{ behavior: 'smooth', block: 'start' }});
472
+ }}
473
+ ";
474
+ Browser.ExecuteScriptAsync(script);
475
+ }
476
+ }
477
+
478
+ private void AddToHistory(string query)
479
+ {
480
+ if (HistoryList.Items.Contains(query))
481
+ {
482
+ HistoryList.Items.Remove(query);
483
+ }
484
+ HistoryList.Items.Insert(0, query);
485
+
486
+ // Limit history size to prevent config bloat
487
+ while (HistoryList.Items.Count > 100)
488
+ {
489
+ HistoryList.Items.RemoveAt(HistoryList.Items.Count - 1);
490
+ }
491
+
492
+ SaveConfig();
493
+ }
494
+
495
+ private void HistoryList_SelectionChanged(object sender, SelectionChangedEventArgs e)
496
+ {
497
+ if (HistoryList.SelectedItem != null)
498
+ {
499
+ string? query = HistoryList.SelectedItem.ToString();
500
+ if (!string.IsNullOrEmpty(query))
501
+ {
502
+ SideSearchBox.Text = query;
503
+ // Do not update history (reorder) when navigating history
504
+ Search(query, true, false);
505
+ }
506
+ }
507
  }
508
  }
509
+ }
src/WpfEditor/EditDictionaries.xaml ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <Window x:Class="Echodict.EditDictionaries"
2
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4
+ Title="Edit Dictionaries" Height="400" Width="600" WindowStartupLocation="CenterOwner">
5
+ <Grid Margin="10">
6
+ <Grid.RowDefinitions>
7
+ <RowDefinition Height="*"/>
8
+ <RowDefinition Height="Auto"/>
9
+ </Grid.RowDefinitions>
10
+
11
+ <TabControl Grid.Row="0" Margin="0,0,0,10">
12
+ <TabItem Header="Sources">
13
+ <Grid Margin="5">
14
+ <Grid.RowDefinitions>
15
+ <RowDefinition Height="Auto"/>
16
+ <RowDefinition Height="*"/>
17
+ <RowDefinition Height="Auto"/>
18
+ </Grid.RowDefinitions>
19
+ <Label Content="Dictionary Sources (Folders):" Grid.Row="0" FontWeight="Bold"/>
20
+ <ListBox x:Name="PathsList" Grid.Row="1" Margin="0,5"/>
21
+ <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right">
22
+ <Button x:Name="BtnAdd" Content="Add Folder..." Width="100" Margin="0,0,10,0" Click="BtnAdd_Click"/>
23
+ <Button x:Name="BtnRemove" Content="Remove" Width="80" Click="BtnRemove_Click"/>
24
+ </StackPanel>
25
+ </Grid>
26
+ </TabItem>
27
+
28
+ <TabItem Header="Groups">
29
+ <Grid Margin="5">
30
+ <Grid.ColumnDefinitions>
31
+ <ColumnDefinition Width="*"/>
32
+ <ColumnDefinition Width="10"/>
33
+ <ColumnDefinition Width="*"/>
34
+ </Grid.ColumnDefinitions>
35
+
36
+ <!-- Left: Groups List -->
37
+ <Grid Grid.Column="0">
38
+ <Grid.RowDefinitions>
39
+ <RowDefinition Height="Auto"/>
40
+ <RowDefinition Height="*"/>
41
+ <RowDefinition Height="Auto"/>
42
+ </Grid.RowDefinitions>
43
+ <Label Content="Groups:" Grid.Row="0" FontWeight="Bold"/>
44
+ <ListBox x:Name="GroupsList" Grid.Row="1" Margin="0,5" SelectionChanged="GroupsList_SelectionChanged"/>
45
+ <StackPanel Grid.Row="2" Orientation="Horizontal">
46
+ <Button x:Name="BtnAddGroup" Content="Add" Width="60" Margin="0,0,5,0" Click="BtnAddGroup_Click"/>
47
+ <Button x:Name="BtnRemoveGroup" Content="Remove" Width="60" Click="BtnRemoveGroup_Click"/>
48
+ </StackPanel>
49
+ </Grid>
50
+
51
+ <!-- Right: Dictionaries in Group -->
52
+ <Grid Grid.Column="2">
53
+ <Grid.RowDefinitions>
54
+ <RowDefinition Height="Auto"/>
55
+ <RowDefinition Height="*"/>
56
+ </Grid.RowDefinitions>
57
+ <Label Content="Dictionaries in Group:" Grid.Row="0" FontWeight="Bold"/>
58
+ <ListBox x:Name="GroupDictsList" Grid.Row="1" Margin="0,5">
59
+ <ListBox.ItemTemplate>
60
+ <DataTemplate>
61
+ <CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}" Click="DictInGroup_Click" Tag="{Binding Path}"/>
62
+ </DataTemplate>
63
+ </ListBox.ItemTemplate>
64
+ </ListBox>
65
+ </Grid>
66
+ </Grid>
67
+ </TabItem>
68
+ </TabControl>
69
+
70
+ <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
71
+ <Button x:Name="BtnRescan" Content="Rescan &amp; Apply" Width="120" Margin="0,0,10,0" Click="BtnRescan_Click"/>
72
+ <Button x:Name="BtnCancel" Content="Cancel" Width="80" Click="BtnCancel_Click"/>
73
+ </StackPanel>
74
+ </Grid>
75
+ </Window>
src/WpfEditor/EditDictionaries.xaml.cs ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System;
2
+ using System.Collections.Generic;
3
+ using System.Linq;
4
+ using System.Windows;
5
+ using System.Windows.Controls;
6
+ using Microsoft.Win32;
7
+
8
+ namespace Echodict
9
+ {
10
+ public partial class EditDictionaries : Window
11
+ {
12
+ public List<string> SourcePaths { get; private set; }
13
+ public List<DictGroup> Groups { get; private set; }
14
+ public bool NeedsRescan { get; private set; } = false;
15
+
16
+ private List<Dictionary> _availableDicts;
17
+
18
+ public EditDictionaries(List<string> currentPaths, List<DictGroup> currentGroups, List<Dictionary> availableDicts)
19
+ {
20
+ InitializeComponent();
21
+ SourcePaths = new List<string>(currentPaths);
22
+
23
+ // Clone groups
24
+ Groups = new List<DictGroup>();
25
+ if (currentGroups != null)
26
+ {
27
+ foreach (var g in currentGroups)
28
+ {
29
+ Groups.Add(new DictGroup
30
+ {
31
+ Name = g.Name,
32
+ DictionaryPaths = new List<string>(g.DictionaryPaths)
33
+ });
34
+ }
35
+ }
36
+
37
+ _availableDicts = availableDicts ?? new List<Dictionary>();
38
+
39
+ RefreshPathsList();
40
+ RefreshGroupsList();
41
+ }
42
+
43
+ private void RefreshPathsList()
44
+ {
45
+ PathsList.ItemsSource = null;
46
+ PathsList.ItemsSource = SourcePaths;
47
+ }
48
+
49
+ private void RefreshGroupsList()
50
+ {
51
+ var selected = GroupsList.SelectedItem;
52
+ GroupsList.ItemsSource = null;
53
+ GroupsList.ItemsSource = Groups;
54
+ GroupsList.DisplayMemberPath = "Name";
55
+ if (selected != null && Groups.Contains(selected))
56
+ {
57
+ GroupsList.SelectedItem = selected;
58
+ }
59
+ }
60
+
61
+ private void GroupsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
62
+ {
63
+ if (GroupsList.SelectedItem is DictGroup group)
64
+ {
65
+ // Populate GroupDictsList
66
+ var viewModels = _availableDicts.Select(d => new DictSelectionViewModel
67
+ {
68
+ Name = d.Name,
69
+ Path = d.Mdx.Filename, // Assuming Mdx.Filename is the unique path
70
+ IsSelected = group.DictionaryPaths.Contains(d.Mdx.Filename)
71
+ }).ToList();
72
+
73
+ GroupDictsList.ItemsSource = viewModels;
74
+ }
75
+ else
76
+ {
77
+ GroupDictsList.ItemsSource = null;
78
+ }
79
+ }
80
+
81
+ private void DictInGroup_Click(object sender, RoutedEventArgs e)
82
+ {
83
+ if (GroupsList.SelectedItem is DictGroup group && sender is CheckBox cb && cb.Tag is string path)
84
+ {
85
+ if (cb.IsChecked == true)
86
+ {
87
+ if (!group.DictionaryPaths.Contains(path))
88
+ group.DictionaryPaths.Add(path);
89
+ }
90
+ else
91
+ {
92
+ group.DictionaryPaths.Remove(path);
93
+ }
94
+ }
95
+ }
96
+
97
+ private void BtnAdd_Click(object sender, RoutedEventArgs e)
98
+ {
99
+ var dialog = new OpenFolderDialog();
100
+ dialog.Title = "Select Dictionary Folder";
101
+ dialog.Multiselect = false;
102
+
103
+ if (dialog.ShowDialog() == true)
104
+ {
105
+ string path = dialog.FolderName;
106
+ if (!SourcePaths.Contains(path))
107
+ {
108
+ SourcePaths.Add(path);
109
+ RefreshPathsList();
110
+ }
111
+ }
112
+ }
113
+
114
+ private void BtnRemove_Click(object sender, RoutedEventArgs e)
115
+ {
116
+ if (PathsList.SelectedItem is string path)
117
+ {
118
+ SourcePaths.Remove(path);
119
+ RefreshPathsList();
120
+ }
121
+ }
122
+
123
+ private void BtnAddGroup_Click(object sender, RoutedEventArgs e)
124
+ {
125
+ string name = SimpleInput.ShowDialog("Enter Group Name:", "New Group");
126
+ if (!string.IsNullOrWhiteSpace(name))
127
+ {
128
+ Groups.Add(new DictGroup { Name = name });
129
+ RefreshGroupsList();
130
+ GroupsList.SelectedIndex = Groups.Count - 1;
131
+ }
132
+ }
133
+
134
+ private void BtnRemoveGroup_Click(object sender, RoutedEventArgs e)
135
+ {
136
+ if (GroupsList.SelectedItem is DictGroup group)
137
+ {
138
+ Groups.Remove(group);
139
+ RefreshGroupsList();
140
+ }
141
+ }
142
+
143
+ private void BtnRescan_Click(object sender, RoutedEventArgs e)
144
+ {
145
+ NeedsRescan = true;
146
+ DialogResult = true;
147
+ Close();
148
+ }
149
+
150
+ private void BtnCancel_Click(object sender, RoutedEventArgs e)
151
+ {
152
+ DialogResult = false;
153
+ Close();
154
+ }
155
+ }
156
+
157
+ public class DictSelectionViewModel
158
+ {
159
+ public string Name { get; set; } = string.Empty;
160
+ public string Path { get; set; } = string.Empty;
161
+ public bool IsSelected { get; set; }
162
+ }
163
+
164
+ public static class SimpleInput
165
+ {
166
+ public static string ShowDialog(string text, string caption)
167
+ {
168
+ Window prompt = new Window()
169
+ {
170
+ Width = 300,
171
+ Height = 150,
172
+ Title = caption,
173
+ WindowStartupLocation = WindowStartupLocation.CenterScreen,
174
+ ResizeMode = ResizeMode.NoResize
175
+ };
176
+ StackPanel sp = new StackPanel() { Margin = new Thickness(10) };
177
+ Label lbl = new Label() { Content = text };
178
+ TextBox txt = new TextBox();
179
+ Button btn = new Button() { Content = "OK", Width = 80, Margin = new Thickness(0, 10, 0, 0), HorizontalAlignment = HorizontalAlignment.Center };
180
+ btn.Click += (sender, e) => { prompt.DialogResult = true; prompt.Close(); };
181
+
182
+ sp.Children.Add(lbl);
183
+ sp.Children.Add(txt);
184
+ sp.Children.Add(btn);
185
+ prompt.Content = sp;
186
+
187
+ txt.Focus();
188
+
189
+ if (prompt.ShowDialog() == true)
190
+ return txt.Text;
191
+ else
192
+ return "";
193
+ }
194
+ }
195
+ }
src/WpfEditor/OCRResultWindow.xaml.cs CHANGED
@@ -83,8 +83,8 @@ namespace WpfEditor
83
 
84
  private void EchodictMenuItem_Click(object sender, RoutedEventArgs e)
85
  {
86
- var win = new EchoDictWindow(selectText);
87
- win.Show();
88
  }
89
 
90
  }
 
83
 
84
  private void EchodictMenuItem_Click(object sender, RoutedEventArgs e)
85
  {
86
+ //var win = new EchoDictWindow(selectText);
87
+ //win.Show();
88
  }
89
 
90
  }
src/WpfEditor/TextEditorControl.cs CHANGED
@@ -1,3 +1,4 @@
 
1
  using Microsoft.Win32;
2
  using Newtonsoft.Json;
3
  using Newtonsoft.Json.Linq;
@@ -313,7 +314,15 @@ namespace WpfEditor
313
  Command = ApplicationCommands.SelectAll
314
  };
315
  ContextMenu.Items.Add(selectAllMenuItem);
316
-
 
 
 
 
 
 
 
 
317
  // 翻译菜单项
318
  MenuItem translateMenuItem = new MenuItem
319
  {
@@ -374,6 +383,20 @@ namespace WpfEditor
374
  }
375
  }
376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
  #region 属性
378
 
379
  public string Text
 
1
+ using Echodict;
2
  using Microsoft.Win32;
3
  using Newtonsoft.Json;
4
  using Newtonsoft.Json.Linq;
 
314
  Command = ApplicationCommands.SelectAll
315
  };
316
  ContextMenu.Items.Add(selectAllMenuItem);
317
+
318
+ // 查询菜单项
319
+ MenuItem QeryMenuItem = new MenuItem
320
+ {
321
+ Header = "查询"
322
+ };
323
+ QeryMenuItem.Click += OnQeryMenuItemClick;
324
+ ContextMenu.Items.Add(QeryMenuItem);
325
+
326
  // 翻译菜单项
327
  MenuItem translateMenuItem = new MenuItem
328
  {
 
383
  }
384
  }
385
 
386
+ // "翻译"菜单项点击事件处理
387
+ private async void OnQeryMenuItemClick(object sender, RoutedEventArgs e)
388
+ {
389
+ if (HasSelection())
390
+ {
391
+ string text = GetSelectedText();
392
+
393
+ var win = new Echodict.EchodictWindow();
394
+ win.Owner = Window.GetWindow(this);
395
+ win.WindowStartupLocation = WindowStartupLocation.CenterOwner;
396
+ win.ShowDialog();
397
+ }
398
+ }
399
+
400
  #region 属性
401
 
402
  public string Text
src/WpfEditor/TreeMenuPage.xaml CHANGED
@@ -4,7 +4,7 @@
4
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
5
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
6
  mc:Ignorable="d"
7
- Title="EchoDict" Height="600" Width="800">
8
  <Grid>
9
  <!-- 主容器 -->
10
  <Grid.ColumnDefinitions>
 
4
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
5
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
6
  mc:Ignorable="d"
7
+ Title="EchoEditor" Height="600" Width="800">
8
  <Grid>
9
  <!-- 主容器 -->
10
  <Grid.ColumnDefinitions>
src/WpfEditor/WpfEditor.csproj CHANGED
@@ -24,6 +24,7 @@
24
  </ItemGroup>
25
 
26
  <ItemGroup>
 
27
  <ProjectReference Include="..\ScreenGrab\ScreenGrab.csproj" />
28
  <ProjectReference Include="..\WeChatOcrCpp\WeChatOcrCpp.vcxproj" />
29
  </ItemGroup>
 
24
  </ItemGroup>
25
 
26
  <ItemGroup>
27
+ <ProjectReference Include="..\EchoDictLib\EchoDictLib.csproj" />
28
  <ProjectReference Include="..\ScreenGrab\ScreenGrab.csproj" />
29
  <ProjectReference Include="..\WeChatOcrCpp\WeChatOcrCpp.vcxproj" />
30
  </ItemGroup>