diff --git a/.vs/AIProofread/v17/.suo b/.vs/AIProofread/v17/.suo index 6f699cd..b1815a6 100644 Binary files a/.vs/AIProofread/v17/.suo and b/.vs/AIProofread/v17/.suo differ diff --git a/AIProofread.sln b/AIProofread.sln index eae8630..b9084f0 100644 --- a/AIProofread.sln +++ b/AIProofread.sln @@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "util-lib", "util-lib\util-l EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "updater", "updater\updater.csproj", "{73AC658D-CD49-4731-8491-A7BDBC811559}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ai-proofread-client", "ai-proofread-client\ai-proofread-client.csproj", "{48C0B207-150A-40B7-9A25-ECF9218FF86F}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -42,6 +44,12 @@ Global {73AC658D-CD49-4731-8491-A7BDBC811559}.Release|Any CPU.Build.0 = Release|Any CPU {73AC658D-CD49-4731-8491-A7BDBC811559}.Test|Any CPU.ActiveCfg = Debug|Any CPU {73AC658D-CD49-4731-8491-A7BDBC811559}.Test|Any CPU.Build.0 = Debug|Any CPU + {48C0B207-150A-40B7-9A25-ECF9218FF86F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {48C0B207-150A-40B7-9A25-ECF9218FF86F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {48C0B207-150A-40B7-9A25-ECF9218FF86F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {48C0B207-150A-40B7-9A25-ECF9218FF86F}.Release|Any CPU.Build.0 = Release|Any CPU + {48C0B207-150A-40B7-9A25-ECF9218FF86F}.Test|Any CPU.ActiveCfg = Debug|Any CPU + {48C0B207-150A-40B7-9A25-ECF9218FF86F}.Test|Any CPU.Build.0 = Debug|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/AIProofread/AIProofread.csproj b/AIProofread/AIProofread.csproj index 5fc78d2..8a75ce1 100644 --- a/AIProofread/AIProofread.csproj +++ b/AIProofread/AIProofread.csproj @@ -290,12 +290,24 @@ FormContact.cs + + Form + + + FormDialog.cs + Form FormLoading.cs + + Form + + + FormLogger.cs + Form @@ -308,12 +320,24 @@ FormMain.cs + + Form + + + FormMessage.cs + Form FormSetting.cs + + Form + + + FormWebView.cs + UserControl @@ -331,7 +355,10 @@ + + + Code @@ -342,18 +369,30 @@ FormContact.cs + + FormDialog.cs + FormLoading.cs + + FormLogger.cs + FormLogin.cs FormMain.cs + + FormMessage.cs + FormSetting.cs + + FormWebView.cs + ProofreadMainControl.cs @@ -408,7 +447,9 @@ util-lib - + + + @@ -421,6 +462,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) diff --git a/AIProofread/Bridge.cs b/AIProofread/Bridge.cs index 6a4688c..bfaa45b 100644 --- a/AIProofread/Bridge.cs +++ b/AIProofread/Bridge.cs @@ -1,11 +1,13 @@ using AIProofread.Controls; using AIProofread.core; +using AIProofread.Model; using AIProofread.Util; using Microsoft.Office.Interop.Word; using Microsoft.Office.Tools.Word; using Microsoft.Web.WebView2.Core; using Microsoft.Web.WebView2.WinForms; using Newtonsoft.Json; +using NPOI.XWPF.UserModel; using System; using System.Collections.Generic; using System.Diagnostics; @@ -73,7 +75,10 @@ namespace AIProofread return CurrentUpgrade != null && CurrentUpgrade.NeedUpgrade(Config.APP_VERSION) && CurrentUpgrade.UpgradeType == 1; } - public void InitPluginUpgrade() + /// + /// 检查插件更新信息 + /// + public void CheckPluginUpgrade() { try { @@ -99,14 +104,18 @@ namespace AIProofread public string GetAppVersion() { - return Config.APP_VERSION; - } + Dictionary data = new Dictionary(); + data["version"] = Config.APP_VERSION; + data["platform"] = Config.IS_WPS ? "wps" : "word"; + data["environment"] = Config.APP_ENV.ToString(); + return JsonConvert.SerializeObject(data); + } public void showDialog(string message) { - System.Windows.Forms.MessageBox.Show(message); + MessageBox.Show(message); } public int getMinWIdth() @@ -143,35 +152,26 @@ namespace AIProofread public void SetDocumentId(int id, Document document) { - Globals.ThisAddIn.documentIdDics[document] = id; + Globals.ThisAddIn.SetDocumentId(document, id); } - public Document GetDocumentById(int id) + public DocumentInfo GetDocumentById(int id) { - //return GeIdBytDocument(Globals.ThisAddIn.Application.ActiveDocument); - var documentDic = Globals.ThisAddIn.documentIdDics; - foreach (var doc in documentDic.Keys) - { - if (documentDic[doc] == id) return doc; - } - return null; + return Globals.ThisAddIn.GetDocumentById(id); } public int GetCurrentDocumentId() { - return GeIdBytDocument(Globals.ThisAddIn.Application.ActiveDocument); + return Globals.ThisAddIn.ActiveDocument.Id; } public int GeIdBytDocument(Document document) { - if (Globals.ThisAddIn.documentIdDics.ContainsKey(document)) + var doc = Globals.ThisAddIn.documentList.Get(document); + if (doc != null) { - return Globals.ThisAddIn.documentIdDics[document]; + return doc.Id; } - //int id = Globals.ThisAddIn.documentIdDics.Count + 1; - //// 设置文档编号 - //SetCurrentDocumentId((int)id); - //return id ; - return 0; + return doc != null ? doc.Id : 0; } // 打开网页 @@ -214,26 +214,23 @@ namespace AIProofread public void ShowCurrentPane() { Globals.ThisAddIn.ShowPanel(); - //Globals.ThisAddIn.currentDocumentTaskPane.Visible = true; } public void HideCurrentPane() { Globals.ThisAddIn.HidePanel(); - //Globals.ThisAddIn.currentDocumentTaskPane.Visible = false; } + + public void ShowLoginForm(string action) + { + Globals.ThisAddIn.ShowLoginForm(action); + } public void Logout(string action) { - if (action == "async-info") - { - // web同步注销到ribbon - Globals.ThisAddIn.SyncLogout(); - } - else - { - // ribbon 发送注销动作到 web - Globals.ThisAddIn.SendMessageToWeb("logout", null); - } + // web同步注销到ribbon + Globals.ThisAddIn.SyncLogout(); + // ribbon 发送注销动作到 web + Globals.ThisAddIn.SendMessageToWeb("logout", null); } /// @@ -246,7 +243,6 @@ namespace AIProofread Userinfo info = JsonConvert.DeserializeObject(userinfo); // 登录成功 展示 Globals.ThisAddIn.ribbon.ProcessLoginInfo(info); - //Globals.ThisAddIn.SendMessageToWeb("async-login-success", null); } // 获取文档所有文本数据 @@ -254,13 +250,20 @@ namespace AIProofread { return Tools.GetAllText(Globals.ThisAddIn.Application.ActiveDocument); } + + /// + /// 获取文档数据 + /// + /// public string getDocumentData() { Dictionary data = new Dictionary(); var doc = Globals.ThisAddIn.Application.ActiveDocument; - - if (!doc.Saved) + string ext = doc.FullName.ToLower(); + // 如果是 + var shouldCheckSaved = ext.EndsWith(".wps") || doc.Paragraphs.Count < 200 || doc.Tables.Count < 20; + if (!shouldCheckSaved && !doc.Saved) { data.Add("code", 1); data.Add("message", "请保存文档后再进行校对"); @@ -277,11 +280,13 @@ namespace AIProofread } else { + data.Add("code", 0); data.Add("message", "success"); data.Add("name", doc.Name); + //data.Add("documentId", Globals.ThisAddIn.ActiveDocument.Id); data.Add("fullName", doc.FullName); - //data.Add("documentId", GeIdBytDocument(doc)); + data.Add("documentId", GeIdBytDocument(doc)); data.Add("wordsCount", doc.Words.Count); data.Add("charactersCount", doc.Characters.Count); data.Add("content", Tools.GetAllText(doc)); @@ -289,55 +294,34 @@ namespace AIProofread return Tools.GetJSONString(data); } - + /// + /// 根据位置获取文档区域文本 + /// + /// + /// + /// public string getParagraphTextByRange(int start, int end) { var list = Tools.GetTextListByParagraphRange(start, end); return Tools.GetJSONString(list); } - + /// + /// 获取文档所有段落文本 + /// + /// public string getAllParagraphs() { - var doc = Globals.ThisAddIn.Application.ActiveDocument; - - var rangeText = doc.Content.Text; - var trimText = HostHelper.ReplaceSpecialChars(rangeText, isReplaceMultSpaceLine: true); - - string[] separator = new string[5] { "\r\a", "\a", "\r", "\v", "\f" }; - string[] array4 = rangeText.Split(separator, StringSplitOptions.None); - string[] array5 = trimText.Split('\n'); - List list = new List(); - var paragraphs = doc.Paragraphs; - int total = paragraphs.Count; - for (int i = 1; i <= total; i++) + var doc = Globals.ThisAddIn.ActiveDocument; + if (doc == null) { - list.Add(GetParagraphText(paragraphs[i])); + return ""; } - var array6 = list.ToArray(); - Dictionary data = new Dictionary - { - {"origin_cut",array4 }, - {"trim_cut",array5 }, - {"paragraph_cut",array6 }, - }; - return Tools.GetJSONString(data); - } - private string GetParagraphText(Paragraph paragraph) - { - // 需要 - return GetRangeText(paragraph.Range); - } - private string GetRangeText(Range range) - { - // 需要 - return range.Text; + return Tools.GetJSONString(doc.GetAllParagraphs()); } public void getParagraphTextByRangeSync(int start, int end) { - //var list = Tools.GetTextListByParagraphRange(start, end); - //return Tools.GetJSONString(list); Task.Run(() => { var list = Tools.GetTextListByParagraphRange(start, end); @@ -345,23 +329,13 @@ namespace AIProofread }); } - public int getTotalParagraphNumber() - { - return Globals.ThisAddIn.Application.ActiveDocument.Paragraphs.Count; - } + public int getTotalParagraphNumber() => Globals.ThisAddIn.ActiveDocument?.GetTotalParagraphNumber() ?? -1; /// /// 读取文档原始文件并转换成base64 /// /// - public string getDocumentFileData() - { - var doc = Globals.ThisAddIn.Application.ActiveDocument.FullName; - FileStream fs = new FileStream(doc, FileMode.Open, FileAccess.Read, FileShare.Read); - byte[] bytes = new byte[fs.Length]; - fs.Read(bytes, 0, bytes.Length); - return Convert.ToBase64String(bytes); - } + public string getDocumentFileData() => Globals.ThisAddIn.ActiveDocument?.GetOriginFileData() ?? ""; public void ShowUpgrade(string data) { @@ -444,54 +418,10 @@ namespace AIProofread } - public void clearAllProofreadMarkById(int documentId) - { - clearAllProofreadMark(GetDocumentById(documentId)); - } - // 清除所有标记 - public void clearAllProofreadMark(Document document) - { - // 标记当前文档所有书签数据 - Globals.ThisAddIn.ActiveCurrentDocumentMarks(document); - try - { - selectProofreadId = -1; - foreach (var item in marks.Values) - { - if (item.mark != null) - { - if (item.content.Tag == "i" && item.content.IsAccept == AcceptStatus.Default) - { - item.mark.Text = ""; - } - item.ResetMarkStyle(); - } - } - DocumentUtil.ClearProofreadMarks(); - } - catch (Exception ex) - { - Logger.Log("ClearAllProofreadMark", ex); - } - try - { - // 清空marks - marks.Clear(); - } - catch (Exception) { } - } + public void clearAllProofreadMarkById(int documentId) => Globals.ThisAddIn.GetDocumentById(documentId)?.ClearAllProofreadMark(); + public void ClearCurrentDocumentMarks() => Globals.ThisAddIn.ActiveDocument?.ClearAllProofreadMark(); + public void removeBookmark(string markId) => DocumentUtil.RemoveBookmark(markId); - public void removeBookmark(string markId) - { - DocumentUtil.RemoveBookmark(markId); - } - //public void addBookmark(string data) - //{ - // var item = JsonConvert.DeserializeObject(data); - // //var mark = DocumentUtil.AddBookmark(item.color, item.start, item.end); - // // 初始化校对对象 - // marks.Add(item.id, new ProofreadItem(item)); - //} public string getAllBookmark() { @@ -536,7 +466,6 @@ namespace AIProofread { // 文档对象 var document = Globals.ThisAddIn.Application.ActiveDocument; - var vstoDocument = Globals.Factory.GetVstoObject(document); // 获取选区 var selection = Globals.ThisAddIn.Application.Selection; // 段落数 @@ -592,11 +521,6 @@ namespace AIProofread } return text; } - - public void ShowLoginForm(string action) - { - Globals.ThisAddIn.ShowLoginForm(action); - } public void ShowSettingForm() { FormSetting frm = new FormSetting(); @@ -611,158 +535,29 @@ namespace AIProofread public void SelectMarkById(int proofreadId, int documentId) { - var doc = documentId < 1 ? Globals.ThisAddIn.Application.ActiveDocument : GetDocumentById(documentId); - // - // 设置当前文档数据 - Globals.ThisAddIn.ActiveCurrentDocumentMarks(doc); - if (proofreadId == selectProofreadId) return; - // 取消上一个标签移除 - if (selectProofreadId > 0 && marks.ContainsKey(selectProofreadId)) - { - var m = marks[selectProofreadId]; - if (doc.Bookmarks.Exists(m.Name)) - { - marks[selectProofreadId].UnSelect(); - } - else - { - marks.Remove(selectProofreadId); - } - } - selectProofreadId = proofreadId; - - if (proofreadId > 0 && marks.ContainsKey(proofreadId)) - { - var mark = marks[proofreadId].mark; - // 已经不存在该标签了 - if (!doc.Bookmarks.Exists(mark.Name)) - { - marks.Remove(selectProofreadId); - return; - } - //object lineNum = (int)mark.Range.Information[WdInformation.wdFirstCharacterLineNumber] - 1; - //object goToLine = WdGoToItem.wdGoToLine; - //object goNext = WdGoToDirection.wdGoToNext; - //Globals.ThisAddIn.Application.ActiveWindow.Selection.GoTo(ref goToLine, ref goNext, ref lineNum); - // - object bookmark = WdGoToItem.wdGoToBookmark; - object bookmarkName = mark.Name; - //doc.GoTo(mark); - //mark.Range.GoTo(); - Globals.ThisAddIn.Application.ActiveWindow.Selection.GoTo(ref bookmark, ref missing, ref missing, ref bookmarkName); - // - //mark.DisableCharacterSpaceGrid = false; - // 先滚动到可视区域 - //doc.ActiveWindow.ScrollIntoView(mark.Range); - marks[proofreadId].Select(); - //Globals.ThisAddIn.SendMessageToWeb("select", proofreadId); - } - Globals.ThisAddIn.SendMessageToWeb("select-proofread", proofreadId); + Globals.ThisAddIn.ActiveDocument?.SelectMarkById(proofreadId); } public void processMark(int proofreadId, int status) { - if (proofreadId > 0 && marks.ContainsKey(proofreadId)) - { - marks[proofreadId].Process(status); - } + Globals.ThisAddIn.ActiveDocument?.ProcessMark(proofreadId, status); } - - private Document _currentDocument; - public Document CurrentDocument - { - get => _currentDocument ?? Globals.ThisAddIn.Application.ActiveDocument; - set - { - _currentDocument = value; - } - } - public string InitContent(string content, int documentId) + { + return InitContent(content, documentId, true); + } + public string InitContent(string content, int documentId, bool clearOriginMark) { try { // 根据文档编号 获取当前文档避免数据混乱 - CurrentDocument = GetDocumentById(documentId); - if (CurrentDocument == null) - { - throw new Exception("没有找到校对文档对象"); - } - List list = JsonConvert.DeserializeObject>(content); + var document = Globals.ThisAddIn.GetDocumentById(documentId) ?? throw new Exception("没有找到校对文档对象"); // 先清除所有数据 - clearAllProofreadMark(CurrentDocument); - - //var app = Globals.ThisAddIn.Application; - //var cur = app.Selection; - // - var prevOffset = 0; - List disabledList = new List(); - foreach (var correct in list) - { - if (correct.CorrectItems != null && correct.CorrectItems.Count > 0) - { - prevOffset = 0; - int index = 0; - foreach (var item in correct.CorrectItems) - { - int _prev = prevOffset; - // 查找对应区域并再该区域添加书签 - var mark = DocumentUtil.FindRangeAndCreateBookmark(item, correct, CurrentDocument, ref prevOffset); - // 防止调用方法中没有更新 - if (_prev >= prevOffset) - { - prevOffset = correct.SentenceOffset + item.Start; - } - - if (item.Tag != "i") index++; - if (mark != null) - { - marks.Add(item.Id, new ProofreadItem(item, mark, documentId)); - } - else - { - disabledList.Add(item.Id); - var msg = new Dictionary{ - {"message","没有找到标记对象" }, - { "origin",item }, - { "origin_correct",correct }, - { "new_text",correct.NewText }, - { "paragraph_num",correct.ParagraphNumber }, - }; - Logger.Log(JsonConvert.SerializeObject(msg)); - } - } - } - } - foreach (var item in marks) - { - if (item.Value.mark != null) - { - if (item.Value.content.Tag == "i") - { - item.Value.mark.Text = ToolUtil.GetBlankText(item.Value.content.Text.Length); - } - if (item.Value.content.Color != null) - { - try - { - var color = (WdColor)ColorTranslator.ToOle(Colors.FromHex(item.Value.content.Color)); - // 给选区添加背景颜色 - item.Value.mark.Shading.BackgroundPatternColor = color; - } - catch (Exception) - { - //item.Value.mark.Shading.BackgroundPatternColor = WdColor.wdColorLightOrange; - } - } - } - } - - - // 隐藏面板对应校对项 - MainPanelWebMessage.DisabledProofreadItem(disabledList); + if (clearOriginMark) document.ClearAllProofreadMark(); + List list = JsonConvert.DeserializeObject>(content); + document.InitProofread(list); } catch (Exception ex) { @@ -772,219 +567,115 @@ namespace AIProofread return "true"; } - void SendMessageToPanel() - { - - } - - - public string GetParagraph(int index) - { - try - { - var paragraphs = CurrentDocument.Paragraphs; - var total = paragraphs.Count; - // 判断索引是否超出范围 - if (index > total) - { - return null; - } - var paragraph = CurrentDocument.Paragraphs[index]; - return paragraph.Range.Text; - } - catch (Exception ex) - { - return "error:" + ex.Message; - } - } - /// /// 新增校对项 查找时的偏移量 /// - private static readonly int INSERT_FIND_OFFSET = 5; + //private static readonly int INSERT_FIND_OFFSET = 5; - /// - /// 根据校对项查找文档对应的位置 并创建书签 - /// - /// 校对项 - /// 校对 - /// - /// - public Microsoft.Office.Tools.Word.Bookmark FindRangeAndCreateBookmark1(CorrectItem correct, CorrectContext sentense, ref int prevOffset) + + public string MarkSentence(string content, int documentId) + { + // 初始化话 + return InitContent(content, documentId, false); + } + + public string ShowDialogMessage(string message) + { + var result = FormMessage.ShowMessage(message); + if (result == DialogResult.Retry) + { + return "retry"; + } + return "ok"; + } + + // 保存文件 + public string WriteText(string content, string path) { - Microsoft.Office.Tools.Word.Bookmark bookmark = null; try { - var document = CurrentDocument; - ControlCollection controls = Globals.Factory.GetVstoObject(document).Controls; - var markName = Config.BuildBookmarkName(correct.Id); - - // 判断是否已经存在 - if (controls.Contains(markName)) - { - try - { - controls.Remove(markName); - } - catch (Exception) { } - } - Range findRange = null; - // 判断段落是否存在 - if (sentense.ParagraphNumber > document.Paragraphs.Count) return null; - - var paragraph = document.Paragraphs[sentense.ParagraphNumber]; - Range paragraphRange = paragraph.Range; - var paragraphStart = paragraphRange.Start; - - - var Start = paragraphStart + sentense.SentenceOffset; - var End = Start + sentense.InsertLength - 1; - if (End > paragraphRange.End) - { - End = paragraphRange.End; - } - - // 当前句子的选区 - var fullRange = document.Range(Start, End); - // 如果选择有文本就用文本 - string fullText = fullRange.Text ?? paragraphRange.Text; - // 当前段落文本 - string paragraphText = paragraphRange.Text; - End = Start + correct.End; - Start = Start + correct.Start; - // 避免越界 - prevOffset = Math.Min(prevOffset, paragraphText.Length - 1); - - int offset = sentense.SentenceOffset; - int length = sentense.InsertLength; - string originText = sentense.Insert; - - // 如果是新增 则查找定位 - if (correct.Tag == "i") - { - // s1. 通过接口的位置 和 文档内容进行比对 - try - { - // 判断接口的定位字符串和文档截取的字符串是否一致 - if (paragraphText.Substring(offset, length) == originText) - { - // 直接使用接口定位 - findRange = document.Range(Start, End); - } - } - catch (Exception exif) - { - Logger.Log(exif); - } - // s2. 位置不匹配 则采用搜索定位 - if (findRange == null) - { - // 找前缀 - var prefix = correct.Start > 2 ? ( - correct.Start > INSERT_FIND_OFFSET - ? originText.Substring(correct.Start - INSERT_FIND_OFFSET, INSERT_FIND_OFFSET) - : originText.Substring(0, correct.Start) - ) : null; - // 找后缀 - var suffix = prefix == null ? ( - correct.End + INSERT_FIND_OFFSET < originText.Length - ? originText.Substring(correct.Start, INSERT_FIND_OFFSET) - : originText.Substring(correct.Start, originText.Length - correct.Start) - ) : null; - // 偏移量 - var start = prefix != null || suffix != null - ? paragraphText.IndexOf(prefix ?? suffix, prevOffset) - : -1; - if (start != -1) - { - var findOffset = paragraphStart + start + (prefix != null ? prefix.Length : 0); - findRange = document.Range(findOffset, findOffset); - } - } - } - else - { - findRange = document.Range(Start, End); - } - // 不是新增模式 且定位区域文本和原始文本不匹配 - if (correct.Tag != "i" && findRange.Text != correct.Origin) - { - // 查找 - findRange = DocumentUtil.FindRange(correct, sentense, ref prevOffset, CurrentDocument, paragraphRange); - } - - // 能够找到对应的区域 则再对应区域添加书签 - if (findRange != null) - { - // 更新查找的结束位置 - prevOffset = findRange.End - paragraphStart; - bookmark = controls.AddBookmark(findRange, markName); - bookmark.Tag = "ai_proofread"; - } - - #region start - - //// 判断并获取当前段落 - - - //// 定位要操作的文字 - //var r = document.Range(Start, End); - - //// 判断选区是否正确 - //if (item.tag == "i" || r.Text == item.origin) - //{ - // bookmark = controls.AddBookmark(r, markName); - // bookmark.Tag = "ai_proofread"; - //} - //else - //{ - // object str = item.origin; - // FindRange(ref fullRange, ref str); - - // if(fullRange != null){ - // bookmark = controls.AddBookmark(fullRange, markName); - // bookmark.Tag = "ai_proofread"; - // } - // //int startPos = 0, index, findCount = 0; - // //while ((index = fullText.IndexOf(item.origin, startPos)) != -1) - // //{ - // // if (findCount == findIndex) - // // { - // // r = document.Range(offset + index, offset + index + item.origin.Length); - // // if(r.Text == item.origin) { } - // // bookmark = controls.AddBookmark(r, markName); - // // bookmark.Tagetg = "ai_proofread"; - // // break; - // // } - // // startPos = index; - // // findCount++; - // //} - //} - #endregion - + File.WriteAllText(path, content); + return BridgeResult.Success("ok"); } catch (Exception ex) { - Logger.Log("create mark error:" + ex.Message + "\n" + ex.StackTrace + "\n\n"); + return BridgeResult.Error(-1, ex.Message); } - return bookmark; } - - /// - /// - /// - /// - /// - private void FindRange(ref Range range, ref object whatToFind) + public string ReadText(string path) { - object matchCase = false; // 是否区分大小写 - object matchWholeWord = false; // 是否匹配整个单词 - object matchWildcards = false; // 是否使用通配符 - object forward = true; // 搜索方向,true表示向前搜索,false表示向后搜索 - object wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue; // 搜索范围,这里表示继续搜索 + try + { + if (!File.Exists(path)) return BridgeResult.Error(-1, "文件不存在"); + return BridgeResult.Success(File.ReadAllText(path)); + } + catch (Exception ex) + { + return BridgeResult.Error(-1, ex.Message); + } + } - range.Find.Execute(ref whatToFind, ref matchCase, ref matchWholeWord, ref matchWildcards, ref forward, ref wrap); + public string SaveCache(string cache, bool silent) + { + if (!silent) + { + if (!Globals.ThisAddIn.Application.ActiveDocument.Saved) + { + MessageBox.Show("请先保存文档"); + return BridgeResult.Error(1, "请先保存文档"); + } + } + try + { + File.WriteAllText(Globals.ThisAddIn.ActiveDocument.ProofreadCachePath, cache); + return BridgeResult.Success("ok"); + } + catch (Exception ex) + { + return BridgeResult.Error(-1, ex.Message); + } + } + + public bool CacheExists() + { + return File.Exists(Globals.ThisAddIn.ActiveDocument.ProofreadCachePath); + } + + public string LoadCache() + { + if (!File.Exists(Globals.ThisAddIn.ActiveDocument.ProofreadCachePath)) + { + return BridgeResult.Error(1, "cache-not-exists"); + } + try + { + return BridgeResult.Success(File.ReadAllText(Globals.ThisAddIn.ActiveDocument.ProofreadCachePath)); + } + catch (Exception ex) + { + return BridgeResult.Error(ex.Message); + } + } + + public string ShowConfirm(string message, string caption, string yesButtonText, string noButtonText) + { + var result = FormDialog.Show(message, caption, yesButtonText, noButtonText); + return BridgeResult.Success(result == DialogResult.Yes ? "yes" : "no"); + } + + public string InitProofreadCacheList(string content) + { + try + { + List list = JsonConvert.DeserializeObject>(content); + Globals.ThisAddIn.InitProofreadCacheList(list); + return BridgeResult.Success(); + } + catch (Exception ex) + { + return BridgeResult.Error(ex); + } } } } diff --git a/AIProofread/Config.cs b/AIProofread/Config.cs index 02af291..32fb69d 100644 --- a/AIProofread/Config.cs +++ b/AIProofread/Config.cs @@ -12,7 +12,7 @@ namespace AIProofread public class Config { public static readonly string APP_NAME = "AI校对王"; - public static readonly string APP_VERSION = "1.0.12"; + public static readonly string APP_VERSION = "1.2.1"; public static bool IS_WPS = false; public static readonly string CONFIG_FILE = AppDomain.CurrentDomain.BaseDirectory + "app.json"; @@ -20,9 +20,9 @@ namespace AIProofread /// /// 网页访问地址 /// - public static string WEB_PATH = "http://192.168.10.100:5173/"; - public static bool RUN_IN_DEBUG = true; - public static AppEnvironment APP_ENV = AppEnvironment.Dev; + public static string WEB_PATH = "http://192.168.10.100:5173/"; //192.168.0.231:5137 192.168.10.100:5173 gm2-plugin.zverse.group + public static bool RUN_IN_DEBUG = false; + public static AppEnvironment APP_ENV = AppEnvironment.Prod; #else public static string WEB_PATH = "https://gm-plugin.gachafun.com/"; public static bool RUN_IN_DEBUG = false; diff --git a/AIProofread/Controls/FormDialog.Designer.cs b/AIProofread/Controls/FormDialog.Designer.cs new file mode 100644 index 0000000..3138c20 --- /dev/null +++ b/AIProofread/Controls/FormDialog.Designer.cs @@ -0,0 +1,109 @@ +namespace AIProofread.Controls +{ + partial class FormDialog + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.LabelMeesage = new System.Windows.Forms.Label(); + this.BtnClose = new System.Windows.Forms.Button(); + this.BtnConfirm = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // LabelMeesage + // + this.LabelMeesage.Font = new System.Drawing.Font("微软雅黑", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.LabelMeesage.ForeColor = System.Drawing.Color.Black; + this.LabelMeesage.Location = new System.Drawing.Point(39, 60); + this.LabelMeesage.Name = "LabelMeesage"; + this.LabelMeesage.Size = new System.Drawing.Size(346, 70); + this.LabelMeesage.TabIndex = 7; + this.LabelMeesage.Text = "label1"; + this.LabelMeesage.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // BtnClose + // + this.BtnClose.BackColor = System.Drawing.Color.White; + this.BtnClose.BackgroundImage = global::AIProofread.Properties.Resources.button_default; + this.BtnClose.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; + this.BtnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.BtnClose.FlatAppearance.BorderColor = System.Drawing.Color.Gainsboro; + this.BtnClose.FlatAppearance.BorderSize = 0; + this.BtnClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this.BtnClose.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.BtnClose.ForeColor = System.Drawing.Color.Black; + this.BtnClose.Location = new System.Drawing.Point(222, 205); + this.BtnClose.Name = "BtnClose"; + this.BtnClose.Size = new System.Drawing.Size(120, 44); + this.BtnClose.TabIndex = 6; + this.BtnClose.Text = "取消"; + this.BtnClose.UseVisualStyleBackColor = false; + this.BtnClose.Click += new System.EventHandler(this.BtnClose_Click); + // + // BtnConfirm + // + this.BtnConfirm.BackgroundImage = global::AIProofread.Properties.Resources.button; + this.BtnConfirm.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; + this.BtnConfirm.FlatAppearance.BorderSize = 0; + this.BtnConfirm.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this.BtnConfirm.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.BtnConfirm.ForeColor = System.Drawing.Color.White; + this.BtnConfirm.Location = new System.Drawing.Point(78, 205); + this.BtnConfirm.Name = "BtnConfirm"; + this.BtnConfirm.Size = new System.Drawing.Size(120, 44); + this.BtnConfirm.TabIndex = 5; + this.BtnConfirm.Text = "确认"; + this.BtnConfirm.UseVisualStyleBackColor = true; + this.BtnConfirm.Click += new System.EventHandler(this.button2_Click); + // + // FormDialog + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.White; + this.CancelButton = this.BtnClose; + this.ClientSize = new System.Drawing.Size(422, 286); + this.Controls.Add(this.LabelMeesage); + this.Controls.Add(this.BtnClose); + this.Controls.Add(this.BtnConfirm); + this.ForeColor = System.Drawing.Color.White; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "FormDialog"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Label LabelMeesage; + private System.Windows.Forms.Button BtnClose; + private System.Windows.Forms.Button BtnConfirm; + } +} \ No newline at end of file diff --git a/AIProofread/Controls/FormDialog.cs b/AIProofread/Controls/FormDialog.cs new file mode 100644 index 0000000..ae5a092 --- /dev/null +++ b/AIProofread/Controls/FormDialog.cs @@ -0,0 +1,49 @@ +using System; +using System.Windows.Forms; + +namespace AIProofread.Controls +{ + public partial class FormDialog : Form + { + public FormDialog() + { + InitializeComponent(); + } + + + private void SetMessage(string message) + { + LabelMeesage.Text = message; + } + private void SetButtonText(string yesButtonText, string noButtonText) + { + BtnClose.Text = noButtonText; + BtnConfirm.Text = yesButtonText; + } + + public static DialogResult Show(string message, string caption, string yesButtonText, string noButtonText) + { + FormDialog formMessage = new FormDialog(); + formMessage.SetMessage(message); + formMessage.Text = caption; + formMessage.SetButtonText(yesButtonText, noButtonText); + return formMessage.ShowDialog(); + } + public static DialogResult Show(string message) + { + return Show(message, "", "是", "否"); + } + + private void BtnClose_Click(object sender, EventArgs e) + { + this.DialogResult = DialogResult.No; + this.Close(); + } + + private void button2_Click(object sender, EventArgs e) + { + this.DialogResult = DialogResult.Yes; + this.Close(); + } + } +} diff --git a/AIProofread/Controls/FormDialog.resx b/AIProofread/Controls/FormDialog.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/AIProofread/Controls/FormDialog.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/AIProofread/Controls/FormLogger.Designer.cs b/AIProofread/Controls/FormLogger.Designer.cs new file mode 100644 index 0000000..cf0e51f --- /dev/null +++ b/AIProofread/Controls/FormLogger.Designer.cs @@ -0,0 +1,103 @@ +namespace AIProofread.Controls +{ + partial class FormLogger + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormLogger)); + this.LogText = new System.Windows.Forms.RichTextBox(); + this.panel1 = new System.Windows.Forms.Panel(); + this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); + this.TsmiClear = new System.Windows.Forms.ToolStripMenuItem(); + this.panel1.SuspendLayout(); + this.contextMenuStrip1.SuspendLayout(); + this.SuspendLayout(); + // + // LogText + // + this.LogText.AutoWordSelection = true; + this.LogText.BackColor = System.Drawing.Color.White; + this.LogText.BorderStyle = System.Windows.Forms.BorderStyle.None; + this.LogText.ContextMenuStrip = this.contextMenuStrip1; + this.LogText.Dock = System.Windows.Forms.DockStyle.Fill; + this.LogText.Font = new System.Drawing.Font("微软雅黑", 7.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.LogText.Location = new System.Drawing.Point(0, 0); + this.LogText.Name = "LogText"; + this.LogText.ReadOnly = true; + this.LogText.ShowSelectionMargin = true; + this.LogText.Size = new System.Drawing.Size(784, 491); + this.LogText.TabIndex = 0; + this.LogText.Text = ""; + // + // panel1 + // + this.panel1.Controls.Add(this.LogText); + this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; + this.panel1.Location = new System.Drawing.Point(0, 0); + this.panel1.Name = "panel1"; + this.panel1.Size = new System.Drawing.Size(784, 491); + this.panel1.TabIndex = 1; + // + // contextMenuStrip1 + // + this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.TsmiClear}); + this.contextMenuStrip1.Name = "contextMenuStrip1"; + this.contextMenuStrip1.Size = new System.Drawing.Size(181, 48); + // + // TsmiClear + // + this.TsmiClear.Name = "TsmiClear"; + this.TsmiClear.Size = new System.Drawing.Size(180, 22); + this.TsmiClear.Text = "清除日志"; + this.TsmiClear.Click += new System.EventHandler(this.TsmiClear_Click); + // + // FormLogger + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(784, 491); + this.Controls.Add(this.panel1); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.Name = "FormLogger"; + this.Text = "实时日志"; + this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.FormLogger_FormClosed); + this.panel1.ResumeLayout(false); + this.contextMenuStrip1.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.RichTextBox LogText; + private System.Windows.Forms.Panel panel1; + private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; + private System.Windows.Forms.ToolStripMenuItem TsmiClear; + } +} \ No newline at end of file diff --git a/AIProofread/Controls/FormLogger.cs b/AIProofread/Controls/FormLogger.cs new file mode 100644 index 0000000..387a54b --- /dev/null +++ b/AIProofread/Controls/FormLogger.cs @@ -0,0 +1,107 @@ +using System; +using System.Windows.Forms; + +namespace AIProofread.Controls +{ + public partial class FormLogger : Form + { + private ListView LogListView; + + public FormLogger() + { + InitializeComponent(); + + + //LogListView.View = View.Details; + //LogListView.FullRowSelect = true; + //LogListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); + + } + + private void InitLogListView() + { + var columnHeader1 = new ColumnHeader(); + var columnHeader2 = new ColumnHeader(); + var columnHeader3 = new ColumnHeader(); + + columnHeader1.Text = "Tag"; + columnHeader1.Width = 67; + columnHeader2.Text = "Time"; + columnHeader2.Width = 117; + columnHeader3.Text = "Message"; + columnHeader3.Width = 480; + + + LogListView.Columns.AddRange(new ColumnHeader[] {columnHeader1,columnHeader2,columnHeader3}); + } + + /// + /// 显示最大日志数 + /// + private const int MaxDisplayItemCount = 100; + + public void Log(string time, string tag, string message) + { + ShowLogInText(time, tag, message); + } + + private void ShowLogInText(string time, string tag, string message) + { + if (LogText.InvokeRequired) + { + //LogText.Invoke(new AppendLogDel(AppendLog), args); + } + else + { + LogText.AppendText(string.Format("{0} {1} {2}",time,tag,message)); + LogText.AppendText(Environment.NewLine); + LogText.ScrollToCaret(); + LogText.Update(); + } + } + + private void ShowLogInList(string time, string tag, string message) + { + if (LogListView.InvokeRequired) + { + LogListView.Invoke(new Action(() => AddLogToList(time, tag, message))); + } + else + { + AddLogToList(time, tag, message); + } + } + + private void AddLogToList(string time, string tag, string message) + { + // + ListViewItem insertItem = new ListViewItem(new string[] { tag, time, message }); + // + //insertItem.SubItems.Add(time); + //insertItem.SubItems.Add(tag, Color.Violet, Color.White, LogListView.Font); + //insertItem.SubItems.Add(message, Color.Blue, Color.White, LogListView.Font); + //ListViewSubItem tagItem = new ListViewSubItem(insertItem,tag); + //ListViewSubItem timeItem = new ListViewSubItem(insertItem,time, Color.Violet, Color.White, LogListView.Font); + //ListViewSubItem messageItem = new ListViewSubItem(insertItem, time, Color.Blue, Color.White, LogListView.Font); + + //insertItem.SubItems.Add(tagItem); + if (LogListView.Items.Count > MaxDisplayItemCount) + { + LogListView.Items.RemoveAt(MaxDisplayItemCount); + } + //ListViewItem lstItem = new ListViewItem(" " + DateTime.Now.ToString(), imageIndex); + //lstItem.SubItems.Add(info); + LogListView.Items.Insert(0, insertItem); + } + + private void FormLogger_FormClosed(object sender, FormClosedEventArgs e) + { + Logger.LoggerForm = null; + } + + private void TsmiClear_Click(object sender, EventArgs e) + { + LogText.Text = string.Empty; + } + } +} diff --git a/AIProofread/Controls/FormLogger.resx b/AIProofread/Controls/FormLogger.resx new file mode 100644 index 0000000..88bc642 --- /dev/null +++ b/AIProofread/Controls/FormLogger.resx @@ -0,0 +1,196 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + + + AAABAAEAIB4AAAEAIACgDwAAFgAAACgAAAAgAAAAPAAAAAEAIAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAQAA + AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAA + AAEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPQAA + AJUAAACYAAAAmAAAAJgAAACYAAAAmAAAAJgAAACYAAAAmAAAAJgAAACYAAAAmAAAAJgAAACYAAAAmAAA + AJgAAACYAAAAmAAAAJgAAACQAAAALQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAB9AAAA/wAAAOoAAADnAAAA5wAAAOcAAADnAAAA5wAAAOcAAADnAAAA5wAAAOcAAADnAAAA5wAA + AOcAAADnAAAA5wAAAOcAAADnAAAA8AAAAPoAAABaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAH4AAADpAAAAQQAAACMAAAAlAAAAJQAAACUAAAAlAAAAJQAAACUAAAAlAAAAJQAA + ACUAAAAlAAAAJQAAACUAAAAlAAAAJQAAACIAAABnAAAA8QAAAFsAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAOUAAAAhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEwAAADvAAAAWwAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB/AAAA5QAAACEAAAAAAAAAVQAAAJwAAABTAAAAAAAA + ADsAAACQAAAAkgAAAJIAAACSAAAAkgAAAJIAAACSAAAAkwAAAEgAAAAAAAAATQAAAO8AAABbAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH8AAADlAAAAIQAAAAAAAACMAAAA/wAA + AIsAAAAAAAAAUwAAAMwAAADPAAAAzwAAAM8AAADPAAAAzwAAAM8AAADQAAAAZgAAAAAAAABNAAAA7wAA + AFsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAOUAAAAhAAAAAAAA + ADsAAABxAAAAPQAAAAAAAAAEAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAFAAAAAAAA + AE0AAADvAAAAWwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB/AAAA5QAA + ACEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAATQAAAO8AAABbAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AH8AAADlAAAAIQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAABNAAAA7wAAAFsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAfwAAAOUAAAAhAAAAAAAAADkAAABrAAAAOAAAAAAAAAAyAAAAeAAAAHkAAAB5AAAAeQAA + AHkAAAB5AAAAeQAAAHoAAAA+AAAAAAAAAE0AAADvAAAAWwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAB/AAAA5QAAACEAAAAAAAAAjQAAAP8AAACLAAAAAAAAAFYAAADYAAAA2wAA + ANsAAADbAAAA2wAAANsAAADbAAAA3AAAAGoAAAAAAAAATQAAAO8AAABbAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH8AAADlAAAAIQAAAAAAAABWAAAAnwAAAFEAAAAAAAAACQAA + ABgAAAAYAAAAGAAAABgAAAAYAAAAGAAAABgAAAAYAAAACwAAAAAAAABNAAAA7wAAAFsAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAOUAAAAhAAAAAAAAAAIAAAAEAAAAAgAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE0AAADvAAAAWwAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB/AAAA5QAAACEAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATQAA + AO8AAABbAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH8AAADlAAAAIQAA + AAAAAAAkAAAAQAAAACEAAAAAAAAAHQAAAEcAAABIAAAASAAAAEgAAABIAAAASAAAAEgAAABIAAAAJAAA + AAAAAABNAAAA7wAAAFsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAA + AOUAAAAhAAAAAAAAAIkAAAD8AAAAhAAAAAAAAABhAAAA7wAAAPIAAADyAAAA8gAAAPIAAADyAAAA8gAA + APMAAAB3AAAAAAAAAE0AAADvAAAAWwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAB/AAAA5QAAACEAAAAAAAAAagAAAMkAAABoAAAAAAAAABUAAAA0AAAANQAAADUAAAA1AAAANQAA + ADUAAAA1AAAANQAAABoAAAAAAAAATQAAAO8AAABbAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAH8AAADlAAAAIQAAAAAAAAAJAAAAFAAAAAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNAAAA7wAAAFsAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAOUAAAAiAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABAAAAAQAA + AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAAAAAE0AAADvAAAAWwAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB9AAAA9wAAAKkAAACbAAAAnAAAAJwAAACcAAAAnAAA + AJwAAACcAAAAnAAAAJwAAACcAAAAnAAAAJwAAACcAAAAnAAAAJwAAACbAAAAuQAAAPUAAABbAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGkAAADhAAAA4gAAAOIAAADiAAAA4gAA + AOIAAADiAAAA4gAAAOIAAADiAAAA4gAAAOIAAADiAAAA4gAAAOIAAADiAAAA4gAAAOIAAADiAAAA2AAA + AEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAACUAAAAmAAAAJgAA + ACYAAAAmAAAAJgAAACYAAAAmAAAAJgAAACYAAAAmAAAAJgAAACYAAAAmAAAAJgAAACYAAAAmAAAAJgAA + ACYAAAAkAAAACQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAD////////////////8AAA/+AAAH/gAAB/4AAAf+P//H/iIAR/4iAEf+IgBH/j//x/4//8f+IgBH/iI + AR/4iAEf+I//H/j//x/4iAEf+IgBH/iIAR/4j/8f+PABH/gAAB/4AAAf+AAAH/////////////////// + //8= + + + \ No newline at end of file diff --git a/AIProofread/Controls/FormMessage.Designer.cs b/AIProofread/Controls/FormMessage.Designer.cs new file mode 100644 index 0000000..a35400c --- /dev/null +++ b/AIProofread/Controls/FormMessage.Designer.cs @@ -0,0 +1,128 @@ +namespace AIProofread.Controls +{ + partial class FormMessage + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.LabelMeesage = new System.Windows.Forms.Label(); + this.panel1 = new System.Windows.Forms.Panel(); + this.button3 = new System.Windows.Forms.Button(); + this.button2 = new System.Windows.Forms.Button(); + this.label1 = new System.Windows.Forms.Label(); + this.panel1.SuspendLayout(); + this.SuspendLayout(); + // + // LabelMeesage + // + this.LabelMeesage.Font = new System.Drawing.Font("微软雅黑", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.LabelMeesage.Location = new System.Drawing.Point(91, 87); + this.LabelMeesage.Name = "LabelMeesage"; + this.LabelMeesage.Size = new System.Drawing.Size(264, 70); + this.LabelMeesage.TabIndex = 4; + this.LabelMeesage.Text = "label1"; + this.LabelMeesage.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // panel1 + // + this.panel1.BackgroundImage = global::AIProofread.Properties.Resources.form_bg; + this.panel1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; + this.panel1.Controls.Add(this.label1); + this.panel1.Location = new System.Drawing.Point(1, 1); + this.panel1.Name = "panel1"; + this.panel1.Size = new System.Drawing.Size(442, 46); + this.panel1.TabIndex = 3; + // + // button3 + // + this.button3.BackColor = System.Drawing.Color.White; + this.button3.BackgroundImage = global::AIProofread.Properties.Resources.button_default; + this.button3.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; + this.button3.FlatAppearance.BorderColor = System.Drawing.Color.Gainsboro; + this.button3.FlatAppearance.BorderSize = 0; + this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this.button3.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.button3.ForeColor = System.Drawing.Color.Black; + this.button3.Location = new System.Drawing.Point(235, 210); + this.button3.Name = "button3"; + this.button3.Size = new System.Drawing.Size(120, 44); + this.button3.TabIndex = 2; + this.button3.Text = "关闭"; + this.button3.UseVisualStyleBackColor = false; + this.button3.Click += new System.EventHandler(this.button3_Click); + // + // button2 + // + this.button2.BackgroundImage = global::AIProofread.Properties.Resources.button; + this.button2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; + this.button2.FlatAppearance.BorderSize = 0; + this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this.button2.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.button2.ForeColor = System.Drawing.Color.White; + this.button2.Location = new System.Drawing.Point(91, 210); + this.button2.Name = "button2"; + this.button2.Size = new System.Drawing.Size(120, 44); + this.button2.TabIndex = 1; + this.button2.Text = "重新校对"; + this.button2.UseVisualStyleBackColor = true; + this.button2.Click += new System.EventHandler(this.button2_Click); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.BackColor = System.Drawing.Color.Transparent; + this.label1.Font = new System.Drawing.Font("微软雅黑", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label1.Location = new System.Drawing.Point(11, 10); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(88, 25); + this.label1.TabIndex = 0; + this.label1.Text = "温馨提示"; + // + // FormMessage + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(444, 286); + this.Controls.Add(this.LabelMeesage); + this.Controls.Add(this.panel1); + this.Controls.Add(this.button3); + this.Controls.Add(this.button2); + this.Name = "FormMessage"; + this.Text = "FormMessage"; + this.panel1.ResumeLayout(false); + this.panel1.PerformLayout(); + this.ResumeLayout(false); + + } + + #endregion + private System.Windows.Forms.Button button2; + private System.Windows.Forms.Button button3; + private System.Windows.Forms.Panel panel1; + private System.Windows.Forms.Label LabelMeesage; + private System.Windows.Forms.Label label1; + } +} \ No newline at end of file diff --git a/AIProofread/Controls/FormMessage.cs b/AIProofread/Controls/FormMessage.cs new file mode 100644 index 0000000..d3dabd8 --- /dev/null +++ b/AIProofread/Controls/FormMessage.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace AIProofread.Controls +{ + public partial class FormMessage : BaseWinForm + { + public FormMessage() + { + InitializeComponent(); + } + + private void SetMessage(string message) + { + LabelMeesage.Text = message; + } + + public static DialogResult ShowMessage(string message) + { + FormMessage formMessage = new FormMessage(); + formMessage.SetMessage(message); + return formMessage.ShowDialog(); + } + + private void button3_Click(object sender, EventArgs e) + { + this.DialogResult = DialogResult.OK; + this.Close(); + } + + private void button2_Click(object sender, EventArgs e) + { + this.DialogResult = DialogResult.Retry; + this.Close(); + } + } +} diff --git a/AIProofread/Controls/FormMessage.resx b/AIProofread/Controls/FormMessage.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/AIProofread/Controls/FormMessage.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/AIProofread/Controls/FormWebView.Designer.cs b/AIProofread/Controls/FormWebView.Designer.cs new file mode 100644 index 0000000..fb8159f --- /dev/null +++ b/AIProofread/Controls/FormWebView.Designer.cs @@ -0,0 +1,66 @@ +namespace AIProofread.Controls +{ + partial class FormWebView + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.WebView = new Microsoft.Web.WebView2.WinForms.WebView2(); + ((System.ComponentModel.ISupportInitialize)(this.WebView)).BeginInit(); + this.SuspendLayout(); + // + // WebView + // + this.WebView.AllowExternalDrop = true; + this.WebView.CreationProperties = null; + this.WebView.DefaultBackgroundColor = System.Drawing.Color.White; + this.WebView.Dock = System.Windows.Forms.DockStyle.Fill; + this.WebView.Location = new System.Drawing.Point(0, 0); + this.WebView.Name = "WebView"; + this.WebView.Size = new System.Drawing.Size(800, 450); + this.WebView.TabIndex = 0; + this.WebView.ZoomFactor = 1D; + // + // FormWebView + // + this.AllowDrop = true; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.WebView); + this.Name = "FormWebView"; + this.Text = "FormWebView"; + this.Load += new System.EventHandler(this.FormWebView_Load); + ((System.ComponentModel.ISupportInitialize)(this.WebView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Microsoft.Web.WebView2.WinForms.WebView2 WebView; + } +} \ No newline at end of file diff --git a/AIProofread/Controls/FormWebView.cs b/AIProofread/Controls/FormWebView.cs new file mode 100644 index 0000000..0716a75 --- /dev/null +++ b/AIProofread/Controls/FormWebView.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace AIProofread.Controls +{ + [ClassInterface(ClassInterfaceType.AutoDual)] + [ComVisible(true)] + public partial class FormWebView : BaseWinForm + { + public string WebUrl { get; set; } + public FormWebView(string url,int width,int height) + { + InitializeComponent(); + this.WebUrl = url; + this.SetSize(width, height); + } + public void SetSize(int width, int height) + { + this.Width = width; + this.Height = height; + } + + private void FormWebView_Load(object sender, EventArgs e) + { + // 初始化 + InitWebView(WebView,this.WebUrl, "webview"); + } + } +} diff --git a/AIProofread/Controls/FormWebView.resx b/AIProofread/Controls/FormWebView.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/AIProofread/Controls/FormWebView.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/AIProofread/Controls/ProofreadMainControl.cs b/AIProofread/Controls/ProofreadMainControl.cs index 3b5ad92..4409e67 100644 --- a/AIProofread/Controls/ProofreadMainControl.cs +++ b/AIProofread/Controls/ProofreadMainControl.cs @@ -7,15 +7,9 @@ namespace AIProofread.Controls { public partial class ProofreadMainControl : UserControl { - private Document doc; - private int minWidth; - - - public ProofreadMainControl(Document doc,int minWidth) + public ProofreadMainControl() { InitializeComponent(); - this.doc = doc; - this.minWidth = minWidth; Bridge.InitWebEnvAsync("main", web); //this.minWidth = 420 * LabelWidth() / 42; @@ -25,17 +19,17 @@ namespace AIProofread.Controls private void ProofreadMainControl_Load(object sender, EventArgs e) { - this.web.Source = new Uri(Config.WebPath("home?version=" + Config.APP_VERSION + "&t=" + DateTime.Now.Ticks)); + this.web.Source = new Uri(Config.WebPath("correct?version=" + Config.APP_VERSION + "&t=" + DateTime.Now.Ticks)); //this.SizeChanged += ProofreadMainControl_SizeChanged; } private void ProofreadMainControl_SizeChanged(object sender, EventArgs e) { - if(this.minWidth > 0 && this.Width < this.minWidth) - { - SendKeys.Send("{ESC}"); - this.Width = this.minWidth; - } + //if(this.minWidth > 0 && this.Width < this.minWidth) + //{ + // SendKeys.Send("{ESC}"); + // this.Width = this.minWidth; + //} } public int LabelWidth() { diff --git a/AIProofread/Logger.cs b/AIProofread/Logger.cs index 1b3257e..091d409 100644 --- a/AIProofread/Logger.cs +++ b/AIProofread/Logger.cs @@ -1,43 +1,55 @@ -using System; +using AIProofread.Controls; +using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Windows.Interop; namespace AIProofread { public class Logger { - private static readonly string AppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + public static FormLogger LoggerForm; + //private static readonly string AppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); /// /// /// /// - public static void Log(string msg) + public static void Log(string tag,string message) { + string time = DateTime.Now.ToString("HH:mm:ss"); + + // 如果日志窗口已经打开,则显示日志 + if (LoggerForm != null && !LoggerForm.IsDisposed && LoggerForm.Visible) + { + LoggerForm.Log(time, tag, message); + return; + } string path = Config.APP_LOG_PATH + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; if (!Directory.Exists(Config.APP_LOG_PATH)) { Directory.CreateDirectory(Config.APP_LOG_PATH); } StreamWriter streamWriter = File.AppendText(path); - streamWriter.WriteLine("***************************[" + (Config.IS_WPS ? "WPS" : "WORD") + "]***************************"); - streamWriter.WriteLine("消息:" + msg); - streamWriter.WriteLine("时间:" + DateTime.Now.ToString("HH:mm:ss")); + streamWriter.WriteLine("***************************[" + tag + "]***************************"); + streamWriter.WriteLine("消息:" + message); + streamWriter.WriteLine("时间:" + time); streamWriter.WriteLine(); streamWriter.Flush(); streamWriter.Close(); streamWriter.Dispose(); } - public static void Log( Exception e) + public static void Log(string msg) + { + Log((Config.IS_WPS ? "WPS" : "WORD"), msg); + } + public static void Log(Exception e) { Log(e.Message + "\n" + e.StackTrace); } public static void Log(string tag, Exception e) { - Log(tag + "\n" + e.StackTrace); + Log(tag,e.Message + "\n" + e.StackTrace); } public static void LogToWeb(string msg) diff --git a/AIProofread/Model/BridgeResult.cs b/AIProofread/Model/BridgeResult.cs new file mode 100644 index 0000000..240625b --- /dev/null +++ b/AIProofread/Model/BridgeResult.cs @@ -0,0 +1,47 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AIProofread.Model +{ + class BridgeResultModel + { + [JsonProperty("code")] + public int Code { get; set; } + [JsonProperty("message")] + public string Message { get; set; } + [JsonProperty("data")] + public object Data { get; set; } + } + public class BridgeResult + { + public static string Error() + { + return Error(-1, "error"); + } + + public static string Error(Exception ex) + { + return Error(-1, ex.Message); + } + public static string Error(string message) + { + return Error(-1, message); + } + public static string Error(int code, string message) + { + return JsonConvert.SerializeObject(new BridgeResultModel() { Code = code, Message = message }); + } + public static string Success() + { + return Success(null); + } + public static string Success(object data) + { + return JsonConvert.SerializeObject(new BridgeResultModel() { Code = 0, Data = data, Message = "success" }); + } + } +} diff --git a/AIProofread/Model/DocumentContent.cs b/AIProofread/Model/DocumentContent.cs new file mode 100644 index 0000000..5758304 --- /dev/null +++ b/AIProofread/Model/DocumentContent.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AIProofread.Model +{ + public class DocumentContent + { + + [JsonProperty("origin")] + public string[] OriginCut { get; set; } + [JsonProperty("trim_cut")] + public string[] TrimCut { get; set; } + [JsonProperty("paragraphs")] + public string[] Paragraphs { get; set; } + + } +} diff --git a/AIProofread/Model/DocumentInfo.cs b/AIProofread/Model/DocumentInfo.cs index 278a676..fe245df 100644 --- a/AIProofread/Model/DocumentInfo.cs +++ b/AIProofread/Model/DocumentInfo.cs @@ -1,11 +1,16 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.Office.Core; +using System.Drawing; +using System.IO; +using System.Threading; +using System.Windows.Forms; +using AIProofread.Controls; +using AIProofread.core; +using AIProofread.Util; using Microsoft.Office.Interop.Word; +using Newtonsoft.Json; using UtilLib; +using CustomTaskPane = Microsoft.Office.Tools.CustomTaskPane; namespace AIProofread.Model { @@ -14,18 +19,119 @@ namespace AIProofread.Model /// public class DocumentInfo { + public static readonly int MIN_WIDTH = 420; private static char[] ArticleSpecialChars = new char[4] { '\a', '\r', '\v', '\f' }; - //private Document currentDocument; - public Document CurrentDocument { get; set; } - private string fileName; - private string uniqueId; + private static object missing = System.Reflection.Missing.Value; + /// + /// + /// + public Dictionary marks = new Dictionary(); + + /// + /// 最小宽度 + /// + public static int MinWidth = 0; + /// + /// 校对选区集合 + /// private List ranges = new List(); - public string UniqueId - { - get { return uniqueId; } + /// + /// 当前选中对现象编号 + /// + private int selectProofreadId; + + //private Document currentDocument; + /// + /// 当前对应文档 + /// + public Document CurrentDocument { get; set; } + + /// + /// 文件名称 + /// + private string fileName; + + private string uniqueId; + public string UniqueId { get { return uniqueId; } } + + public string ProofreadCachePath + { + get + { + return CurrentDocument.FullName + "-proofread.json"; + } + } + + public bool IsActive { get; internal set; } + public bool PaneVisible { get; set; } + public int Id { get; set; } + + public CustomTaskPane TaskPane { get; set; } + + // 初始化 + public DocumentInfo(Document doc) + { + this.CurrentDocument = doc; + Initialize(); + } + + /// + /// 显示面板 + /// + public void ShowPane() + { + if (null != TaskPane) + { + TaskPane.Visible = PaneVisible = true; + } + } + + /// + /// 隐藏面板 + /// + public void HidePane() + { + if (null != TaskPane) TaskPane.Visible = PaneVisible = false; + } + + /// + /// 激活 + /// + public void Active() + { + IsActive = true; + if (null != TaskPane && PaneVisible) + { + TaskPane.Visible = true; + } + } + + public void Deactive() + { + IsActive = false; + if (null != TaskPane && PaneVisible) + { + TaskPane.Visible = false; + } + } + + public void Dispose() + { + try + { + ProofreadMainControl control = (ProofreadMainControl)TaskPane.Control; + control.ResetWeb(); + + HidePane(); + TaskPane?.Dispose(); + } + catch (Exception e) + { + Logger.Log("Error", e); + } } // 计算uniqueId @@ -40,16 +146,58 @@ namespace AIProofread.Model uniqueId = filename.GetHashCode().ToString(); } - // 初始化 - public DocumentInfo(Document doc) + /// + /// 添加变量控制重复调用 + /// + private bool isResizing = false; + private void Control_SizeChanged(object sender, EventArgs e) { - this.CurrentDocument = doc; + if (isResizing) return; + if (TaskPane != null && TaskPane.Visible && TaskPane.Width < MinWidth) + { + isResizing = true; + SendKeys.Send("{ESC}"); + TaskPane.Width = MinWidth; + isResizing = false; + } + } + + // 创建pane 并初始化 + public void CreateTaskPane() + { + var control = new ProofreadMainControl(); + if (MinWidth < 10) + { + MinWidth = MIN_WIDTH * control.LabelWidth() / 42; + } + // 创建pane + TaskPane = Globals.ThisAddIn.CustomTaskPanes.Add(control, " "); + // 默认隐藏 + TaskPane.Visible = false; + // 设置宽度 + control.Width = MinWidth; + TaskPane.Width = MinWidth; + + // 监听尺寸变化 防止最小尺寸小于设置值 + control.SizeChanged += Control_SizeChanged; + TaskPane.VisibleChanged += TaskPane_VisibleChanged; + } + + private void TaskPane_VisibleChanged(object sender, EventArgs e) + { + // 如果已经隐藏 则记录隐藏用于(WPS)多面板的切换的处理 + if (TaskPane.Visible) + { + PaneVisible = TaskPane.Visible; + } } public void Initialize() { ranges.Clear(); ComputeUniqueId(); + if (TaskPane == null) CreateTaskPane(); + } //处理文档选区时 判断当前选区是否有校对项 有则选择该范围 @@ -103,6 +251,34 @@ namespace AIProofread.Model return string.IsNullOrEmpty(text) ? "" : text; } + /// + /// 保存校对缓存结果 + /// + private void SaveProofreadCache(string cacheData) + { + // 判断文档是否已经保存 + + if (!CurrentDocument.Saved) + { + // 保存文档 + if (!CurrentDocument.Saved) + { + // 提示保存文档 + var result = MessageBox.Show("当前文档尚未保存,是否保存?", "提示", MessageBoxButtons.YesNo); + if (result == DialogResult.Yes) + { + CurrentDocument.Save(); + } + else + { + return; + } + } + } + } + + + // 定位所有的校对项 public void LocateAllProofreadItems(List list) { @@ -115,7 +291,7 @@ namespace AIProofread.Model { foreach (var correct in item.CorrectItems) { - var range = LocateProofreadItem(correct,item,ref prevOffset); + var range = LocateProofreadItem(correct, item, ref prevOffset); if (range == null) continue; } @@ -149,10 +325,12 @@ namespace AIProofread.Model var paraText = paraRange.Text; var paraStart = paraRange.Start; - var offset = paraStart + ctx.SentenceOffset; + //var offset = paraStart + ctx.SentenceOffset; //var cutLength = Math.Min(c.InsertLen, paraText.Length - offset); - var sentence = paraText.Substring(ctx.SentenceOffset, ctx.InsertLength); - if (sentence == ctx.Insert) + var sentence = paraRange.Sentences[ctx.SentenceNumber]; //paraText.Substring(ctx.SentenceOffset, ctx.InsertLength); + ctx.SentenceOffset = sentence.Start; + var offset = paraStart + ctx.SentenceOffset; + if (sentence.Text == ctx.Insert) { // 比对原始内容与校对原文是否一致 var range = document.Range(offset + correct.Start, offset + correct.End); // @@ -221,8 +399,255 @@ namespace AIProofread.Model } + public void SendMessageToWeb(string msg, object data) + { + var json = JsonConvert.SerializeObject(new WebMessage(msg, data)); + ProofreadMainControl control = (ProofreadMainControl)TaskPane.Control; + try + { + if (control.web.CoreWebView2 == null) + { + Thread.Sleep(300); + } + control.web.CoreWebView2.PostWebMessageAsJson(json); + } + catch (Exception ex) + { + Logger.Log("SendMessage", "send message to web error \n" + ex.Message + "\n" + msg + data.ToString()); + } + } - + public void ClearAllProofreadMark() + { + try + { + selectProofreadId = -1; + foreach (var item in marks.Values) + { + if (item.mark != null) + { + if (item.content.Tag == "i" && item.content.IsAccept == AcceptStatus.Default) + { + item.mark.Text = ""; + } + item.ResetMarkStyle(); + } + } + DocumentUtil.ClearProofreadMarks(); + } + catch (Exception ex) + { + Logger.Log("ClearAllProofreadMark", ex); + } + // 清空marks + marks.Clear(); + } + /// + /// 选中标签 + /// + /// + public void SelectMarkById(int proofreadId) + { + if (proofreadId == selectProofreadId) return; + // 取消上一个标签移除 + if (selectProofreadId > 0 && marks.ContainsKey(selectProofreadId)) + { + var m = marks[selectProofreadId]; + if (m != null && CurrentDocument.Bookmarks.Exists(m.Name)) + { + marks[selectProofreadId].UnSelect(); + } + else + { + marks.Remove(selectProofreadId); + } + } + selectProofreadId = proofreadId; + + if (proofreadId > 0 && marks.ContainsKey(proofreadId)) + { + var mark = marks[proofreadId].mark; + if (mark == null) return; + // 已经不存在该标签了 + if (mark != null && !CurrentDocument.Bookmarks.Exists(mark.Name)) + { + marks.Remove(selectProofreadId); + return; + } + //object lineNum = (int)mark.Range.Information[WdInformation.wdFirstCharacterLineNumber] - 1; + //object goToLine = WdGoToItem.wdGoToLine; + //object goNext = WdGoToDirection.wdGoToNext; + //Globals.ThisAddIn.Application.ActiveWindow.Selection.GoTo(ref goToLine, ref goNext, ref lineNum); + // + object bookmark = WdGoToItem.wdGoToBookmark; + object bookmarkName = mark.Name; + //doc.GoTo(mark); + //mark.Range.GoTo(); + Globals.ThisAddIn.Application.ActiveWindow.Selection.GoTo(ref bookmark, ref missing, ref missing, ref bookmarkName); + // + //mark.DisableCharacterSpaceGrid = false; + // 先滚动到可视区域 + //doc.ActiveWindow.ScrollIntoView(mark.Range); + marks[proofreadId].Select(); + //Globals.ThisAddIn.SendMessageToWeb("select", proofreadId); + } + Globals.ThisAddIn.SendMessageToWeb("select-proofread", proofreadId); + } + + + public void InitProofread(List list) + { + int prevOffset = 0; + + List disabledList = new List(); + foreach (var correct in list) + { + Logger.Log(string.Format("correct content:", correct.Insert)); + if (correct.CorrectItems != null && correct.CorrectItems.Count > 0) + { + prevOffset = 0; + int index = 0; + foreach (var item in correct.CorrectItems) + { + Logger.Log(string.Format("mark type {0} data {1}->{2}", item.Tag, item.Origin, item.Text)); + int _prev = prevOffset; + // 查找对应区域并再该区域添加书签 + var mark = DocumentUtil.FindRangeAndCreateBookmark(item, correct, CurrentDocument, ref prevOffset); + // 防止调用方法中没有更新 + if (_prev >= prevOffset) + { + prevOffset = correct.SentenceOffset + item.Start; + } + + if (item.Tag != "i") index++; + if (mark != null) + { + marks.Add(item.Id, new ProofreadItem(item,correct.Insert, mark, Id)); + } + else + { + disabledList.Add(item.Id); + var msg = new Dictionary{ + {"message","没有找到标记对象" }, + { "origin",item }, + { "origin_correct",correct }, + { "new_text",correct.NewText }, + { "paragraph_num",correct.ParagraphNumber }, + }; + Logger.Log(JsonConvert.SerializeObject(msg)); + } + } + } + } + foreach (var item in marks) + { + if (item.Value.mark != null) + { + if (item.Value.content.Tag == "i") + { + item.Value.mark.Text = ToolUtil.GetBlankText(item.Value.content.Text.Length); + } + if (item.Value.content.Color != null) + { + try + { + var color = (WdColor)ColorTranslator.ToOle(Colors.FromHex(item.Value.content.Color)); + // 给选区添加背景颜色 + item.Value.mark.Shading.BackgroundPatternColor = color; + } + catch (Exception) + { + //item.Value.mark.Shading.BackgroundPatternColor = WdColor.wdColorLightOrange; + } + } + } + } + + // 隐藏面板对应校对项 + MainPanelWebMessage.DisabledProofreadItem(disabledList); + } + + + public void InitProofreadCache(List list) + { + marks.Clear(); + + foreach (var correct in list) + { + correct.CorrectItems.ForEach(item => + { + var mark = DocumentUtil.FindBookMarkByCorrect(item); + var pi = new ProofreadItem(item,correct.Insert, mark, Id); + marks.Add(item.Id, pi); + }); + //marks.Add(item.Id, new ProofreadItem(item.CorrectItems[0], null, Id)); + } + } + + private void FindMarkByCorrectItem() + { + + } + + public DocumentContent GetAllParagraphs() + { + string rangeText = CurrentDocument.Content.Text; + string trimText = HostHelper.ReplaceSpecialChars(rangeText, isReplaceMultSpaceLine: true); + + string[] separator = new string[5] { "\r\a", "\a", "\r", "\v", "\f" }; + string[] array4 = rangeText.Split(separator, StringSplitOptions.None); + string[] array5 = trimText.Split('\n'); + + List list = new List(); + var paragraphs = CurrentDocument.Paragraphs; + int total = paragraphs.Count; + for (int i = 1; i <= total; i++) + { + list.Add(GetParagraphText(paragraphs[i])); + } + + return new DocumentContent() + { + OriginCut = array4, + TrimCut = array5, + Paragraphs = list.ToArray(), + }; + } + + private string GetParagraphText(Paragraph paragraph) + { + // 需要 + return GetRangeText(paragraph.Range); + } + + /// + /// 获取文档段落总数 + /// + /// + public int GetTotalParagraphNumber() + { + return CurrentDocument.Paragraphs.Count; + } + + /// + /// 读取文档原始文件并转换成base64 + /// + /// + public string GetOriginFileData() + { + FileStream fs = new FileStream(CurrentDocument.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); + byte[] bytes = new byte[fs.Length]; + fs.Read(bytes, 0, bytes.Length); + return Convert.ToBase64String(bytes); + } + + internal void ProcessMark(int proofreadId, int status) + { + if (proofreadId > 0 && marks.ContainsKey(proofreadId)) + { + marks[proofreadId].Process(status); + } + } } } diff --git a/AIProofread/Model/DocumentList.cs b/AIProofread/Model/DocumentList.cs new file mode 100644 index 0000000..6039d4c --- /dev/null +++ b/AIProofread/Model/DocumentList.cs @@ -0,0 +1,123 @@ +using Microsoft.Office.Interop.Word; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AIProofread.Model +{ + /// + /// 文档列表 + /// + public class DocumentList + { + public List documentList = new List(); + public DocumentInfo ActiveDocument { get; set; } + public int Count => documentList.Count; + + public void Add(DocumentInfo documentInfo) + { + documentList.Add(documentInfo); + } + + public void Clear() + { + documentList.ForEach(doc =>{ doc.Dispose(); }); + + documentList.Clear(); + } + + public DocumentInfo Get(int index) + { + return documentList[index]; + } + public DocumentInfo GetById(int id) + { + return Count > 0 ? documentList.FirstOrDefault(x => x.Id == id) : null; + } + public DocumentInfo Get(string uniqueId) + { + return Count > 0 ? documentList.FirstOrDefault(x => x.UniqueId == uniqueId) : null; + } + public DocumentInfo Get(Document doc) + { + return Count > 0 && doc != null ? documentList.FirstOrDefault(x => x.CurrentDocument == doc) : null; + } + + public DocumentInfo GetActive() + { + // documentList.FirstOrDefault(x => x.IsActive) + return Count > 0 ? ActiveDocument : null; + } + + public bool Contains(DocumentInfo documentInfo) + { + return Count > 0 && documentList.Contains(documentInfo); + } + + public bool Contains(string uniqueId) + { + return Count > 0 && documentList.Any(x => x.UniqueId == uniqueId); + } + + // 通过文档判断是否包含 + public bool Contains(Document originDocument) + { + return Count > 0 && originDocument != null && documentList.Any(x => x.CurrentDocument == originDocument); + } + + /// + /// 移除文档 + /// + /// + /// + public bool Remove(DocumentInfo documentInfo) + { + return documentList.Remove(documentInfo); + } + + /// + /// 获取文档的索引 + /// + /// + /// + public int IndexOf(DocumentInfo item) + { + return documentList.IndexOf(item); + } + + /// + /// 设置当前激活的文档 + /// + /// + public DocumentInfo SetActiveDocument(Document originDocument) + { + if (originDocument == null) return null; + var document = Get(originDocument); + + // 如果不存在,则添加 + if (document == null) + { + document = new DocumentInfo(originDocument); + Add(document); + } + if (ActiveDocument == document) return document; + else if (Globals.ThisAddIn.IsWPS) + { + // WPS 只有一个窗口 所以需要先关闭之前文档的面板 + ActiveDocument?.Deactive(); + } + // 如果存在,则设置激活 + ActiveDocument = document; + //document.IsActive = true; + document.Active(); + return document; + } + + internal void HideAllPane() + { + documentList.ForEach(d => d.HidePane()); + } + } +} diff --git a/AIProofread/ProofreadItem.cs b/AIProofread/ProofreadItem.cs index f23a4fa..481f44a 100644 --- a/AIProofread/ProofreadItem.cs +++ b/AIProofread/ProofreadItem.cs @@ -8,9 +8,11 @@ using Bookmark = Microsoft.Office.Tools.Word.Bookmark; namespace UtilLib { + public class ProofreadItem { public Bookmark mark; + public string OriginSentence { get; set; } public CorrectItem content; private float originSize; private WdColor originColor; @@ -18,10 +20,11 @@ namespace UtilLib public string Name { get; set; } public int DocumentId { get; set; } - public ProofreadItem(CorrectItem content,int documentId) + public ProofreadItem(CorrectItem content,string originSentence,int documentId) { this.content = content; this.DocumentId = documentId; + this.OriginSentence = originSentence; InitBookMark(null); SetMarkName(); } @@ -31,9 +34,10 @@ namespace UtilLib this.Name = this.mark != null ? mark.Name : Config.BuildBookmarkName(content.Id); } - public ProofreadItem(CorrectItem content, Bookmark bookmark, int documentId) + public ProofreadItem(CorrectItem content, string originSentence, Bookmark bookmark, int documentId) { this.DocumentId = documentId; + this.OriginSentence = originSentence; this.content = content; if (bookmark != null) { diff --git a/AIProofread/Properties/Resources.Designer.cs b/AIProofread/Properties/Resources.Designer.cs index d386324..125e77e 100644 --- a/AIProofread/Properties/Resources.Designer.cs +++ b/AIProofread/Properties/Resources.Designer.cs @@ -60,6 +60,26 @@ namespace AIProofread.Properties { } } + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap button { + get { + object obj = ResourceManager.GetObject("button", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap button_default { + get { + object obj = ResourceManager.GetObject("button_default", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + /// /// 查找 System.Drawing.Bitmap 类型的本地化资源。 /// @@ -70,6 +90,16 @@ namespace AIProofread.Properties { } } + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap form_bg { + get { + object obj = ResourceManager.GetObject("form_bg", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + /// /// 查找 System.Drawing.Bitmap 类型的本地化资源。 /// @@ -110,6 +140,46 @@ namespace AIProofread.Properties { } } + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap icon_export { + get { + object obj = ResourceManager.GetObject("icon-export", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap icon_export_wps { + get { + object obj = ResourceManager.GetObject("icon-export-wps", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap icon_history { + get { + object obj = ResourceManager.GetObject("icon-history", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap icon_history_wps { + get { + object obj = ResourceManager.GetObject("icon-history-wps", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + /// /// 查找 System.Drawing.Bitmap 类型的本地化资源。 /// @@ -130,6 +200,26 @@ namespace AIProofread.Properties { } } + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap icon_panel { + get { + object obj = ResourceManager.GetObject("icon-panel", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap icon_panel_wps { + get { + object obj = ResourceManager.GetObject("icon-panel-wps", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + /// /// 查找 System.Drawing.Bitmap 类型的本地化资源。 /// diff --git a/AIProofread/Properties/Resources.resx b/AIProofread/Properties/Resources.resx index 54ecec9..645ba9f 100644 --- a/AIProofread/Properties/Resources.resx +++ b/AIProofread/Properties/Resources.resx @@ -118,67 +118,94 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - ..\Resources\icon-proofread.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-setting-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-logout.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-phone-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-user-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-setting.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-phone.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-book-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-proofread-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-update-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-book.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\favicon.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-clear.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-clear-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-logout-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\icon-update.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + ..\Resources\icon-panel.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a ..\Resources\icon-user.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - ..\Resources\icon-refresh.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + ..\Resources\icon-save-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - ..\Resources\icon-refresh-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + ..\Resources\icon-proofread-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\button.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-phone.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-user-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\form_bg.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a ..\Resources\icon-save.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - ..\Resources\icon-save-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + ..\Resources\icon-logout-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-book-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-update-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-setting.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-update.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-clear-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-book.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-panel-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\favicon.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-refresh-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\button_default.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-refresh.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-setting-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-clear.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-phone-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-history-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-logout.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-history.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-proofread.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-export-wps.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\icon-export.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a \ No newline at end of file diff --git a/AIProofread/Resources/button.png b/AIProofread/Resources/button.png new file mode 100644 index 0000000..c3e0a9f Binary files /dev/null and b/AIProofread/Resources/button.png differ diff --git a/AIProofread/Resources/button_default.png b/AIProofread/Resources/button_default.png new file mode 100644 index 0000000..9a73f5d Binary files /dev/null and b/AIProofread/Resources/button_default.png differ diff --git a/AIProofread/Resources/export.png b/AIProofread/Resources/export.png new file mode 100644 index 0000000..d400e95 Binary files /dev/null and b/AIProofread/Resources/export.png differ diff --git a/AIProofread/Resources/form_bg.png b/AIProofread/Resources/form_bg.png new file mode 100644 index 0000000..34e9a8c Binary files /dev/null and b/AIProofread/Resources/form_bg.png differ diff --git a/AIProofread/Resources/icon-export-wps.jpg b/AIProofread/Resources/icon-export-wps.jpg new file mode 100644 index 0000000..98e5742 Binary files /dev/null and b/AIProofread/Resources/icon-export-wps.jpg differ diff --git a/AIProofread/Resources/icon-export.png b/AIProofread/Resources/icon-export.png new file mode 100644 index 0000000..f449f13 Binary files /dev/null and b/AIProofread/Resources/icon-export.png differ diff --git a/AIProofread/Resources/icon-history-wps.jpg b/AIProofread/Resources/icon-history-wps.jpg new file mode 100644 index 0000000..90df8b5 Binary files /dev/null and b/AIProofread/Resources/icon-history-wps.jpg differ diff --git a/AIProofread/Resources/icon-history.png b/AIProofread/Resources/icon-history.png new file mode 100644 index 0000000..1ad3d17 Binary files /dev/null and b/AIProofread/Resources/icon-history.png differ diff --git a/AIProofread/Resources/icon-panel-wps.jpg b/AIProofread/Resources/icon-panel-wps.jpg new file mode 100644 index 0000000..064f943 Binary files /dev/null and b/AIProofread/Resources/icon-panel-wps.jpg differ diff --git a/AIProofread/Resources/icon-panel.png b/AIProofread/Resources/icon-panel.png new file mode 100644 index 0000000..9b64958 Binary files /dev/null and b/AIProofread/Resources/icon-panel.png differ diff --git a/AIProofread/Resources/icon-save-wps.jpg b/AIProofread/Resources/icon-save-wps.jpg index c415533..bf749cc 100644 Binary files a/AIProofread/Resources/icon-save-wps.jpg and b/AIProofread/Resources/icon-save-wps.jpg differ diff --git a/AIProofread/Resources/icon-save.png b/AIProofread/Resources/icon-save.png index 73a5f4a..7ef3b41 100644 Binary files a/AIProofread/Resources/icon-save.png and b/AIProofread/Resources/icon-save.png differ diff --git a/AIProofread/Ribbon1.Designer.cs b/AIProofread/Ribbon1.Designer.cs index 2c8b486..d71bce4 100644 --- a/AIProofread/Ribbon1.Designer.cs +++ b/AIProofread/Ribbon1.Designer.cs @@ -39,6 +39,7 @@ namespace AIProofread this.tabAIProofread = this.Factory.CreateRibbonTab(); this.group1 = this.Factory.CreateRibbonGroup(); this.BtnProofreadAll = this.Factory.CreateRibbonButton(); + this.BtnExportProofreadResult = this.Factory.CreateRibbonButton(); this.btnClear = this.Factory.CreateRibbonButton(); this.btnOpenLexicon = this.Factory.CreateRibbonButton(); this.btnSetting = this.Factory.CreateRibbonButton(); @@ -51,14 +52,20 @@ namespace AIProofread this.Group = this.Factory.CreateRibbonGroup(); this.ButtonSaveCache = this.Factory.CreateRibbonButton(); this.ButtonLoadCache = this.Factory.CreateRibbonButton(); + this.group2 = this.Factory.CreateRibbonGroup(); + this.BtnShowPanel = this.Factory.CreateRibbonButton(); this.grpDebug = this.Factory.CreateRibbonGroup(); this.btnShowPane = this.Factory.CreateRibbonButton(); this.btnHidePane = this.Factory.CreateRibbonButton(); this.BtnOpenLog = this.Factory.CreateRibbonButton(); this.button1 = this.Factory.CreateRibbonButton(); + this.BtnOpenLogger = this.Factory.CreateRibbonButton(); + this.BtnTest = this.Factory.CreateRibbonButton(); + this.BtnOpenAppDir = this.Factory.CreateRibbonButton(); this.tabAIProofread.SuspendLayout(); this.group1.SuspendLayout(); this.Group.SuspendLayout(); + this.group2.SuspendLayout(); this.grpDebug.SuspendLayout(); this.SuspendLayout(); // @@ -66,6 +73,7 @@ namespace AIProofread // this.tabAIProofread.Groups.Add(this.group1); this.tabAIProofread.Groups.Add(this.Group); + this.tabAIProofread.Groups.Add(this.group2); this.tabAIProofread.Groups.Add(this.grpDebug); this.tabAIProofread.Label = "AI校对王"; this.tabAIProofread.Name = "tabAIProofread"; @@ -74,6 +82,7 @@ namespace AIProofread // group1 // this.group1.Items.Add(this.BtnProofreadAll); + this.group1.Items.Add(this.BtnExportProofreadResult); this.group1.Items.Add(this.btnClear); this.group1.Items.Add(this.btnOpenLexicon); this.group1.Items.Add(this.btnSetting); @@ -89,16 +98,25 @@ namespace AIProofread // this.BtnProofreadAll.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge; this.BtnProofreadAll.Image = global::AIProofread.Properties.Resources.icon_proofread; - this.BtnProofreadAll.Label = "全文校对\n"; + this.BtnProofreadAll.Label = "全文校对\r\n"; this.BtnProofreadAll.Name = "BtnProofreadAll"; this.BtnProofreadAll.ShowImage = true; this.BtnProofreadAll.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.BtnProofreadAll_Click); // + // BtnExportProofreadResult + // + this.BtnExportProofreadResult.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge; + this.BtnExportProofreadResult.Image = global::AIProofread.Properties.Resources.icon_export; + this.BtnExportProofreadResult.Label = "导出勘误表\r\n"; + this.BtnExportProofreadResult.Name = "BtnExportProofreadResult"; + this.BtnExportProofreadResult.ShowImage = true; + this.BtnExportProofreadResult.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.BtnExportProofreadResult_Click); + // // btnClear // this.btnClear.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge; this.btnClear.Image = global::AIProofread.Properties.Resources.icon_clear; - this.btnClear.Label = "清除标注\n"; + this.btnClear.Label = "清除标注\r\n"; this.btnClear.Name = "btnClear"; this.btnClear.ShowImage = true; this.btnClear.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.btnClear_Click); @@ -107,7 +125,7 @@ namespace AIProofread // this.btnOpenLexicon.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge; this.btnOpenLexicon.Image = global::AIProofread.Properties.Resources.icon_book; - this.btnOpenLexicon.Label = "词库管理\n"; + this.btnOpenLexicon.Label = "词库管理\r\n"; this.btnOpenLexicon.Name = "btnOpenLexicon"; this.btnOpenLexicon.ShowImage = true; this.btnOpenLexicon.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.btnOpenLexicon_Click); @@ -116,7 +134,7 @@ namespace AIProofread // this.btnSetting.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge; this.btnSetting.Image = global::AIProofread.Properties.Resources.icon_setting; - this.btnSetting.Label = "插件设置\n"; + this.btnSetting.Label = "插件设置\r\n"; this.btnSetting.Name = "btnSetting"; this.btnSetting.ShowImage = true; this.btnSetting.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.btnSetting_Click); @@ -125,7 +143,7 @@ namespace AIProofread // this.BtnGetContact.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge; this.BtnGetContact.Image = global::AIProofread.Properties.Resources.icon_phone; - this.BtnGetContact.Label = "联系客服\n"; + this.BtnGetContact.Label = "联系客服\r\n"; this.BtnGetContact.Name = "BtnGetContact"; this.BtnGetContact.ShowImage = true; this.BtnGetContact.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.BtnGetContact_Click); @@ -134,7 +152,7 @@ namespace AIProofread // this.BtnUpdate.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge; this.BtnUpdate.Image = global::AIProofread.Properties.Resources.icon_update; - this.BtnUpdate.Label = "版本更新\n"; + this.BtnUpdate.Label = "版本更新\r\n"; this.BtnUpdate.Name = "BtnUpdate"; this.BtnUpdate.ShowImage = true; this.BtnUpdate.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.BtnUpdate_Click); @@ -143,7 +161,7 @@ namespace AIProofread // this.btnLogin.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge; this.btnLogin.Image = global::AIProofread.Properties.Resources.icon_user; - this.btnLogin.Label = "用户登录\n"; + this.btnLogin.Label = "用户登录\r\n"; this.btnLogin.Name = "btnLogin"; this.btnLogin.ShowImage = true; this.btnLogin.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.btnLogin_Click); @@ -152,7 +170,7 @@ namespace AIProofread // this.btnLogout.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge; this.btnLogout.Image = global::AIProofread.Properties.Resources.icon_logout; - this.btnLogout.Label = "退出登录\n"; + this.btnLogout.Label = "退出登录\r\n"; this.btnLogout.Name = "btnLogout"; this.btnLogout.ShowImage = true; this.btnLogout.Visible = false; @@ -180,17 +198,33 @@ namespace AIProofread // this.ButtonSaveCache.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge; this.ButtonSaveCache.Image = global::AIProofread.Properties.Resources.icon_save; - this.ButtonSaveCache.Label = "手动保存数据"; + this.ButtonSaveCache.Label = "暂存文件\r\n"; this.ButtonSaveCache.Name = "ButtonSaveCache"; this.ButtonSaveCache.ShowImage = true; + this.ButtonSaveCache.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.ButtonSaveCache_Click); // // ButtonLoadCache // this.ButtonLoadCache.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge; - this.ButtonLoadCache.Image = global::AIProofread.Properties.Resources.icon_refresh; - this.ButtonLoadCache.Label = "追踪历史数据"; + this.ButtonLoadCache.Image = global::AIProofread.Properties.Resources.icon_history; + this.ButtonLoadCache.Label = "加载文件\r\n"; this.ButtonLoadCache.Name = "ButtonLoadCache"; this.ButtonLoadCache.ShowImage = true; + this.ButtonLoadCache.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.ButtonLoadCache_Click); + // + // group2 + // + this.group2.Items.Add(this.BtnShowPanel); + this.group2.Name = "group2"; + // + // BtnShowPanel + // + this.BtnShowPanel.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge; + this.BtnShowPanel.Image = global::AIProofread.Properties.Resources.icon_panel; + this.BtnShowPanel.Label = "显示面板\r\n"; + this.BtnShowPanel.Name = "BtnShowPanel"; + this.BtnShowPanel.ShowImage = true; + this.BtnShowPanel.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.BtnShowPanel_Click); // // grpDebug // @@ -198,6 +232,9 @@ namespace AIProofread this.grpDebug.Items.Add(this.btnHidePane); this.grpDebug.Items.Add(this.BtnOpenLog); this.grpDebug.Items.Add(this.button1); + this.grpDebug.Items.Add(this.BtnOpenLogger); + this.grpDebug.Items.Add(this.BtnTest); + this.grpDebug.Items.Add(this.BtnOpenAppDir); this.grpDebug.Label = "开发调试"; this.grpDebug.Name = "grpDebug"; this.grpDebug.Visible = false; @@ -226,6 +263,24 @@ namespace AIProofread this.button1.Name = "button1"; this.button1.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.button1_Click); // + // BtnOpenLogger + // + this.BtnOpenLogger.Label = "打开日志窗口"; + this.BtnOpenLogger.Name = "BtnOpenLogger"; + this.BtnOpenLogger.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.BtnOpenLogger_Click); + // + // BtnTest + // + this.BtnTest.Label = "button2"; + this.BtnTest.Name = "BtnTest"; + this.BtnTest.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.BtnTest_Click); + // + // BtnOpenAppDir + // + this.BtnOpenAppDir.Label = "打开插件目录"; + this.BtnOpenAppDir.Name = "BtnOpenAppDir"; + this.BtnOpenAppDir.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.BtnOpenAppDir_Click); + // // Ribbon1 // this.Name = "Ribbon1"; @@ -238,6 +293,8 @@ namespace AIProofread this.group1.PerformLayout(); this.Group.ResumeLayout(false); this.Group.PerformLayout(); + this.group2.ResumeLayout(false); + this.group2.PerformLayout(); this.grpDebug.ResumeLayout(false); this.grpDebug.PerformLayout(); this.ResumeLayout(false); @@ -266,6 +323,12 @@ namespace AIProofread internal Microsoft.Office.Tools.Ribbon.RibbonGroup Group; internal Microsoft.Office.Tools.Ribbon.RibbonButton ButtonSaveCache; internal Microsoft.Office.Tools.Ribbon.RibbonButton ButtonLoadCache; + internal Microsoft.Office.Tools.Ribbon.RibbonButton BtnOpenLogger; + internal Microsoft.Office.Tools.Ribbon.RibbonButton BtnTest; + internal Microsoft.Office.Tools.Ribbon.RibbonButton BtnOpenAppDir; + internal Microsoft.Office.Tools.Ribbon.RibbonGroup group2; + internal Microsoft.Office.Tools.Ribbon.RibbonButton BtnShowPanel; + internal Microsoft.Office.Tools.Ribbon.RibbonButton BtnExportProofreadResult; } partial class ThisRibbonCollection diff --git a/AIProofread/Ribbon1.cs b/AIProofread/Ribbon1.cs index 89b958f..080af1b 100644 --- a/AIProofread/Ribbon1.cs +++ b/AIProofread/Ribbon1.cs @@ -15,12 +15,16 @@ using System.Linq; using System.Text; using AIProofread.core; using System.Windows.Forms; +using NPOI.XSSF.UserModel; +using NPOI.SS.UserModel; +using AIProofread.Model; namespace AIProofread { public partial class Ribbon1 { private bool IS_LOGIN = false; + private static bool IS_WPS = false; private void Ribbon1_Load(object sender, RibbonUIEventArgs e) { @@ -42,8 +46,12 @@ namespace AIProofread } } + /// + /// 初始化WPS相关功能(图标) + /// public void InitWPS() { + IS_WPS = true; BtnProofreadAll.Image = AIProofread.Properties.Resources.icon_proofread_wps; btnClear.Image = AIProofread.Properties.Resources.icon_clear_wps; btnOpenLexicon.Image = AIProofread.Properties.Resources.icon_book_wps; @@ -55,13 +63,18 @@ namespace AIProofread // 缓存相关 ButtonLoadCache.Image = AIProofread.Properties.Resources.icon_refresh_wps; ButtonSaveCache.Image = AIProofread.Properties.Resources.icon_save_wps; + // 显示面板 + BtnShowPanel.Image = AIProofread.Properties.Resources.icon_panel_wps; + // 导出校对结果 + BtnExportProofreadResult.Image = AIProofread.Properties.Resources.icon_export_wps; } public void ProcessLoginInfo(Userinfo userinfo) { if (userinfo == null) return; - + // 登录状态 IS_LOGIN = true; + // 切换登录状态 ToggleLogin(); LblNickname.Label = userinfo.nickname; LblDate.Label = userinfo.expiration; @@ -69,13 +82,24 @@ namespace AIProofread // 关闭所有登录窗口 foreach (var item in Globals.ThisAddIn.LoginFormList) { - if (!item.IsDisposed) + try { - item.Close(); + if (!item.IsDisposed) + { + item.Close(); + } + } + catch (Exception ex) + { + Logger.Log(this.Name, ex); } } + Globals.ThisAddIn.LoginFormList.Clear(); } + /// + /// 注销登录 + /// public void ProcessLogout() { IS_LOGIN = false; @@ -142,8 +166,8 @@ namespace AIProofread var result = MessageBox.Show("请确认是否清除此文档的所有校对标注?", "提示", MessageBoxButtons.OKCancel); if(result == DialogResult.OK) { - Bridge.bridge.clearAllProofreadMark(null); - Globals.ThisAddIn.SendMessageToWeb("clear-tips", null); + //Bridge.bridge.clearAllProofreadMark(null); + Globals.ThisAddIn.ClearAllProofreadMark(); } } @@ -409,5 +433,170 @@ namespace AIProofread { Bridge.StartUpgradeProcess(); } + + private void BtnOpenLogger_Click(object sender, RibbonControlEventArgs e) + { + // 判断日志窗口是否已经存在或者打开 + if (Logger.LoggerForm == null || Logger.LoggerForm.IsDisposed) + { + // 创建日志窗口 + Logger.LoggerForm = new FormLogger(); + } + Logger.LoggerForm.Show(); + } + + private void BtnTest_Click(object sender, RibbonControlEventArgs e) + { + // 获取当前系统时间戳 + int time = (int)(DateTime.Now.Ticks / 10000000); + BtnTest.Label = "测试按钮" + time; + } + + private void ButtonSaveCache_Click(object sender, RibbonControlEventArgs e) + { + Globals.ThisAddIn.SendMessageToWeb("save-cache", ""); + } + + private void ButtonLoadCache_Click(object sender, RibbonControlEventArgs e) + { + Globals.ThisAddIn.SendMessageToWeb("load-cache", ""); + } + + private void BtnShowPanel_Click(object sender, RibbonControlEventArgs e) + { + Globals.ThisAddIn.SendMessageToWeb("show-panel", ""); + } + + private void BtnOpenAppDir_Click(object sender, RibbonControlEventArgs e) + { + // 打开日志目录 + Process.Start(AppDomain.CurrentDomain.BaseDirectory); + } + + private ICellStyle CreateBaseCellStyle(IWorkbook workbook) + { + var style = workbook.CreateCellStyle(); + style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; + style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; + style.WrapText = true; + + return style; + } + private IFont CreateBaseFont(IWorkbook workbook) + { + // 宋体 11 + var font = workbook.CreateFont(); + font.FontName = "宋体"; + font.FontHeightInPoints = 11; + + return font; + } + + + private void BtnExportProofreadResult_Click(object sender, RibbonControlEventArgs e) + { + SaveFileDialog sfd = new SaveFileDialog(); + sfd.Filter = "Excel文件|*.xlsx"; + var result = sfd.ShowDialog(); + // 如果用户取消选择,则返回 + if(result == DialogResult.Cancel) + { + return; + } + using (var fs = File.OpenWrite(sfd.FileName)) + { + var book = new XSSFWorkbook(); + var sheet = book.CreateSheet("Sheet1"); + // 设置表格样式 + var style = CreateBaseCellStyle(book); + style.SetFont(CreateBaseFont(book)); + style.BorderBottom = NPOI.SS.UserModel.BorderStyle.None; + style.BorderTop = NPOI.SS.UserModel.BorderStyle.None; + style.BorderLeft = NPOI.SS.UserModel.BorderStyle.None; + style.BorderRight = NPOI.SS.UserModel.BorderStyle.None; + style.WrapText = true; + sheet.SetDefaultColumnStyle(0, style); + sheet.SetDefaultColumnStyle(1, style); + sheet.SetDefaultColumnStyle(2, style); + sheet.SetDefaultColumnStyle(3, style); + sheet.SetDefaultColumnStyle(4, style); + sheet.SetDefaultColumnStyle(5, style); + sheet.SetDefaultColumnStyle(6, style); + + + // 表头设置 + var row = sheet.CreateRow(0); + row.CreateCell(0).SetCellValue("序号"); + row.CreateCell(1).SetCellValue("页"); + row.CreateCell(2).SetCellValue("行"); + + var cell = row.CreateCell(3);// + // 设置宽度 + sheet.SetColumnWidth(3, 50 * 256); + cell.SetCellValue("详细信息"); + + var cellExp = row.CreateCell(4); + // 设置文字颜色为红色 + var expStyle = book.CreateCellStyle(); + var f1 = CreateBaseFont(book); + f1.Color = NPOI.HSSF.Util.HSSFColor.Red.Index; + expStyle.SetFont(f1); + cellExp.CellStyle = expStyle; + cellExp.SetCellValue("异常"); + + var suggestCell = row.CreateCell(5);// + suggestCell.CellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index; + suggestCell.SetCellValue("建议"); + + row.CreateCell(6).SetCellValue("处理状态"); + + var blackFont = CreateBaseFont(book); + blackFont.Color = NPOI.HSSF.Util.HSSFColor.Black.Index; + var redFont = CreateBaseFont(book); + redFont.Color = NPOI.HSSF.Util.HSSFColor.Red.Index; + + int id = 1; + foreach (var item in Globals.ThisAddIn.ActiveDocument.marks) + { + if(item.Value.mark == null) continue; + var it = item.Value.content; + var range = item.Value.mark.Range; + + // 获取书签在文档的页码数 + var pageNumber = range.get_Information(WdInformation.wdActiveEndPageNumber); + // 获取书签在当前页面的行数 + var lineNumber = range.get_Information(WdInformation.wdFirstCharacterLineNumber); + row = sheet.CreateRow(id); + row.CreateCell(0).SetCellValue(id); + row.CreateCell(1).SetCellValue(pageNumber); + row.CreateCell(2).SetCellValue(lineNumber); + + XSSFRichTextString originText = new XSSFRichTextString(item.Value.OriginSentence); + originText.ApplyFont(blackFont); + var startIndex = item.Value.OriginSentence.IndexOf(it.Origin); + // 对查找内容引用红色 + originText.ApplyFont(startIndex, startIndex + it.Origin.Length, redFont); + row.CreateCell(3).SetCellValue(originText); + + row.CreateCell(4).SetCellValue(it.Origin); + row.CreateCell(5).SetCellValue(it.Text); + row.CreateCell(6).SetCellValue(StatusText(it.IsAccept)); + id++; + } + + // 保存到文件 + book.Write(fs); + MessageBox.Show("导出成功"); + } + } + + private string StatusText(int status) + { + if(status == AcceptStatus.Accept) return "采纳"; + else if (status == AcceptStatus.Review) return "采纳"; + else if (status == AcceptStatus.Ignore) return "忽略"; + + return "未处理"; + } } } diff --git a/AIProofread/Ribbon1.resx b/AIProofread/Ribbon1.resx index 835e4e5..22c03e6 100644 --- a/AIProofread/Ribbon1.resx +++ b/AIProofread/Ribbon1.resx @@ -120,4 +120,19 @@ True + + True + + + True + + + True + + + True + + + True + \ No newline at end of file diff --git a/AIProofread/ThisAddIn.cs b/AIProofread/ThisAddIn.cs index 83b1f21..fcd6220 100644 --- a/AIProofread/ThisAddIn.cs +++ b/AIProofread/ThisAddIn.cs @@ -1,16 +1,16 @@ using System; -using System.Collections.Generic; using Newtonsoft.Json; using System.Threading; using Microsoft.Office.Interop.Word; -using System.Linq; using System.Windows.Forms; using System.IO; using AIProofread.Controls; using UtilLib; using AIProofread.Model; +using System.Collections.Generic; //using CustomTaskPane = Microsoft.Office.Core.CustomTaskPane; -using CustomTaskPane = Microsoft.Office.Tools.CustomTaskPane; +//using CustomTaskPane = Microsoft.Office.Tools.CustomTaskPane; +//using NPOI.SS.Formula.Functions; namespace AIProofread { @@ -38,34 +38,164 @@ namespace AIProofread /// 工具栏 /// public Ribbon1 ribbon; + /// + /// 当前word application + /// + public static Microsoft.Office.Interop.Word.Application CurrentWordApplication; + ///// + ///// 智能标记集合 + ///// + //internal SmartTagCollection VstoSmartTags; + + /// + /// 所有文档信息 + /// + public DocumentList documentList = new DocumentList(); + /// + /// 当前文档信息 + /// + public DocumentInfo ActiveDocument { get; set; } public bool IsWPS { get; set; } public List LoginFormList = new List(); - public Dictionary taskPanels = new Dictionary(); - public Dictionary panelsVisibleStatus = new Dictionary(); - public Dictionary documentIdDics = new Dictionary(); + //public override void BeginInit() + //{ + // base.BeginInit(); + // CurrentWordApplication = Application; + // CurrentWordApplication.DocumentChange += CurrentWordApplication_DocumentChange; + //} - /// - /// 当前文档面板 - /// - public CustomTaskPane currentDocumentTaskPane; - /// - /// 所有文档信息 - /// - public Dictionary documentList = new Dictionary(); - /// - /// 当前文档信息 - /// - public DocumentInfo CurrentDocument { get; set; } + private void ThisAddIn_Startup(object sender, System.EventArgs e) + { + try + { + AppInitialize(); + // 处理文档事件 + Application.DocumentOpen += Application_DocumentOpen; + Application.DocumentBeforeClose += Application_DocumentBeforeClose; - private static readonly Dictionary> allMarks = new Dictionary>(); + Application.WindowActivate += Application_WindowActivate; + //Application.WindowDeactivate += Application_WindowDeactivate; + Application.DocumentBeforeSave += Application_DocumentBeforeSave; ; + + (Application as ApplicationEvents4_Event).NewDocument += Application_NewDocument; + Application.DocumentChange += Application_DocumentChange; + // 选区发生变化事件 + this.Application.WindowSelectionChange += Application_WindowSelectionChange; + //try + //{ + // // 检测升级信息 + // Bridge.bridge.CheckPluginUpgrade(); + //}catch(Exception ex) + //{ + // Logger.Log("检测升级信息异常: " + ex.ToString()); + //} + } + catch (Exception ex1) + { + Logger.Log("Startup", ex1.ToString()); + } + } + + private void Application_DocumentBeforeSave(Document originDocument, ref bool SaveAsUI, ref bool Cancel) + { + Logger.Log("DocumentSave", originDocument.Name + "\r\n"); + if (CurrentWordApplication.Documents.Count == 0) + { + return; + } + + if (ActiveDocument == null) return; + // TODO 完成缓存保存 + + } + + //public DocumentInfo ActiveDocument()=> documentList.GetActiveDocument(); + + private void AppInitialize() + { + CurrentWordApplication = Application; + // 初始化配置 + InitAppByConfig(); + // 主线程 + FmainThreadContext = SynchronizationContext.Current; + + // 启动地址 + applicationStartupPath = System.Windows.Forms.Application.StartupPath; + // 判断是否是WPS + if (applicationStartupPath.Contains("WPS")) + { + Config.IS_WPS = true; + IsWPS = true; + + try + { + Globals.Ribbons.Ribbon1.InitWPS(); + } + catch (Exception ex) + { + Logger.Log("Init WPS Error " + ex.Message); + } + } + } + + private void InitAppByConfig() + { + try + { + if (File.Exists(Config.CONFIG_FILE)) + { + string content = File.ReadAllText(Config.CONFIG_FILE); + Logger.Log("INIT", "Found app.json " + content); + if (content == null || content.Length == 0) return; + AppConfig config = JsonConvert.DeserializeObject(content); + + // 插件网址 + if (!string.IsNullOrEmpty(config.AppUrl)) + { + Config.WEB_PATH = config.AppUrl; + } + // 运行环境 + if (!string.IsNullOrEmpty(config.Environment)) + { + Config.APP_ENV = config.Environment == "dev" ? AppEnvironment.Dev : ( + config.Environment == "test" ? AppEnvironment.Test : AppEnvironment.Prod + ); + } + Config.RUN_IN_DEBUG = config.AppRunInDebug; + if (Config.APP_ENV != AppEnvironment.Prod && this.ribbon != null) + { + this.ribbon.ShowDebug(); + } + } + } + catch (Exception) { } + } + + private void Application_DocumentChange() + { + // 检测是否存在打开的文档 + if (CurrentWordApplication.Documents.Count == 0) + { + return; + } + //var activeDocument = CurrentWordApplication.ActiveDocument; + + // 设置当前文档 + ActiveDocument = documentList.SetActiveDocument(CurrentWordApplication.ActiveDocument); + } + + public void SetActiveDocument(Document doc) + { + ActiveDocument = documentList.SetActiveDocument(doc); + } private void Application_WindowDeactivate(Document doc, Window Wn) { - Logger.Log("Application_WindowDeactivate -- " + doc.FullName + " visible:"); + //Logger.Log("Application_WindowDeactivate -- " + doc.FullName + " visible:"); //HidePanel(Doc); // 处理wps直接资源管理器新开文档面板闪烁问题 //if (IsWPS) { @@ -73,164 +203,77 @@ namespace AIProofread //} } + /// + /// 激活文档 + /// + /// + /// private void Application_WindowActivate(Document activeDoc, Window Wn) { - // 当前文档添加书签集合 - if (!allMarks.ContainsKey(activeDoc)) - { - allMarks[activeDoc] = new Dictionary(); - } - Logger.Log("Application_WindowActivate -- " + activeDoc.FullName); - //ShowPanel(Doc); - // 创建面板 - if (!taskPanels.ContainsKey(activeDoc)) - { - ShowPanel(activeDoc, false); - panelsVisibleStatus.Add(activeDoc, false); - } - // 设置当前面板为新创建的面板 - this.currentDocumentTaskPane = taskPanels[activeDoc]; - if (IsWPS) - { - HideOtherPanel(activeDoc); - } - if (panelsVisibleStatus.ContainsKey(activeDoc) && panelsVisibleStatus[activeDoc]) - { - taskPanels[activeDoc].Visible = true; - } + ActiveDocument = documentList.SetActiveDocument(activeDoc); + + //// 当前文档添加书签集合 + //if (!allMarks.ContainsKey(activeDoc)) + //{ + // allMarks[activeDoc] = new Dictionary(); + //} + //Logger.Log("Application_WindowActivate -- " + activeDoc.FullName); + ////ShowPanel(Doc); + //// 创建面板 + //if (!taskPanels.ContainsKey(activeDoc)) + //{ + // ShowPanel(activeDoc, false); + // panelsVisibleStatus.Add(activeDoc, false); + //} + //// 设置当前面板为新创建的面板 + //this.currentDocumentTaskPane = taskPanels[activeDoc]; + //if (IsWPS) + //{ + // HideOtherPanel(activeDoc); + //} + //if (panelsVisibleStatus.ContainsKey(activeDoc) && panelsVisibleStatus[activeDoc]) + //{ + // taskPanels[activeDoc].Visible = true; + //} } + /// + /// 关闭文档 + /// + /// + /// private void Application_DocumentBeforeClose(Document currentDoc, ref bool Cancel) { - Logger.Log("Application_DocumentBeforeClose -- " + currentDoc.FullName); - if (allMarks.ContainsKey(currentDoc)) - { - allMarks.Remove(currentDoc); - } + Logger.Log("DocumentBeforeClose", currentDoc.FullName); + //if (allMarks.ContainsKey(currentDoc)) + //{ + // allMarks.Remove(currentDoc); + //} - DisposePanel(currentDoc); + //DisposePanel(currentDoc); } - public void ActiveCurrentDocumentMarks(Document document) + //public void ActiveCurrentDocumentMarks(Document document) + //{ + // // 判断是否存在 没有的话初始化 + // var currentDoc = document ?? Application.ActiveDocument ; + // if (!allMarks.ContainsKey(currentDoc)) + // { + // allMarks[currentDoc] = new Dictionary(); + // } + // Bridge.marks = allMarks[currentDoc]; + //} + + private void Application_NewDocument(Document doc) { - // 判断是否存在 没有的话初始化 - var currentDoc = document ?? Application.ActiveDocument ; - if (!allMarks.ContainsKey(currentDoc)) - { - allMarks[currentDoc] = new Dictionary(); - } - Bridge.marks = allMarks[currentDoc]; + Logger.Log("NewDocument", doc.Name); } - private void Application_NewDocument(Document Doc) + private void Application_DocumentOpen(Document doc) { - Logger.Log("Application_NewDocument -- " + Doc.FullName); - ShowPanel(Doc); + Logger.Log("DocumentOpen", doc.Name); } - private void Application_DocumentOpen(Document Doc) - { - Logger.Log("Application_DocumentOpen -- " + Doc.FullName); - ShowPanel(Doc); - } - - void DisposePanel(Document doc) - { - if (panelsVisibleStatus.ContainsKey(doc)) - { - panelsVisibleStatus.Remove(doc); - } - if (taskPanels.ContainsKey(doc)) - { - var control = (ProofreadMainControl)taskPanels[doc].Control; - control.ResetWeb(); - taskPanels[doc].Visible = false; - taskPanels[doc].Dispose(); - taskPanels.Remove(doc); - } - } - - void HideOtherPanel(Document doc) - { - if (taskPanels.ContainsKey(doc) && taskPanels[doc].Visible) - { - return; - } - // 隐藏其他的文档 - foreach (var key in taskPanels.Keys) - { - // 记录面板原始状态 - if (key != doc) - { - taskPanels[key].Visible = false; - } - } - } - - void HidePanel(Document doc) - { - if (taskPanels.ContainsKey(doc)) - { - taskPanels[doc].Visible = false; - } - } - - private CustomTaskPane ShowPanel(Document doc, bool show) - { - - if (Application.ActiveDocument == null) return null; - if (doc == null) doc = Application.ActiveDocument; - - if (taskPanels.ContainsKey(doc)) - { - return taskPanels[doc]; - } - - //proofreadPanel = new ProofreadMainControl(); - var control = new ProofreadMainControl(doc, MinWidth); - if (MinWidth < 10) - { - MinWidth = 420 * control.LabelWidth() / 42; - } - var panel = Globals.ThisAddIn.CustomTaskPanes.Add(control, AddinName); - this.currentDocumentTaskPane = panel; - taskPanels.Add(doc, panel); - panel.Visible = false; - // 设置宽度 - control.Width = MinWidth; - panel.Width = MinWidth; - // 监听尺寸变化 防止最小尺寸小于设置值 - control.SizeChanged += Control_SizeChanged; - //new CustomTaskPaneHandler(control, MinWidth); - return panel; - } - - - - /// - /// word创建面板 - /// - private CustomTaskPane ShowPanel(Document doc) - { - return ShowPanel(doc, !IsWPS); - } - - - /// - /// 添加变量控制重复调用 - /// - private bool isResizing = false; - private void Control_SizeChanged(object sender, EventArgs e) - { - if (isResizing) return; - if (currentDocumentTaskPane != null && currentDocumentTaskPane.Visible && currentDocumentTaskPane.Width < MinWidth) - { - isResizing = true; - SendKeys.Send("{ESC}"); - currentDocumentTaskPane.Width = MinWidth; - isResizing = false; - } - } public int GetMinWidth() { @@ -252,97 +295,13 @@ namespace AIProofread // } //} - private void InitAppByConfig() - { - try - { - if (File.Exists(Config.CONFIG_FILE)) - { - string content = File.ReadAllText(Config.CONFIG_FILE); - Logger.Log("Found app.json " + content); - if (content == null || content.Length == 0) return; - AppConfig config = JsonConvert.DeserializeObject(content); - - // 插件网址 - if (!string.IsNullOrEmpty(config.AppUrl)) - { - Config.WEB_PATH = config.AppUrl; - } - // 运行环境 - if (!string.IsNullOrEmpty(config.Environment)) - { - Config.APP_ENV = config.Environment == "dev" ? AppEnvironment.Dev : ( - config.Environment == "test" ? AppEnvironment.Test : AppEnvironment.Prod - ); - } - if (Config.APP_ENV != AppEnvironment.Prod && this.ribbon != null) - { - this.ribbon.ShowDebug(); - } - } - } - catch (Exception) { } - } - - private void ThisAddIn_Startup(object sender, System.EventArgs e) - { - try - { - InitAppByConfig(); - FmainThreadContext = SynchronizationContext.Current; - // 启动地址 - applicationStartupPath = System.Windows.Forms.Application.StartupPath; - if (applicationStartupPath.Contains("WPS")) - { - IsWPS = true; - Config.IS_WPS = true; - try - { - Globals.Ribbons.Ribbon1.InitWPS(); - } - catch (Exception ex) - { - Logger.Log("Init WPS Error " + ex.Message); - } - } - // 处理文档事件 - Application.DocumentOpen += Application_DocumentOpen; - Application.DocumentBeforeClose += Application_DocumentBeforeClose; - Application.WindowActivate += Application_WindowActivate; - Application.WindowDeactivate += Application_WindowDeactivate; - (Application as ApplicationEvents4_Event).NewDocument += Application_NewDocument; - //Application.DocumentChange += - // 选区发生变化事件 - this.Application.WindowSelectionChange += Application_WindowSelectionChange; - // 检测升级信息 - Bridge.bridge.InitPluginUpgrade(); - - try - { - if (Application.Documents.Count > 0 && Application.ActiveDocument != null) - { - // 默认直接打开文档 就直接创建panel - ShowPanel(Application.ActiveDocument, false); - } - } - catch (Exception ex2) - { - Logger.Log("加载默认文档失败: " + ex2.ToString()); - } - } - catch (Exception ex1) - { - Logger.Log("Init Error " + ex1.ToString()); - } - } - private void Application_WindowSelectionChange(Selection s) { if (s.Bookmarks != null) { if (s.Range.Start == s.Range.End) // 说明是点击呀 { - var count = s.Bookmarks.Count; + //var count = s.Bookmarks.Count; if (s.Bookmarks.Count >= 1) // 只有这一个 { foreach (Bookmark item in s.Bookmarks) @@ -352,13 +311,14 @@ namespace AIProofread { // 只选择第一个书签 // TODO: 优化 + Bridge.bridge.SelectMarkById(proofreadId, 0); return; } } } } } - Bridge.bridge.SelectMarkById(-1,0); + //Bridge.bridge.SelectMarkById(-1, 0); } public int MyProperty { get; set; } @@ -366,46 +326,21 @@ namespace AIProofread public void SendMessageToWeb(string msg, object data) { // 先显示panel - var panel = this.ShowPanel(Application.ActiveDocument, true); - SendMessageToWeb(panel.Control, msg, data); - } - - public void SendMessageToWeb(UserControl panelControl, string msg, object data) - { - var json = JsonConvert.SerializeObject(new WebMessage(msg, data)); - var control = (ProofreadMainControl)panelControl; - try - { - if (control.web.CoreWebView2 == null) - { - Thread.Sleep(500); - } - control.web.CoreWebView2.PostWebMessageAsJson(json); - } - catch (Exception ex) - { - Logger.Log("send message to web error \n" + ex.Message + "\n" + msg + data.ToString()); - } + //var panel = this.ShowPanel(Application.ActiveDocument, true); + //SendMessageToWeb(panel.Control, msg, data); + ActiveDocument?.SendMessageToWeb(msg, data); } // 显示面板 public void ShowPanel() { - this.currentDocumentTaskPane.Visible = true; - if (panelsVisibleStatus.ContainsKey(Application.ActiveDocument)) - { - panelsVisibleStatus[Application.ActiveDocument] = true; - } + ActiveDocument?.ShowPane(); } // 隐藏面板 public void HidePanel() { - this.currentDocumentTaskPane.Visible = false; - if (panelsVisibleStatus.ContainsKey(Application.ActiveDocument)) - { - panelsVisibleStatus[Application.ActiveDocument] = false; - } + ActiveDocument?.HidePane(); } /// @@ -413,12 +348,13 @@ namespace AIProofread /// public void HideAllPanel() { - foreach (var item in taskPanels) - { - item.Value.Visible = false; - } + this.documentList.HideAllPane(); } + /// + /// 显示登录窗口 + /// + /// public void ShowLoginForm(string action) { FormLogin frm = new FormLogin(action); @@ -427,30 +363,85 @@ namespace AIProofread frm.Show(); } - void ClearPanels() - { - taskPanels.Values.ToList().ForEach(p => - { - try - { - p.Dispose(); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message + "\n" + ex.StackTrace); - Logger.Log(ex.Message + "\n" + ex.StackTrace); - } - }); - taskPanels.Clear(); - } + /// + /// 清理所有面板 + /// + //void ClearPanels() + //{ + // taskPanels.Values.ToList().ForEach(p => + // { + // try + // { + // p.Dispose(); + // } + // catch (Exception ex) + // { + // Console.WriteLine(ex.Message + "\n" + ex.StackTrace); + // Logger.Log(ex.Message + "\n" + ex.StackTrace); + // } + // }); + // taskPanels.Clear(); + //} private void ThisAddIn_Shutdown(object sender, System.EventArgs e) { // PanelModule.DisposeCTP(); //this.proofreadPanel.Dispose(); - ClearPanels(); + Logger.Log("shutdown"); + documentList.Clear(); } + public void SyncLogout() + { + ribbon.ProcessLogout(); + //taskPanels.Values.ToList().ForEach(p => + //{ + // try + // { + // // 同步登录失败信息 + // SendMessageToWeb(p.Control, "async-logout", null); + // } + // catch (Exception ex) + // { + // Logger.Log("async-logout:", ex); + // } + //}); + + } + + public void SetDocumentId(Document document, int id) + { + var doc = documentList.Get(document); + if (doc != null) doc.Id = id; + } + + public DocumentInfo GetDocumentById(int id) + { + return documentList.GetById(id); + } + + + /// + /// 清除所有标记 + /// + public void ClearAllProofreadMark() + { + ActiveDocument?.ClearAllProofreadMark(); + Globals.ThisAddIn.SendMessageToWeb("clear-tips", null); + } + + + //public string LoadCacheByPath() + //{ + + //} + + //public void SaveCache(string cache) + //{ + + //} + + #region VSTO generated code /// @@ -463,22 +454,9 @@ namespace AIProofread this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); } - public void SyncLogout() + public void InitProofreadCacheList(System.Collections.Generic.List list) { - ribbon.ProcessLogout(); - taskPanels.Values.ToList().ForEach(p => - { - try - { - // 同步登录失败信息 - SendMessageToWeb(p.Control, "async-logout", null); - } - catch (Exception ex) - { - Logger.Log("async-logout:", ex); - } - }); - + ActiveDocument?.InitProofreadCache(list); } #endregion diff --git a/AIProofread/core/DocumentUtil.cs b/AIProofread/core/DocumentUtil.cs index 9921238..79f76ff 100644 --- a/AIProofread/core/DocumentUtil.cs +++ b/AIProofread/core/DocumentUtil.cs @@ -173,7 +173,7 @@ namespace AIProofread /// /// /// - public static Range FindRange(CorrectItem correct, CorrectContext sentense,ref int prevOffset, Microsoft.Office.Interop.Word.Document document, Range range) + public static Range FindRange(CorrectItem correct, CorrectContext sentense, ref int prevOffset, Microsoft.Office.Interop.Word.Document document, Range range) { var paragraphText = range.Text; @@ -194,7 +194,7 @@ namespace AIProofread End = range.Start + offset + wordEnd; Start = range.Start + offset + wordStart; // 直接找到 - var findRange = activeDocument.Range(ref Start,ref End); + var findRange = activeDocument.Range(ref Start, ref End); // 判断对应选区是否是要找的文本 if (findRange.Text == findText) { @@ -291,7 +291,37 @@ namespace AIProofread } + public static Bookmark FindBookMarkByCorrect(CorrectItem correct) + { + var document = Globals.ThisAddIn.ActiveDocument.CurrentDocument; + var marks = document.Bookmarks; + var markName = Config.BuildBookmarkName(correct.Id); + if (!document.Bookmarks.Exists(markName)) return null; + + ControlCollection controls = Globals.Factory.GetVstoObject(document).Controls; + controls.Remove(markName); + //return controls[markName] as Bookmark; + var bookmark = marks[markName]; + var start = bookmark.Range.Start; + var end = bookmark.Range.End; + return controls.AddBookmark(document.Range(start, end), markName); + + //if(bookmark == null) + //{ + // foreach (var m in marks) + // { + // var mark = m as Bookmark; + // var name = mark.Name; + // var tag = mark.Tag?.ToString(); + // if(tag == markName || name == markName) + // { + // return mark; + // } + // } + //} + //return bookmark as Bookmark; + } public static Bookmark FindRangeAndCreateBookmark(CorrectItem correct, CorrectContext sentense, Microsoft.Office.Interop.Word.Document document, ref int prevOffset) { @@ -321,6 +351,7 @@ namespace AIProofread // 更新查找的结束位置 //prevOffset = findRange.End - paragraphStart; bookmark = controls.AddBookmark(findRange, markName); + bookmark.Tag = "ai_proofread"; } } @@ -338,10 +369,15 @@ namespace AIProofread var paraStart = paraRange.Start; // 定位句子的其实位置 - var offset = paraStart + c.SentenceOffset; - //var cutLength = Math.Min(c.InsertLen, paraText.Length - offset); - var sentence = paraText.Substring(c.SentenceOffset, c.InsertLength); - if (sentence == c.Insert) + //var offset = paraStart + c.SentenceOffset; + ////var cutLength = Math.Min(c.InsertLen, paraText.Length - offset); + /// TODO 目前接口没有返回 句子相关数据 直接获取 + var sentence = paraRange.Sentences[c.SentenceNumber]; //paraText.Substring(c.SentenceOffset, c.InsertLength); + c.SentenceOffset = sentence.Start; + var offset = c.SentenceOffset; + c.Insert = sentence.Text; + + if (sentence.Text == c.Insert) { // 比对原始内容与校对原文是否一致 var range = document.Range(offset + item.Start, offset + item.End); // diff --git a/AIProofread/core/MainPanelWebMessage.cs b/AIProofread/core/MainPanelWebMessage.cs index f9b94f4..f1b13ed 100644 --- a/AIProofread/core/MainPanelWebMessage.cs +++ b/AIProofread/core/MainPanelWebMessage.cs @@ -80,8 +80,14 @@ namespace AIProofread.core } public static void DisabledProofreadItem(List proofreadItemIdList) { + if (proofreadItemIdList.Count == 0) return; Globals.ThisAddIn.SendMessageToWeb(MessageActionEnum.DisableProofreadItem.Action, proofreadItemIdList); } + public static void DisabledProofreadItem(int proofreadItemId) + { + DisabledProofreadItem(new List() { proofreadItemId }); + } + } } diff --git a/AIProofread/core/PanelModule.cs b/AIProofread/core/PanelModule.cs index 9eed0ae..cd3fac5 100644 --- a/AIProofread/core/PanelModule.cs +++ b/AIProofread/core/PanelModule.cs @@ -17,7 +17,7 @@ namespace AIProofread { if (ctp == null) { - uc = new ProofreadMainControl(null,450); + uc = new ProofreadMainControl(); ctp = Globals.ThisAddIn.CustomTaskPanes.Add(control: uc, title: "AI校对王"); ctp.DockPosition = Office.MsoCTPDockPosition.msoCTPDockPositionRight; } diff --git a/AIProofread/obj/Debug/AIProofread.Properties.Resources.resources b/AIProofread/obj/Debug/AIProofread.Properties.Resources.resources index 54aeefa..14b30c5 100644 Binary files a/AIProofread/obj/Debug/AIProofread.Properties.Resources.resources and b/AIProofread/obj/Debug/AIProofread.Properties.Resources.resources differ diff --git a/AIProofread/obj/Debug/AIProofread.csproj.AssemblyReference.cache b/AIProofread/obj/Debug/AIProofread.csproj.AssemblyReference.cache index 9106360..83a0140 100644 Binary files a/AIProofread/obj/Debug/AIProofread.csproj.AssemblyReference.cache and b/AIProofread/obj/Debug/AIProofread.csproj.AssemblyReference.cache differ diff --git a/AIProofread/obj/Debug/AIProofread.csproj.CoreCompileInputs.cache b/AIProofread/obj/Debug/AIProofread.csproj.CoreCompileInputs.cache index 2d2ab87..76f943d 100644 --- a/AIProofread/obj/Debug/AIProofread.csproj.CoreCompileInputs.cache +++ b/AIProofread/obj/Debug/AIProofread.csproj.CoreCompileInputs.cache @@ -1 +1 @@ -11c03afee37eea7e40c8b52f8e997c1261df45d7ed4e6445471b049c699b20a7 +e41eeef295075b0004214c8cd1d281efa264dd90d94486af5e0e1e63e30e1f99 diff --git a/AIProofread/obj/Debug/AIProofread.csproj.FileListAbsolute.txt b/AIProofread/obj/Debug/AIProofread.csproj.FileListAbsolute.txt index f2c0d2a..6960bd4 100644 --- a/AIProofread/obj/Debug/AIProofread.csproj.FileListAbsolute.txt +++ b/AIProofread/obj/Debug/AIProofread.csproj.FileListAbsolute.txt @@ -206,3 +206,7 @@ C:\Users\yaclt\source\repos\repos\AIProofread\AIProofread\obj\Debug\AIProofread. C:\Users\yaclt\source\repos\repos\AIProofread\AIProofread\obj\Debug\AIProofr.8811D769.Up2Date C:\Users\yaclt\source\repos\repos\AIProofread\AIProofread\obj\Debug\AIProofread.dll C:\Users\yaclt\source\repos\repos\AIProofread\AIProofread\obj\Debug\AIProofread.pdb +C:\Users\yaclt\source\repos\repos\AIProofread\AIProofread\obj\Debug\AIProofread.Controls.FormLogger.resources +C:\Users\yaclt\source\repos\repos\AIProofread\AIProofread\obj\Debug\AIProofread.Controls.FormMessage.resources +C:\Users\yaclt\source\repos\repos\AIProofread\AIProofread\obj\Debug\AIProofread.Controls.FormDialog.resources +C:\Users\yaclt\source\repos\repos\AIProofread\AIProofread\obj\Debug\AIProofread.Controls.FormWebView.resources diff --git a/AIProofread/obj/Debug/AIProofread.csproj.GenerateResource.cache b/AIProofread/obj/Debug/AIProofread.csproj.GenerateResource.cache index 9485d9f..cb8a110 100644 Binary files a/AIProofread/obj/Debug/AIProofread.csproj.GenerateResource.cache and b/AIProofread/obj/Debug/AIProofread.csproj.GenerateResource.cache differ diff --git a/AIProofread/obj/Debug/AIProofread.dll b/AIProofread/obj/Debug/AIProofread.dll index 2f4dd5d..7343d1a 100644 Binary files a/AIProofread/obj/Debug/AIProofread.dll and b/AIProofread/obj/Debug/AIProofread.dll differ diff --git a/AIProofread/obj/Debug/AIProofread.pdb b/AIProofread/obj/Debug/AIProofread.pdb index 7762ca7..684a6b0 100644 Binary files a/AIProofread/obj/Debug/AIProofread.pdb and b/AIProofread/obj/Debug/AIProofread.pdb differ diff --git a/AIProofread/obj/Debug/DesignTimeResolveAssemblyReferences.cache b/AIProofread/obj/Debug/DesignTimeResolveAssemblyReferences.cache index 7a6d1a9..c142275 100644 Binary files a/AIProofread/obj/Debug/DesignTimeResolveAssemblyReferences.cache and b/AIProofread/obj/Debug/DesignTimeResolveAssemblyReferences.cache differ diff --git a/AIProofread/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache b/AIProofread/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache index 3799ebb..6024533 100644 Binary files a/AIProofread/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache and b/AIProofread/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache differ diff --git a/AIProofread/obj/Debug/TempPE/Properties.Resources.Designer.cs.dll b/AIProofread/obj/Debug/TempPE/Properties.Resources.Designer.cs.dll index 4ab298f..e5c3ef7 100644 Binary files a/AIProofread/obj/Debug/TempPE/Properties.Resources.Designer.cs.dll and b/AIProofread/obj/Debug/TempPE/Properties.Resources.Designer.cs.dll differ diff --git a/ai-proofread-client/App.config b/ai-proofread-client/App.config new file mode 100644 index 0000000..b50c74f --- /dev/null +++ b/ai-proofread-client/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/ai-proofread-client/Form1.Designer.cs b/ai-proofread-client/Form1.Designer.cs new file mode 100644 index 0000000..a514ff9 --- /dev/null +++ b/ai-proofread-client/Form1.Designer.cs @@ -0,0 +1,40 @@ +namespace ai_proofread_client +{ + partial class Form1 + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows 窗体设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Text = "Form1"; + } + + #endregion + } +} + diff --git a/ai-proofread-client/Form1.cs b/ai-proofread-client/Form1.cs new file mode 100644 index 0000000..1def5a7 --- /dev/null +++ b/ai-proofread-client/Form1.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ai_proofread_client +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} diff --git a/ai-proofread-client/Program.cs b/ai-proofread-client/Program.cs new file mode 100644 index 0000000..7ea293e --- /dev/null +++ b/ai-proofread-client/Program.cs @@ -0,0 +1,34 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Windows.Forms; + +namespace ai_proofread_client +{ + internal static class Program + { + [DllImport("kernel32.dll")] + public static extern bool AllocConsole(); + [DllImport("kernel32.dll")] + static extern bool FreeConsole(); + + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main(string[] args) + { + // 允许调用控制台输出 + AllocConsole(); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + //Application.Run(new Form1()); + Console.WriteLine("xxx-->0"); + Debug.WriteLine("xxx-->1"); + Console.WriteLine(string.Join("\n",args)); + Console.ReadLine(); + // 释放 + FreeConsole(); + } + } +} diff --git a/ai-proofread-client/Properties/AssemblyInfo.cs b/ai-proofread-client/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8682ba1 --- /dev/null +++ b/ai-proofread-client/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("ai-proofread-client")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ai-proofread-client")] +[assembly: AssemblyCopyright("Copyright © 2024")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("48c0b207-150a-40b7-9a25-ecf9218ff86f")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ai-proofread-client/Properties/Resources.Designer.cs b/ai-proofread-client/Properties/Resources.Designer.cs new file mode 100644 index 0000000..ffdf73f --- /dev/null +++ b/ai-proofread-client/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + +namespace ai_proofread_client.Properties +{ + + + /// + /// 强类型资源类,用于查找本地化字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// 返回此类使用的缓存 ResourceManager 实例。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ai_proofread_client.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/ai-proofread-client/Properties/Resources.resx b/ai-proofread-client/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/ai-proofread-client/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ai-proofread-client/Properties/Settings.Designer.cs b/ai-proofread-client/Properties/Settings.Designer.cs new file mode 100644 index 0000000..d1a0672 --- /dev/null +++ b/ai-proofread-client/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ai_proofread_client.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/ai-proofread-client/Properties/Settings.settings b/ai-proofread-client/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/ai-proofread-client/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/ai-proofread-client/ai-proofread-client.csproj b/ai-proofread-client/ai-proofread-client.csproj new file mode 100644 index 0000000..4e60f96 --- /dev/null +++ b/ai-proofread-client/ai-proofread-client.csproj @@ -0,0 +1,80 @@ + + + + + Debug + AnyCPU + {48C0B207-150A-40B7-9A25-ECF9218FF86F} + WinExe + ai_proofread_client + ai-proofread-client + v4.6.2 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Form + + + Form1.cs + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + \ No newline at end of file diff --git a/util-lib/CorrectContext.cs b/util-lib/CorrectContext.cs index 899eb4e..ea12946 100644 --- a/util-lib/CorrectContext.cs +++ b/util-lib/CorrectContext.cs @@ -16,14 +16,21 @@ namespace UtilLib /// [JsonProperty("new_text")] public string NewText { get; set; } - + /// /// 句子原始文本长度 /// - [JsonProperty("insert_len")] - public int InsertLength { get; set; } + //[JsonProperty("insert_len")] + //public int InsertLength { get; set; } + + /// + /// 校对位移(相对当前句子) + /// + [JsonProperty("start_num")] public int Offset { get; set; } - public int Paragraph_offset { get; set; } + + //public int Paragraph_offset { get; set; } + /// /// 句子所在文档的段落数(从1开始) /// @@ -31,13 +38,21 @@ namespace UtilLib public int ParagraphNumber { get; set; } /// - /// 句子在段落中的其实位置 + /// 句子在段落中的起始位置 /// [JsonProperty("sentence_offset")] public int SentenceOffset { get; set; } + + /// + /// 当前句子在段落的序号 + /// + [JsonProperty("sentence_num")] + public int SentenceNumber { get; set; } + /// /// 当前句子的校对列表项 /// + [JsonProperty("diffs")] public List CorrectItems { get; set; } } } diff --git a/util-lib/CorrectItem.cs b/util-lib/CorrectItem.cs index a1c1c52..c361f84 100644 --- a/util-lib/CorrectItem.cs +++ b/util-lib/CorrectItem.cs @@ -5,7 +5,7 @@ namespace UtilLib public class CorrectItem { /// - /// 校对类别() + /// 校对类别(r 替换 d 删除 i 插入新增) /// public string Tag { get; set; } /// @@ -29,13 +29,13 @@ namespace UtilLib /// public int Id { get; set; } /// - /// 校对项索引 + /// 标识类型index(字符型数字) /// - public int idx { get; set; } + public int Index { get; set; } /// - /// 校对所属分类 + /// 标识类型(校对所属分类) /// - public int Type { get; set; } + public string Type { get; set; } /// /// 校对状态 /// @@ -45,5 +45,9 @@ namespace UtilLib /// 校对项颜色 /// public string Color { get; set; } + /// + /// 标识类型(校对所属分类) + /// + public string Addition { get; set; } } }