TabPageMatlabSourceCode.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text.RegularExpressions;
  4. using System.ComponentModel;
  5. using System.IO;
  6. using System.Data;
  7. using System.Drawing;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Windows.Forms;
  12. using System.Text.Json;
  13. using System.Threading;
  14. using System.Text.Encodings.Web;
  15. using System.Text.Json.Serialization;
  16. using System.Text.Unicode;
  17. namespace Uestc.Auto6.Dso.Hardware.Calibration.Tool
  18. {
  19. public partial class TabPageMatlabSourceCode : UserControl
  20. {
  21. public TabPageMatlabSourceCode()
  22. {
  23. InitializeComponent();
  24. InitPrePosProcessor();
  25. Running = false;
  26. }
  27. public IInstrumentSession currInstrumentSession = null;
  28. public void SetInstrument(IInstrumentSession instrumentSession)
  29. {
  30. currInstrumentSession = instrumentSession;
  31. }
  32. private void InitPrePosProcessor()
  33. {
  34. comboBoxMatlabSourceCode_PrePosProcessType.Items.Clear();
  35. comboBoxMatlabSourceCode_PrePosProcessType.SelectedIndex = -1;
  36. string jsonFileName = Path.GetFileNameWithoutExtension(Application.ExecutablePath) + ".MatlabSourceCodePrePosProcessor.config";
  37. if (!File.Exists(jsonFileName))
  38. return;
  39. List<TitleClassNamePair> allDefinedProcessors = JsonSerializer.Deserialize<List<TitleClassNamePair>>(File.ReadAllText(jsonFileName, Encoding.UTF8));
  40. //allDefinedProcessors.Clear();
  41. //allDefinedProcessors.Add(new TitleClassNamePair() { Title = "这是一个测试", ClassName = "MatlabSourceCodePrePosProcessor_Test" });
  42. //JsonSerializerOptions options = new JsonSerializerOptions{Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)};
  43. //File.WriteAllText(jsonFileName, JsonSerializer.Serialize<List<TitleClassNamePair>>(allDefinedProcessors, options),Encoding.UTF8);
  44. if (allDefinedProcessors.Count > 0)
  45. {
  46. foreach (TitleClassNamePair pair in allDefinedProcessors)
  47. {
  48. if (ExistsPrePosProcessos(pair.ClassName))
  49. comboBoxMatlabSourceCode_PrePosProcessType.Items.Add(new ComboxItemObject { Text = pair.Title, Value = pair.ClassName });
  50. }
  51. if (allDefinedProcessors.Count > 0)
  52. comboBoxMatlabSourceCode_PrePosProcessType.SelectedIndex = 0;
  53. }
  54. buttonMatlabSourceCode_LoadFromFile.Enabled = Helper.bMatlabInstalled;
  55. buttonMatlabSourceCode_RunStopStatus.Enabled = Helper.bMatlabInstalled;
  56. }
  57. IMatlabSourceCodePrePosProcessor currMatlabSourceCodePrePosProcessor = null;
  58. IMatlabSourceCodePrePosProcessor CreatePrePosProcessos(string className)
  59. {
  60. var q = from t in Helper.AllMatlabSourceCodePrePosProcessorClass.ToArray()
  61. where t.Name == className
  62. select t;
  63. if (Enumerable.Count(q) > 0)
  64. return (IMatlabSourceCodePrePosProcessor)Activator.CreateInstance((Type)q.ToList()[0]);
  65. else
  66. return null;
  67. }
  68. Boolean ExistsPrePosProcessos(string className)
  69. {
  70. var q = from t in Helper.AllMatlabSourceCodePrePosProcessorClass.ToArray()
  71. where t.Name == className
  72. select t;
  73. return (Enumerable.Count(q) > 0);
  74. }
  75. private Boolean bFirstRun = true;
  76. IntPtr figure1;//图像句柄
  77. private String DisposeText(String matlabcode, out Boolean hasclose, out String closecode)
  78. {
  79. String result = "";
  80. hasclose = false;
  81. String[] sArray = Regex.Split(matlabcode, "\n");
  82. closecode = "";
  83. foreach (String code in sArray)
  84. {
  85. if (code.Contains("close"))
  86. {
  87. hasclose = true;
  88. String[] mixcode = code.Split(';');
  89. foreach (String currtcode in mixcode)
  90. {
  91. if (currtcode.Contains("close"))
  92. {
  93. closecode = currtcode + ";\n";
  94. }
  95. else if (currtcode.Equals(""))
  96. continue;
  97. else
  98. result += currtcode + ";\n";
  99. }
  100. }
  101. else
  102. result += code + "\n";
  103. }
  104. return result;
  105. }
  106. private string matLabSourceCode = "";
  107. private void timer1_Tick(object sender, EventArgs e)
  108. {
  109. string sourceCode = richTextBoxMatlabSourceCode_SourceCode.Text;
  110. if (sourceCode.Trim() == "")
  111. return;
  112. if (matlabApp == null)
  113. return;
  114. if (figure1 == IntPtr.Zero)
  115. return;
  116. if (currMatlabSourceCodePrePosProcessor != null)
  117. currMatlabSourceCodePrePosProcessor.PutInputData(matlabApp, currInstrumentSession);
  118. try
  119. {
  120. String response = matlabApp.Execute(matLabSourceCode);
  121. if (!String.IsNullOrEmpty(response))
  122. {
  123. try
  124. {
  125. richTextBoxMatlabSourceCode_Result.Text = response;
  126. }
  127. catch (Exception ee)
  128. {
  129. System.Diagnostics.Trace.WriteLine(ee);
  130. }
  131. }
  132. if (currMatlabSourceCodePrePosProcessor != null)
  133. currMatlabSourceCodePrePosProcessor.GetOutputData(matlabApp, currInstrumentSession);
  134. }
  135. catch
  136. {
  137. }
  138. }
  139. private bool Running
  140. {
  141. get => buttonMatlabSourceCode_RunStopStatus.Tag.ToString() != "stop";
  142. set
  143. {
  144. buttonMatlabSourceCode_RunStopStatus.Tag = value ? "run" : "stop";
  145. buttonMatlabSourceCode_RunStopStatus.Text = value ? "Stop" : "Run";
  146. richTextBoxMatlabSourceCode_SourceCode.ReadOnly = value;
  147. buttonMatlabSourceCode_LoadFromFile.Enabled = !value;
  148. }
  149. }
  150. private MLApp.MLApp matlabApp = null;
  151. bool bHasClose = false;
  152. string closeCode = "";
  153. private void AttachMatlabFigure()
  154. {
  155. matlabApp = Activator.CreateInstance(Type.GetTypeFromProgID("Matlab.Application")) as MLApp.MLApp;
  156. matlabApp.Visible = 0;
  157. matlabApp.Execute("close all");
  158. matlabApp.Execute("figure('toolbar','none','menubar','none')");//创建基础图层 后面的图层皆在这一图层上绘制
  159. Thread.Sleep(1000);
  160. figure1 = ImportOutFuncs.FindWindow("SunAwtFrame", "Figure 1");
  161. if (figure1 != IntPtr.Zero)
  162. panelFigure_SizeChanged(null, null);
  163. }
  164. private void buttonMatlabSourceCode_RunStopStatus_Click(object sender, EventArgs e)
  165. {
  166. if (Running)
  167. {
  168. Running = false;
  169. timer1.Stop();
  170. }
  171. else
  172. {
  173. if (currInstrumentSession == null)
  174. {
  175. MessageBox.Show("请先连接我们的示波器!");
  176. return;
  177. }
  178. string sourceCode = richTextBoxMatlabSourceCode_SourceCode.Text;
  179. if (string.Empty == sourceCode.Trim())
  180. {
  181. MessageBox.Show("没有可执行的代码!");
  182. return;
  183. }
  184. //string formula = "result=zeros(1,length(source1));" + DisposeText(sourceCode, out bHasClose, out closeCode);
  185. string formula = DisposeText(sourceCode, out bHasClose, out closeCode);
  186. if (bFirstRun)
  187. {
  188. AttachMatlabFigure();
  189. bFirstRun = false;
  190. }
  191. if (matlabApp == null || figure1 == IntPtr.Zero)
  192. {
  193. timer1.Stop();
  194. MessageBox.Show("出现问题,不能处理!");
  195. return;
  196. }
  197. matLabSourceCode = formula;
  198. timer1.Start();
  199. Running = true;
  200. }
  201. }
  202. private string loadedFileName = "";
  203. private void buttonMatlabSourceCode_LoadFromFile_Click(object sender, EventArgs e)
  204. {
  205. if (openFileDialog1.ShowDialog() == DialogResult.OK)
  206. {
  207. Running = false;
  208. richTextBoxMatlabSourceCode_SourceCode.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
  209. loadedFileName = openFileDialog1.FileName;
  210. }
  211. }
  212. private void buttonMatlabSourceCode_SaveToFile_Click(object sender, EventArgs e)
  213. {
  214. if (loadedFileName == "")
  215. return;
  216. if (saveFileDialog1.ShowDialog() != DialogResult.OK)
  217. return;
  218. richTextBoxMatlabSourceCode_SourceCode.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
  219. }
  220. private void comboBoxMatlabSourceCode_PrePosProcessType_SelectedIndexChanged(object sender, EventArgs e)
  221. {
  222. if (comboBoxMatlabSourceCode_PrePosProcessType.SelectedIndex >= 0)
  223. currMatlabSourceCodePrePosProcessor = CreatePrePosProcessos((comboBoxMatlabSourceCode_PrePosProcessType.SelectedItem as ComboxItemObject).Value.ToString());
  224. else
  225. currMatlabSourceCodePrePosProcessor = null;
  226. }
  227. private delegate void UpdateUI();//委托用于更新UI
  228. private void panelFigure_SizeChanged(object sender, EventArgs e)
  229. {
  230. if (figure1 == IntPtr.Zero)
  231. return;
  232. //跨线程,用委托方式执行
  233. UpdateUI update = delegate
  234. {
  235. //设置matlab图像窗体的父窗体为panel
  236. ImportOutFuncs.SetParent(figure1, panelFigure.Handle);
  237. //获取窗体原来的风格
  238. var style = ImportOutFuncs.GetWindowLong(figure1, ImportOutFuncs.GWL_STYLE);
  239. //设置新风格,去掉标题,取消所有边框,不能通过边框改变尺寸
  240. ImportOutFuncs.SetWindowLong(figure1, ImportOutFuncs.GWL_STYLE, style & ~ImportOutFuncs.WS_CAPTION & ~ImportOutFuncs.WS_THICKFRAME);
  241. //移动到panel里合适的位置并重绘
  242. ImportOutFuncs.MoveWindow(figure1, 0, 0, panelFigure.Width + 0, panelFigure.Height + 0, true);
  243. Application.DoEvents();
  244. //MoveWindow(figure1, 0, 0, 400 + 0, 300 + 0, true);
  245. //调用显示窗体函数,隐藏再显示相当于刷新一下窗体
  246. };
  247. panelFigure.Invoke(update);
  248. //再移动一次,防止显示错误
  249. //Thread.Sleep(100);
  250. //ImportOutFuncs.MoveWindow(figure1, 0, 0, panelFigure.Width + 0, panelFigure.Height + 0, true);
  251. Application.DoEvents();
  252. }
  253. }
  254. }