callmeyan d2e960243c 优化多文档校对性能;
修复多文档同时校对时有几率数据错乱的问题;
2024-08-24 12:20:47 +08:00

475 lines
15 KiB
C#

using System;
using System.Collections.Generic;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Tools.Word;
using AIProofread.Controls;
using Microsoft.Office.Tools;
using Newtonsoft.Json;
using UtilLib;
using System.Threading;
using Microsoft.Office.Interop.Word;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace AIProofread
{
public partial class ThisAddIn
{
public static SynchronizationContext FmainThreadContext;
public string AddinName = " ";
/// <summary>
/// 最小宽度
/// </summary>
public static int MinWidth = 0;
/// <summary>
/// 启动路径
/// </summary>
public string applicationStartupPath;
/// <summary>
/// 校对面板
/// </summary>
public ProofreadMainControl proofreadPanel;
/// <summary>
/// 工具栏
/// </summary>
public Ribbon1 ribbon;
public bool IsWPS { get; set; }
public List<FormLogin> LoginFormList = new List<FormLogin>();
public Dictionary<Word.Document, CustomTaskPane> taskPanels = new Dictionary<Word.Document, CustomTaskPane>();
public Dictionary<Word.Document, bool> panelsVisibleStatus = new Dictionary<Word.Document, bool>();
public Dictionary<Word.Document, int> documentIdDics = new Dictionary<Word.Document, int>();
public CustomTaskPane currentDocumentTaskPane;
private static readonly Dictionary<Word.Document, Dictionary<int, ProofreadItem>> allMarks = new Dictionary<Word.Document, Dictionary<int, ProofreadItem>>();
private void Application_WindowDeactivate(Word.Document doc, Window Wn)
{
Logger.Log("Application_WindowDeactivate -- " + doc.FullName + " visible:");
//HidePanel(Doc);
// 处理wps直接资源管理器新开文档面板闪烁问题
//if (IsWPS) {
// this.currentDocumentTaskPane.Visible = false;
//}
}
private void Application_WindowActivate(Word.Document activeDoc, Window Wn)
{
// 当前文档添加书签集合
if (!allMarks.ContainsKey(activeDoc))
{
allMarks[activeDoc] = new Dictionary<int, ProofreadItem>();
}
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(Word.Document currentDoc, ref bool Cancel)
{
Logger.Log("Application_DocumentBeforeClose -- " + currentDoc.FullName);
if (allMarks.ContainsKey(currentDoc))
{
allMarks.Remove(currentDoc);
}
DisposePanel(currentDoc);
}
public void ActiveCurrentDocumentMarks(Word.Document document)
{
// 判断是否存在 没有的话初始化
var currentDoc = document ?? Application.ActiveDocument ;
if (!allMarks.ContainsKey(currentDoc))
{
allMarks[currentDoc] = new Dictionary<int, ProofreadItem>();
}
Bridge.marks = allMarks[currentDoc];
}
private void Application_NewDocument(Word.Document Doc)
{
Logger.Log("Application_NewDocument -- " + Doc.FullName);
ShowPanel(Doc);
}
private void Application_DocumentOpen(Word.Document Doc)
{
Logger.Log("Application_DocumentOpen -- " + Doc.FullName);
ShowPanel(Doc);
}
void DisposePanel(Word.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(Word.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(Word.Document doc)
{
if (taskPanels.ContainsKey(doc))
{
taskPanels[doc].Visible = false;
}
}
private CustomTaskPane ShowPanel(Word.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;
}
/// <summary>
/// word创建面板
/// </summary>
private CustomTaskPane ShowPanel(Word.Document doc)
{
return ShowPanel(doc, !IsWPS);
}
/// <summary>
/// 添加变量控制重复调用
/// </summary>
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()
{
return MinWidth;
}
public void Send(SendOrPostCallback d)
{
FmainThreadContext.Send(d, null);
}
//private void ProofreadPanel_SizeChanged(object sender, EventArgs e)
//{
// // 处理最小宽度
// if (customTaskPane != null && customTaskPane.Width < MinWidth && customTaskPane.Visible)
// {
// SendKeys.Send("{ESC}");
// customTaskPane.Width = MinWidth;
// }
//}
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<AppConfig>(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;
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(Word.Selection s)
{
if (s.Bookmarks != null)
{
if (s.Range.Start == s.Range.End) // 说明是点击呀
{
var count = s.Bookmarks.Count;
if (s.Bookmarks.Count >= 1) // 只有这一个
{
foreach (Microsoft.Office.Interop.Word.Bookmark item in s.Bookmarks)
{
int proofreadId = Config.GetBookmarkIdByName(item.Name);
if (proofreadId > 0)
{
Bridge.bridge.SelectMarkById(proofreadId,0);
return;
}
}
}
}
}
Bridge.bridge.SelectMarkById(-1,0);
}
public int MyProperty { get; set; }
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());
}
}
// 显示面板
public void ShowPanel()
{
this.currentDocumentTaskPane.Visible = true;
if (panelsVisibleStatus.ContainsKey(Application.ActiveDocument))
{
panelsVisibleStatus[Application.ActiveDocument] = true;
}
}
// 隐藏面板
public void HidePanel()
{
this.currentDocumentTaskPane.Visible = false;
if (panelsVisibleStatus.ContainsKey(Application.ActiveDocument))
{
panelsVisibleStatus[Application.ActiveDocument] = false;
}
}
/// <summary>
/// 隐藏所有面板
/// </summary>
public void HideAllPanel()
{
foreach (var item in taskPanels)
{
item.Value.Visible = false;
}
}
public void ShowLoginForm(string action)
{
FormLogin frm = new FormLogin(action);
LoginFormList.Add(frm);
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();
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
// PanelModule.DisposeCTP();
//this.proofreadPanel.Dispose();
ClearPanels();
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
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);
}
});
}
#endregion
}
}