using connor_zwcadm.model; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using ZWCAD; using ZwmToolKitLib; using ZwSoft.ZwCAD.ApplicationServices; using ZwSoft.ZwCAD.DatabaseServices; namespace connor_zwcadm.util { public class KCADUtil { public const string CADPROP_BLOCKNAME = "#BLOCK_TITLE_NAME#"; public ZwmDb Database { get; } public TCUtil TCUtil { get; } public string File_Path { get; } private readonly Dictionary> configMap = new Dictionary>(); public KCADUtil(string file_path) { File_Path = file_path; if (!File.Exists(file_path)) { throw new Exception("文件不存在:" + file_path); } ZcadApplication zcadApp = Application.ZcadApplication as ZcadApplication; //ZcadApplication zcadApp = new ZcadApplication(); if (zcadApp == null) { throw new Exception("初始 ZcadApplication 化失败"); } ZWCAD.ZcadApplication m_cadApp; ZwmToolKitLib.ZwmApp m_objZwmApp; ZwmToolKitLib.ZwmDb m_objZwmDb; try { //取得一个正在运行的ZWCAD实例 m_cadApp = (ZWCAD.ZcadApplication)Marshal.GetActiveObject("ZWCAD.Application.2018"); KUtil.Log("ZWCAD.Application.2018"); }//end of try catch { try { KUtil.Log("try"); //建立一个新的AUTOCAD实例,并标识已经建立成功。 // m_cadApp = new AutoCAD.AcadApplication(); m_cadApp = new ZWCAD.ZcadApplication(); m_cadApp.Visible = true; } catch { throw new Exception("无法起动CAD应用程序,确认已经安装"); } }//end of catch KUtil.Log("Application2: " + m_cadApp); m_objZwmApp = m_cadApp.GetInterfaceObject("ZwmToolKit.ZwmApp"); KUtil.Log("Application3: " + Application.ZcadApplication); m_objZwmApp.GetDb(out m_objZwmDb); Database = m_objZwmDb;//zcadApp.GetInterfaceObject("ZwmToolKit.ZwmDb"); if (Database == null) { throw new Exception("打开ZwmDb失败"); } Database.Close(); KUtil.Log("打开Database: " + file_path); Database.OpenFile(file_path); } public void CloseDatabse() { if (Database != null) { KUtil.Log("关闭Database"); Database.Close(); KUtil.Log("关闭Database完成"); } } public List GetSaveConfig(string titleName, TCUtil tcUtil) { if (configMap.ContainsKey(titleName)) { return configMap[titleName]; } string prefName = KMain.PREF_PROP_CONFIG_PREFIX + titleName; string[] prefVals = tcUtil.GetPrefValues(prefName); KUtil.Log("读取同步配置:" + prefName); int len = prefVals == null ? 0 : prefVals.Length; List res = new List(); for (int i = 0; i < len; i++) { string config = prefVals[i]; int ind = config.IndexOf('='); if (ind <= 0) { continue; } // KUtil.Log(">> "+config); string tcConfig = config.Substring(0, ind); string cadConfig = config.Substring(ind + 1); PropertyInfo info = PropertyInfo.parse(cadConfig, tcConfig); if (info == null) { KUtil.Log("无效配置: " + config); continue; } res.Add(info); } KUtil.Log(string.Join(", ", res)); if (res.Count == 0) { res = null; } configMap.Add(titleName, res); return res; } public List> ReadBom() { Bom bom = null; Database.GetBom(ref bom); if (bom == null) { throw new Exception("加载明细栏数据失败"); } string strLabel = ""; string strName = ""; string strValue = ""; BomRow m_objBomRow = null; int nColCount = 0; int existRowCnt = 0; bom.GetItemCount(ref existRowCnt); KUtil.Log("读取明细栏属性,行数量:" + existRowCnt); List> bomProperties = new List>(); for (int i = 0; i < existRowCnt; i++) { bom.GetItem(i, ref m_objBomRow); Dictionary bomProps = new Dictionary(); m_objBomRow.GetItemCount(ref nColCount); for (int nCol = 1; nCol < nColCount; nCol++) { m_objBomRow.GetItem(nCol, ref strLabel, ref strName, ref strValue); KUtil.Put(bomProps, strLabel, strValue); } if (bomProps.Count > 0) { KUtil.Log(KUtil.PrintDictionary(bomProps)); bomProperties.Add(bomProps); } } return bomProperties; } public string WriteBomLine(Dictionary> bomlineMap) { if (bomlineMap == null || bomlineMap.Count == 0) { return ""; } string strLabel = ""; string strName = ""; string strValue = ""; int nColCount = 0; int existRowCnt = 0; Bom bom = null; Database.GetBom(ref bom); if (bom == null) { throw new Exception("加载明细栏数据失败"); } bom.GetItemCount(ref existRowCnt); KUtil.Log("图纸BOM行数量:" + existRowCnt); List updatedRows = new List(); StringBuilder errSB = new StringBuilder(); for (int i = 0; i < existRowCnt; i++) { if (!bomlineMap.ContainsKey(i)) { continue; } BomRow bomRow = null; bom.GetItem(i, ref bomRow); bomRow.GetItemCount(ref nColCount); KUtil.Log("更新第 " + (i + 1) + " 行"); Dictionary bomProps = bomlineMap[i]; if (bomProps == null) { if (!("".Equals(errSB.ToString().Trim()))) { errSB.Append(";"); errSB.Append((i + 1)); } else { errSB.Append((i + 1)); } continue; } for (int nCol = 1; nCol < nColCount; nCol++) { bomRow.GetItem(nCol, ref strLabel, ref strName, ref strValue); if (bomProps.ContainsKey(strLabel)) { string newValue = bomProps[strLabel]; bomRow.SetItem(strLabel, newValue); KUtil.Log(">> [" + strLabel + "] = [" + strValue + "] -> [" + newValue + "]"); } } bom.SetItem(i, bomRow); } Database.RefreshBom(); Database.Save(29); KUtil.Log("更新明细栏完成"); return errSB.ToString(); } public void WriteBom(List> cadBomProps) { if (cadBomProps == null || cadBomProps.Count == 0) { return; } string attrIndex = ConfigUtil.GetValue("attr_index"); if (string.IsNullOrWhiteSpace(attrIndex)) { throw new Exception("请检查配置文件,未配置attr_index"); } Bom bom = null; Database.GetBom(ref bom); if (bom == null) { throw new Exception("加载明细栏数据失败"); } int bomlineCnt = cadBomProps.Count; KUtil.Log("更新明细栏"); string strLabel = ""; string strName = ""; string strValue = ""; int nColCount = 0; int existRowCnt = 0; bom.GetItemCount(ref existRowCnt); KUtil.Log("已存在行数量:" + existRowCnt); List updatedRows = new List(); for (int i = 0; i < existRowCnt; i++) { BomRow bomRow = null; int index = -1; bom.GetItem(i, ref bomRow); bomRow.GetItemCount(ref nColCount); for (int nCol = 1; nCol < nColCount; nCol++) { bomRow.GetItem(nCol, ref strLabel, ref strName, ref strValue); if (attrIndex.Equals(strLabel) && !string.IsNullOrWhiteSpace(strValue)) { index = int.Parse(strValue); } } if (index > 0 && index - 1 < bomlineCnt) { KUtil.Log("更新序号:" + index); Dictionary bomProps = cadBomProps[index - 1]; for (int nCol = 1; nCol < nColCount; nCol++) { bomRow.GetItem(nCol, ref strLabel, ref strName, ref strValue); if (bomProps.ContainsKey(strLabel)) { string newValue = bomProps[strLabel]; bomRow.SetItem(strLabel, newValue); KUtil.Log(">> [" + strLabel + "] = [" + strValue + "] -> [" + newValue + "]"); } } bom.SetItem(i, bomRow); updatedRows.Add(index - 1); } } for (int i = 0; i < bomlineCnt; i++) { if (updatedRows.Contains(i)) { continue; } Dictionary bomProps = cadBomProps[i]; int index = i + 1; BomRow bomRow = null; KUtil.Log("新建序号:" + index); //object balloon = null; //Database.GetBalloon(out balloon, "请选择序号["+index+"]"); bom.CreateBomRow(ref bomRow); bomRow.GetItemCount(ref nColCount); for (int nCol = 1; nCol < nColCount; nCol++) { bomRow.GetItem(nCol, ref strLabel, ref strName, ref strValue); if (attrIndex.Equals(strLabel)) { bomRow.SetItem(strLabel, "" + index); KUtil.Log(">> [" + strLabel + "] = " + index); continue; } if (bomProps.ContainsKey(strLabel)) { string newValue = bomProps[strLabel]; bomRow.SetItem(strLabel, newValue); KUtil.Log(">> [" + strLabel + "] = [" + strValue + "] -> [" + newValue + "]"); } } bom.AddItem(bomRow); } Database.RefreshBom(); Database.Save(29); KUtil.Log("更新明细栏完成"); } public void WriteTitle(Dictionary titleProps) { if (titleProps == null || titleProps.Count == 0) { return; } Title title = null; Database.GetTitle(ref title); if (title == null) { throw new Exception("加载标题栏数据失败"); } KUtil.Log("更新标题栏"); string strLabel = ""; string strName = ""; string strValue = ""; int nColCount = 0; title.GetItemCount(ref nColCount); for (int nCol = 0; nCol < nColCount; nCol++) { title.GetItem(nCol, ref strLabel, ref strName, ref strValue); if (titleProps.ContainsKey(strLabel)) { string newValue = titleProps[strLabel]; title.SetItem(strName, newValue); KUtil.Log(">> [" + strLabel + ":" + strName + "] = [" + strValue + "] -> [" + newValue + "]"); } } Database.RefreshTitle(); Database.Save(29); } public Dictionary ReadTitle() { Title title = null; KUtil.Log("ReadTitle"); try { Database.GetTitle(ref title); } catch (Exception ex) { KUtil.Log("Exception:" + ex); } KUtil.Log("ReadTitle:" + title); if (title == null) { Application.ShowAlertDialog("加载标题栏数据失败"); throw new Exception("加载标题栏数据失败"); } KUtil.Log("读取标题栏属性"); Dictionary propMap = new Dictionary(); string strLabel = ""; string strName = ""; string strValue = ""; int nColCount = 0; title.GetItemCount(ref nColCount); for (int nCol = 0; nCol < nColCount; nCol++) { title.GetItem(nCol, ref strLabel, ref strName, ref strValue); KUtil.Put(propMap, strLabel, strValue); } KUtil.Log(KUtil.PrintDictionary(propMap)); return propMap; } public FrameInfo ReadFrame() { Frame frame = null; Database.GetFrame(out frame); if (frame == null) { throw new Exception("加载图纸图框数据失败"); } FrameInfo info = new FrameInfo(frame.FrameStyleName, frame.TitleStyleName, frame.BomStyleName); KUtil.Log("图框信息:" + info); return info; } public TCData ReadDocData(bool readBom, TCUtil tcUtil) { //读取图纸数据 KUtil.Log("开始读取图纸数据: " + File_Path); Dictionary cadProps = ReadTitle(); FrameInfo frameInfo = ReadFrame(); //解析图纸数据 TCData titleData; { string titleName = frameInfo.Title_Name; tcUtil.SetProgress("解析标题栏\"" + titleName + "\""); List saveConfig = GetSaveConfig(titleName, tcUtil); if (saveConfig == null || saveConfig.Count == 0) { throw new Exception("未配置标题栏\"" + titleName + "\"的同步信息"); } titleData = TCData.Parse(saveConfig, cadProps); if (titleData == null) { throw new System.Exception("图纸中未找到有效标题栏的数据"); } } if (readBom) { string titleName = frameInfo.Bom_Name; tcUtil.SetProgress("解析明细栏\"" + titleName + "\""); List saveConfig = GetSaveConfig(titleName, tcUtil); if (saveConfig == null || saveConfig.Count == 0) { throw new Exception("未配置明细栏\"" + titleName + "\"的同步信息"); } List> bomProperties = ReadBom(); int bomlineCnt = bomProperties == null ? 0 : bomProperties.Count; KUtil.Log("找到明细栏数量:" + bomlineCnt); List bomlineDatas = new List(); for (int i = 0; i < bomlineCnt; i++) { Dictionary bomProps = bomProperties[i]; TCData tcData = TCData.Parse(saveConfig, bomProps); if (tcData == null) { continue; } bomlineDatas.Add(tcData); } titleData.BomLineDatas = bomlineDatas; } KUtil.Log("读取图纸完成:" + File_Path); titleData.DocFileName = File_Path; return titleData; } public Dictionary ReadCADBomLine(TCUtil tcUtil) { //读取图纸数据 KUtil.Log("开始读取图纸BOM: " + File_Path); FrameInfo frameInfo = ReadFrame(); string titleName = frameInfo.Bom_Name; tcUtil.SetProgress("解析明细栏\"" + titleName + "\""); List saveConfig = GetSaveConfig(titleName, tcUtil); if (saveConfig == null || saveConfig.Count == 0) { throw new Exception("未配置明细栏\"" + titleName + "\"的同步信息"); } Bom bom = null; Database.GetBom(ref bom); if (bom == null) { throw new Exception("加载明细栏数据失败"); } string strLabel = ""; string strName = ""; string strValue = ""; BomRow m_objBomRow = null; int nColCount = 0; int existRowCnt = 0; bom.GetItemCount(ref existRowCnt); KUtil.Log("读取明细栏属性,行数量:" + existRowCnt); Dictionary bomlineMap = new Dictionary(); for (int i = 0; i < existRowCnt; i++) { bom.GetItem(i, ref m_objBomRow); Dictionary bomProps = new Dictionary(); m_objBomRow.GetItemCount(ref nColCount); for (int nCol = 1; nCol < nColCount; nCol++) { m_objBomRow.GetItem(nCol, ref strLabel, ref strName, ref strValue); KUtil.Put(bomProps, strLabel, strValue); } if (bomProps.Count == 0) { continue; } KUtil.Log(KUtil.PrintDictionary(bomProps)); TCData tcData = TCData.Parse(saveConfig, bomProps); if (tcData == null) { KUtil.Log(">> 无效行"); continue; } KUtil.Put(bomlineMap, i, tcData); } KUtil.Log("读取图纸BOM完成:" + File_Path); return bomlineMap; } public static List GetBlocks(Transaction trans, Database database, BlockTable blockTable, OpenMode mode, params string[] blockName) { if (KUtil.GetLen(blockName) == 0) { return null; } bool hasBlock = false; foreach (string name in blockName) { if (blockTable.Has(name)) { hasBlock = true; break; } } if (!hasBlock) { return null; } List blockRefs = new List(); BlockTableRecord blockTableRecord = trans.GetObject(database.CurrentSpaceId, mode) as BlockTableRecord; foreach (ObjectId item in blockTableRecord) { BlockReference blockReference = trans.GetObject(item, mode) as BlockReference; if (blockReference == null) { continue; } if (blockName.Contains(blockReference.Name)) { blockRefs.Add(blockReference); } } return blockRefs; } public static void GetBlocksByRegex(Transaction trans, Database database, BlockTable blockTable, OpenMode mode, out List blockRefs, out List blockRefRegexs, params string[] blockName) { blockRefs = new List(); blockRefRegexs = new List(); if (KUtil.GetLen(blockName) == 0) { return; } KUtil.Log("开始查询块 " + string.Join(", ", blockName)); List regexList = new List(); foreach (string name in blockName) { regexList.Add(new Regex(name)); } BlockTableRecord blockTableRecord = trans.GetObject(database.CurrentSpaceId, mode) as BlockTableRecord; foreach (ObjectId item in blockTableRecord) { BlockReference blockReference = trans.GetObject(item, mode) as BlockReference; if (blockReference == null) { continue; } string targetRgx = null; KUtil.Log("块名称: " + blockReference.Name); string block_name = blockReference.Name; if (block_name.Contains("_A")) { int index = block_name.IndexOf("_A"); block_name = block_name.Substring(index); KUtil.Log("块名称2: " + block_name); } foreach (Regex rgx in regexList) { KUtil.Log("块名称1: " + rgx.ToString()); //if (rgx.IsMatch(blockReference.Name)) { // targetRgx = rgx.ToString(); // KUtil.Log(">> "+targetRgx+" -> "+blockReference.Name); // break; //} if ((rgx.ToString()).Contains(block_name)) { targetRgx = rgx.ToString(); KUtil.Log(">> " + targetRgx + " -> " + blockReference.Name); break; } /*if (blockReference.Name.Equals(rgx.ToString())){ targetRgx = rgx.ToString(); KUtil.Log(">> " + targetRgx + " -> " + blockReference.Name); break; }*/ } if (targetRgx != null) { blockRefs.Add(blockReference); blockRefRegexs.Add(targetRgx); } } } public static bool CheckOpendDoc(TCData data) { if (data == null || string.IsNullOrWhiteSpace(data.DocFileName)) { return false; } foreach (object doc in Application.DocumentManager) { if (doc is Document) { if (data.DocFileName.Equals(((Document)doc).Name)) { using (((Document)doc).LockDocument()) { string newPath = System.IO.Path.GetTempPath() + System.IO.Path.GetFileName(data.DocFileName); KUtil.Log("另存打开的图纸:" + newPath); ((Document)doc).Database.SaveAs(newPath, false, DwgVersion.Current, null); //((Document)doc).Database.SaveAs(newPath, DwgVersion.Current); data.DocFileName = newPath; return true; } } } } return false; } public void saveData() { Database.Save(29); } } }