RecipeEditorControlViewModel.cs 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.ComponentModel;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text.RegularExpressions;
  10. using System.Threading.Tasks;
  11. using System.Windows;
  12. using System.Windows.Controls;
  13. using System.Windows.Data;
  14. using System.Windows.Input;
  15. using System.Windows.Media;
  16. using System.Xml;
  17. using Aitex.UI.RecipeEditor.Core;
  18. using Aitex.UI.RecipeEditor.View;
  19. using ExcelLibrary.SpreadSheet;
  20. using Microsoft.Win32;
  21. using Xceed.Wpf.DataGrid;
  22. namespace Aitex.UI.RecipeEditor
  23. {
  24. public class RecipeEditorControlViewModel : INotifyPropertyChanged
  25. {
  26. public List<Tuple<string, string, ObservableCollection<RecipeRow>, Guid>> UndoList { get; set; }
  27. public List<Tuple<string, string, ObservableCollection<RecipeRow>, Guid>> RedoList { get; set; }
  28. public bool IsUndoEnabled { get { return UndoList != null && UndoList.Count > 0; } }
  29. public bool IsRedoEnabled { get { return RedoList != null && RedoList.Count > 0; } }
  30. public ObservableCollection<RecipeRow> RecipeRows { get; set; }
  31. private ObservableCollection<RecipeRow> _previousRecipeRows { get; set; }
  32. private string _valueBeforeEditing { get; set; }
  33. private string _currentRecipeVariationName = string.Empty;
  34. private SmartCellData _currentEditingCellData { get; set; }
  35. public List<Tuple<int/*row no*/, int/*col no*/, string/*var name*/, string/*reason*/>> Errors { get; set; }
  36. public List<Tuple<string, string>> CreateRecipeList { get; set; }
  37. public List<Tuple<string, string>> OpenRecipeList { get; set; }
  38. public DataGridControl DataGridControl { get; set; }
  39. public int CurrentRunningStepNo { get; set; }
  40. public Visibility SingleAppElementVisibility { get; set; }
  41. public Visibility RecipeInfoTextVisibility { get; set; }
  42. public ICommand ShowDetailedErrInfoCommand { get; set; }
  43. public ICommand EditRecipeInfoCommand { get; set; }
  44. //public ICommand CellContentChangedCommand { get; set; }
  45. public ICommand RightClickCommand { get; set; }
  46. public ICommand OpenLocalRecipeCommand { get; set; }
  47. public ICommand ExpandGroupCommand { get; set; }
  48. public ICommand CollapseGroupCommand { get; set; }
  49. public ICommand SaveRecipeCommand { get; set; }
  50. public ICommand RecipeHelpDocCommand { get; set; }
  51. public ICommand RecipeExport2ExcelCommand { get; set; }
  52. public ICommand ToggleHideSameCommand { get; set; }
  53. public ICommand UndoCommand { get; set; }
  54. public ICommand RedoCommand { get; set; }
  55. public ICommand SmartCellEditorLoadedCommand { get; set; }
  56. public ICommand SmartCellEditorUnloadedCommand { get; set; }
  57. public RecipeHead RecipeHead { get; set; }
  58. public bool IsBusy { get; set; }
  59. public bool IsHideSameContent { get; set; }
  60. public string RecipeInfo { get; set; }
  61. public HashSet<string> MaskedTechNames { get; set; }
  62. public HashSet<string> MaskedCatalogNames { get; set; }
  63. public event EventHandler OnSaveRecipeFile;
  64. public event EventHandler OnLocalRecipeOpened;
  65. public event EventHandler OnLoadRecipeContent;
  66. public bool IsRecipeModified { get; set; }
  67. public string UserName { set; get; }
  68. //private List<Tuple<string, string, string>> SourceDilteInjectRestrictions { get; set; }
  69. private Dictionary<string, string> _preDefinedRecipeVars { get; set; }
  70. private List<Tuple<string/*varName*/, string/*check condition*/, string/*message*/>> _validationRules { get; set; }
  71. private List<string> _checkVariables { get; set; }
  72. private Dictionary<string, int> RowVarNameDic { get; set; }
  73. private Dictionary<int, List<SmartCellData>> _copiedColumnDatas = new Dictionary<int, List<SmartCellData>>();
  74. private Dictionary<string/*CatalogName*/, Dictionary<string/*GroupName*/, List<RecipeVariableDefine/*StepList*/>>> _recipeReadingFormat;
  75. private Dictionary<string/*ModuleName*/, List<string>/*each item's control name*/> _recipeSavingFormat;
  76. private string _currentRecipeFormatContent;
  77. public bool IsBarcodeEnabled
  78. {
  79. get; set;
  80. }
  81. public Visibility IsBarcodeVisibility
  82. {
  83. get
  84. {
  85. return IsBarcodeEnabled ? Visibility.Visible : Visibility.Hidden;
  86. }
  87. }
  88. private string _defaultEndPointValue { get; set; }
  89. /// <summary>
  90. /// class construction
  91. /// </summary>
  92. public RecipeEditorControlViewModel()
  93. {
  94. UndoList = new List<Tuple<string, string, ObservableCollection<RecipeRow>, Guid>>();
  95. RedoList = new List<Tuple<string, string, ObservableCollection<RecipeRow>, Guid>>();
  96. //if(SingleAppElementVisibility
  97. CreateRecipeList = new List<Tuple<string, string>>();
  98. OpenRecipeList = new List<Tuple<string, string>>();
  99. foreach (var item in GetDefinedRecipeVariations())
  100. {
  101. CreateRecipeList.Add(new Tuple<string, string>("配置:" + item, item));
  102. OpenRecipeList.Add(new Tuple<string, string>("转换为配置:" + item, item));
  103. }
  104. RecipeInfoTextVisibility = Visibility.Collapsed;
  105. SingleAppElementVisibility = Visibility.Collapsed;
  106. RightClickCommand = new DelegatedCommand((o) => true, (o) => RightClickAction());
  107. ExpandGroupCommand = new DelegatedCommand((o) => true, (o) => ExpandGroups());
  108. CollapseGroupCommand = new DelegatedCommand((o) => true, (o) => CollapseGroups());
  109. SaveRecipeCommand = new DelegatedCommand((o) => true, (o) => SaveRecipeFile());
  110. OpenLocalRecipeCommand = new DelegatedCommand((o) => true, (o) => OpenLocalRecipe());
  111. ShowDetailedErrInfoCommand = new DelegatedCommand((o) => true, (o) => ShowDetailedErrInformation());
  112. EditRecipeInfoCommand = new DelegatedCommand((o) => true, (o) => EditRecipeInformation());
  113. RecipeHelpDocCommand = new DelegatedCommand((o) => true, (o) => ShowHelpDocView());
  114. RecipeExport2ExcelCommand = new DelegatedCommand((o) => true, (o) => Export2Excel());
  115. ToggleHideSameCommand = new DelegatedCommand((o) => true, (o) => ToggleHideSameContent());
  116. UndoCommand = new DelegatedCommand((o) => true, (o) => UndoOperation(o));
  117. RedoCommand = new DelegatedCommand((o) => true, (o) => RedoOperation(o));
  118. SmartCellEditorLoadedCommand = new DelegatedCommand((o) => true, (o) => SmartCellEditorLoaded(o));
  119. SmartCellEditorUnloadedCommand = new DelegatedCommand((o) => true, (o) => SmartCellEditorUnloaded(o));
  120. }
  121. /// <summary>
  122. /// When smart cell editor loaded
  123. /// </summary>
  124. /// <param name="obj"></param>
  125. private void SmartCellEditorLoaded(object obj)
  126. {
  127. _currentEditingCellData = obj as SmartCellData;
  128. if (_currentEditingCellData == null) return;
  129. _valueBeforeEditing = _currentEditingCellData.Value;
  130. _previousRecipeRows = CloneRecipeRowData(RecipeRows);
  131. }
  132. /// <summary>
  133. /// make a clone of current recipe row data
  134. /// </summary>
  135. /// <returns></returns>
  136. private ObservableCollection<RecipeRow> CloneRecipeRowData(ObservableCollection<RecipeRow> oldData)
  137. {
  138. ObservableCollection<RecipeRow> newRecipeRows = new ObservableCollection<RecipeRow>();
  139. foreach (var item in oldData)
  140. {
  141. var newRecipeRow = new RecipeRow() { CatalogName = item.CatalogName, FriendlyName = item.FriendlyName, TechnicalName = item.TechnicalName, RecipeItems = new ObservableCollection<SmartCellData>() };
  142. newRecipeRows.Add(newRecipeRow);
  143. foreach (var item2 in item.RecipeItems)
  144. {
  145. var newRecipeItem = new SmartCellData() { Background = item2.Background, ErrInfo = item2.ErrInfo, FontWeight = item2.FontWeight, Foreground = item2.Foreground, IsHidden = item2.IsHidden, IsMasked = item2.IsMasked, IsRunning = item2.IsRunning, RecipeVariableDefine = item2.RecipeVariableDefine, Value = item2.Value };
  146. newRecipeRow.RecipeItems.Add(newRecipeItem);
  147. }
  148. }
  149. return newRecipeRows;
  150. }
  151. /// <summary>
  152. /// When smart cell editor unloaded
  153. /// </summary>
  154. /// <param name="obj"></param>
  155. private void SmartCellEditorUnloaded(object obj)
  156. {
  157. if (_currentEditingCellData != null && _currentEditingCellData.Value != _valueBeforeEditing)
  158. {
  159. IsRecipeModified = true;
  160. var ret = OverrideSelectedCellsData();
  161. if (ret < 2)
  162. AddUndoHistory(string.Format("第{0}步({1})",
  163. _currentEditingCellData.ColIndex + 1,
  164. _currentEditingCellData.RecipeVariableDefine.CatalogName + _currentEditingCellData.RecipeVariableDefine.FriendlyName), _previousRecipeRows);
  165. else
  166. AddUndoHistory(string.Format("第{0}步({1})等{2}个单元格数据",
  167. _currentEditingCellData.ColIndex + 1,
  168. _currentEditingCellData.RecipeVariableDefine.CatalogName + _currentEditingCellData.RecipeVariableDefine.FriendlyName, ret), _previousRecipeRows);
  169. }
  170. RefreshCellsDisplay(false);
  171. }
  172. /// <summary>
  173. /// Adding undo history
  174. /// </summary>
  175. /// <param name="description"></param>
  176. /// <param name="recipeRows"></param>
  177. private void AddUndoHistory(string description, ObservableCollection<RecipeRow> recipeRows)
  178. {
  179. System.Diagnostics.Debug.WriteLine(description);
  180. if (recipeRows == null)
  181. return;
  182. string shortDesc = "";
  183. if (description.Length > 50)
  184. {
  185. shortDesc = description.Substring(0, 50);
  186. shortDesc += "...";
  187. }
  188. else
  189. {
  190. shortDesc = description;
  191. }
  192. UndoList.Insert(0, new Tuple<string, string, ObservableCollection<RecipeRow>, Guid>(shortDesc, description, recipeRows, Guid.NewGuid()));
  193. UndoList = new List<Tuple<string, string, ObservableCollection<RecipeRow>, Guid>>(UndoList.ToList());
  194. RedoList = new List<Tuple<string, string, ObservableCollection<RecipeRow>, Guid>>();
  195. InvokePropertyChanged("UndoList");
  196. InvokePropertyChanged("RedoList");
  197. InvokePropertyChanged("IsUndoEnabled");
  198. InvokePropertyChanged("IsRedoEnabled");
  199. }
  200. /// <summary>
  201. /// Redo something here
  202. /// </summary>
  203. private void RedoOperation(object obj)
  204. {
  205. try
  206. {
  207. if (RedoList == null || RedoList.Count == 0)
  208. return;
  209. Guid redoId = Guid.Empty;
  210. if (obj == null)
  211. redoId = RedoList[0].Item4;
  212. else
  213. redoId = (Guid)obj;
  214. var itemIndex = RedoList.FindIndex((o) => o.Item4 == redoId);
  215. if (itemIndex < 0)
  216. return;
  217. UndoList.Reverse();
  218. for (int i = 0; i <= itemIndex; i++)
  219. {
  220. if (i == 0)
  221. UndoList.Add(new Tuple<string, string, ObservableCollection<RecipeRow>, Guid>(RedoList[i].Item1, RedoList[i].Item2, CloneRecipeRowData(RecipeRows), RedoList[i].Item4));
  222. else
  223. UndoList.Add(new Tuple<string, string, ObservableCollection<RecipeRow>, Guid>(RedoList[i].Item1, RedoList[i].Item2, RedoList[i - 1].Item3, RedoList[i].Item4));
  224. }
  225. UndoList.Reverse();
  226. UndoList = new List<Tuple<string, string, ObservableCollection<RecipeRow>, Guid>>(UndoList.ToList());
  227. RecipeRows = RedoList[itemIndex].Item3;
  228. RedoList.RemoveRange(0, itemIndex + 1);
  229. RedoList = new List<Tuple<string, string, ObservableCollection<RecipeRow>, Guid>>(RedoList.ToList());
  230. RefreshDataGrid();
  231. RefreshCellsDisplay(false);
  232. InvokePropertyChanged("UndoList");
  233. InvokePropertyChanged("RedoList");
  234. InvokePropertyChanged("IsUndoEnabled");
  235. InvokePropertyChanged("IsRedoEnabled");
  236. }
  237. catch (Exception ex)
  238. {
  239. System.Diagnostics.Debug.WriteLine(ex.Message);
  240. MessageBox.Show("恢复动作失败!\r\n\r\n" + ex.Message, "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
  241. }
  242. }
  243. /// <summary>
  244. /// Undo something here
  245. /// </summary>
  246. private void UndoOperation(object obj)
  247. {
  248. try
  249. {
  250. if (UndoList == null || UndoList.Count == 0)
  251. return;
  252. Guid undoId = Guid.Empty;
  253. if (obj == null)
  254. undoId = UndoList[0].Item4;
  255. else
  256. undoId = (Guid)obj;
  257. var itemIndex = UndoList.FindIndex((o) => o.Item4 == undoId);
  258. if (itemIndex < 0)
  259. return;
  260. RedoList.Reverse();
  261. for (int i = 0; i <= itemIndex; i++)
  262. {
  263. if (i == 0)
  264. RedoList.Add(new Tuple<string, string, ObservableCollection<RecipeRow>, Guid>(UndoList[i].Item1, UndoList[i].Item2, CloneRecipeRowData(RecipeRows), UndoList[i].Item4));
  265. else
  266. RedoList.Add(new Tuple<string, string, ObservableCollection<RecipeRow>, Guid>(UndoList[i].Item1, UndoList[i].Item2, UndoList[i - 1].Item3, UndoList[i].Item4));
  267. }
  268. RedoList.Reverse();
  269. RedoList = new List<Tuple<string, string, ObservableCollection<RecipeRow>, Guid>>(RedoList.ToList());
  270. RecipeRows = UndoList[itemIndex].Item3;
  271. UndoList.RemoveRange(0, itemIndex + 1);
  272. UndoList = new List<Tuple<string, string, ObservableCollection<RecipeRow>, Guid>>(UndoList.ToList());
  273. RefreshDataGrid();
  274. RefreshCellsDisplay(false);
  275. InvokePropertyChanged("UndoList");
  276. InvokePropertyChanged("RedoList");
  277. InvokePropertyChanged("IsUndoEnabled");
  278. InvokePropertyChanged("IsRedoEnabled");
  279. }
  280. catch (Exception ex)
  281. {
  282. System.Diagnostics.Debug.WriteLine(ex.Message);
  283. MessageBox.Show("撤销动作失败!\r\n\r\n" + ex.Message, "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
  284. }
  285. }
  286. /// <summary>
  287. /// hide or show same content before and after one step
  288. /// </summary>
  289. private void ToggleHideSameContent()
  290. {
  291. IsHideSameContent = !IsHideSameContent;
  292. RefreshCellsDisplay(false);
  293. }
  294. /// <summary>
  295. /// get recipe variations
  296. /// </summary>
  297. /// <returns></returns>
  298. public List<string> GetDefinedRecipeVariations()
  299. {
  300. var list1 = new List<string>();
  301. var dir = new System.IO.FileInfo(Process.GetCurrentProcess().MainModule.FileName).Directory;
  302. string cfgPath = dir + "\\Config\\";
  303. var di = new System.IO.DirectoryInfo(cfgPath);
  304. if (di.Exists)
  305. {
  306. foreach (var item in di.GetFiles("*.xml"))
  307. {
  308. list1.Add(item.Name.Substring(0, item.Name.Length - item.Extension.Length));
  309. }
  310. }
  311. return list1;
  312. }
  313. /// <summary>
  314. /// Export to excel
  315. /// </summary>
  316. private void Export2Excel()
  317. {
  318. try
  319. {
  320. if (RecipeRows == null) return;
  321. var dlg = new SaveFileDialog();
  322. dlg.DefaultExt = ".xls";
  323. dlg.Filter = "Excel文件 (.xls)|*.xls|所有文件 (*.*)|*.*";
  324. if (dlg.ShowDialog() == true)
  325. {
  326. if (File.Exists(dlg.FileName))
  327. File.Delete(dlg.FileName);
  328. Workbook workbook = new Workbook();
  329. Worksheet worksheet = new Worksheet("First Sheet");
  330. XmlDocument doc = new XmlDocument();
  331. doc.LoadXml(_currentRecipeFormatContent);
  332. var catalogNodes = doc.SelectNodes("TableRecipeFormat/Catalog");
  333. int groupRowIndex = 0;
  334. int stepRowIndex = 0;
  335. int catalogRowIndex = 0;
  336. foreach (XmlElement cNode in catalogNodes)
  337. {
  338. XmlNodeList sNodes = cNode.SelectNodes("Group/Step");
  339. string catalogHeader = cNode.Attributes["DisplayName"].Value;
  340. worksheet.Cells[catalogRowIndex, 0] = new ExcelLibrary.SpreadSheet.Cell(catalogHeader);
  341. catalogRowIndex += sNodes.Count;
  342. XmlNodeList gNodes = cNode.SelectNodes("Group");
  343. foreach (XmlElement gNode in gNodes)
  344. {
  345. XmlNodeList stepNodes = gNode.SelectNodes("Step");
  346. string groupHeader = gNode.Attributes["DisplayName"].Value;
  347. worksheet.Cells[groupRowIndex, 1] = new ExcelLibrary.SpreadSheet.Cell(groupHeader);
  348. groupRowIndex += stepNodes.Count;
  349. foreach (XmlElement nd in stepNodes)
  350. {
  351. string stepHeader = nd.Attributes["DisplayName"].Value;
  352. worksheet.Cells[stepRowIndex, 2] = new ExcelLibrary.SpreadSheet.Cell(stepHeader);
  353. stepRowIndex++;
  354. }
  355. }
  356. }
  357. string recipeContent = GetRecipeContentString();
  358. XmlDocument rcp = new XmlDocument();
  359. rcp.LoadXml(recipeContent);
  360. XmlNodeList stepNodeList = rcp.SelectNodes("/TableRecipeData/Step");
  361. for (int stepNo = 0; stepNo < stepNodeList.Count; stepNo++)
  362. {
  363. var dataDic = new Dictionary<string, string>();
  364. foreach (XmlAttribute att in (stepNodeList[stepNo] as XmlElement).Attributes)
  365. {
  366. dataDic.Add(att.Name, att.Value);
  367. }
  368. //fill sub node's attributes
  369. foreach (XmlElement subStep in stepNodeList[stepNo].ChildNodes)
  370. {
  371. foreach (XmlAttribute att in subStep.Attributes)
  372. {
  373. dataDic.Add(att.Name, att.Value);
  374. }
  375. foreach (XmlElement subsubStep in subStep.ChildNodes)
  376. {
  377. foreach (XmlAttribute att2 in subsubStep.Attributes)
  378. {
  379. dataDic.Add(att2.Name, att2.Value);
  380. }
  381. }
  382. }
  383. long length = dataDic.LongCount();
  384. int step = 0;
  385. foreach (string key in dataDic.Keys)
  386. {
  387. worksheet.Cells.ColumnWidth[(ushort)step] = 4000;
  388. var cellContent = dataDic[key];
  389. double v;
  390. if (double.TryParse(cellContent, out v))
  391. {
  392. worksheet.Cells[step, stepNo + 3] = new ExcelLibrary.SpreadSheet.Cell(v);
  393. }
  394. else
  395. {
  396. worksheet.Cells[step, stepNo + 3] = new ExcelLibrary.SpreadSheet.Cell(cellContent);
  397. }
  398. step++;
  399. }
  400. }
  401. workbook.Worksheets.Add(worksheet);
  402. workbook.Save(dlg.FileName);
  403. MessageBox.Show(string.Format("成功导出到Excel文件!\r\n\r\n{0}", dlg.FileName), "导出", MessageBoxButton.OK, MessageBoxImage.Information);
  404. }
  405. }
  406. catch (Exception ex)
  407. {
  408. System.Diagnostics.Debug.WriteLine(ex.Message);
  409. MessageBox.Show("导出Excel文件发生异常!\r\n\r\n" + ex.Message, "导出", MessageBoxButton.OK, MessageBoxImage.Error);
  410. }
  411. }
  412. /// <summary>
  413. /// Show recipe information
  414. /// </summary>
  415. private void ShowHelpDocView()
  416. {
  417. var view = RecipeHelpView.Instance;
  418. view.Owner = Application.Current.MainWindow;
  419. view.DataContext = this;
  420. if (view.Visibility == Visibility.Visible)
  421. view.Hide();
  422. else
  423. view.Show();
  424. }
  425. /// <summary>
  426. /// Edit recipe information
  427. /// </summary>
  428. private void EditRecipeInformation()
  429. {
  430. RecipeInfoEditor editor = new RecipeInfoEditor() { RecipeHead = this.RecipeHead, Owner = Application.Current.MainWindow };
  431. editor.ShowDialog();
  432. InvokePropertyChanged("RecipeHead");
  433. }
  434. public void EnableBarcode(bool enable)
  435. {
  436. IsBarcodeEnabled = enable;
  437. InvokePropertyChanged("IsBarcodeVisibility");
  438. }
  439. public void SetCurrentUser(string user)
  440. {
  441. UserName = user;
  442. InvokePropertyChanged("UserName");
  443. }
  444. public void SetEndPointDefaultValue(string defaultValue)
  445. {
  446. _defaultEndPointValue = defaultValue;
  447. }
  448. /// <summary>
  449. /// Show recipe information
  450. /// </summary>
  451. private void ShowDetailedErrInformation()
  452. {
  453. var view = ErrorInformationDetailsView.Instance;
  454. view.Owner = Application.Current.MainWindow;
  455. view.DataContext = this;
  456. if (view.Visibility == Visibility.Visible)
  457. view.Hide();
  458. else
  459. view.ShowDialog();
  460. }
  461. /// <summary>
  462. /// Update selected cells data
  463. /// </summary>
  464. /// <returns>overrided cells number</returns>
  465. private int OverrideSelectedCellsData()
  466. {
  467. int overridedCellsNum = 0;
  468. if (_currentEditingCellData != null)
  469. {
  470. var finalCellData = _currentEditingCellData;
  471. bool containsEditingCell = false;
  472. foreach (var item in DataGridControl.SelectedCellRanges)
  473. {
  474. int startColIndex = Math.Min(item.ColumnRange.StartIndex, item.ColumnRange.EndIndex);
  475. int endColIndex = Math.Max(item.ColumnRange.StartIndex, item.ColumnRange.EndIndex);
  476. int startRowIndex = Math.Min(item.ItemRange.StartIndex, item.ItemRange.EndIndex);
  477. int endRowIndex = Math.Max(item.ItemRange.StartIndex, item.ItemRange.EndIndex);
  478. if (startColIndex > 0 && startColIndex <= RecipeRows[0].RecipeItems.Count &&
  479. endColIndex > 0 && endColIndex <= RecipeRows[0].RecipeItems.Count &&
  480. startRowIndex >= 0 && startRowIndex < RecipeRows.Count &&
  481. endRowIndex >= 0 && endRowIndex < RecipeRows.Count)
  482. {
  483. for (int m = startRowIndex; m <= endRowIndex; m++)
  484. {
  485. for (int n = startColIndex; n <= endColIndex; n++)
  486. {
  487. int rowIndex = m;
  488. int colIndex = n - 1;
  489. if (RecipeRows[rowIndex].RecipeItems[colIndex] == _currentEditingCellData)
  490. {
  491. containsEditingCell = true;
  492. break;
  493. }
  494. }
  495. }
  496. }
  497. }
  498. if (containsEditingCell)
  499. {
  500. foreach (var item in DataGridControl.SelectedCellRanges)
  501. {
  502. int startColIndex = Math.Min(item.ColumnRange.StartIndex, item.ColumnRange.EndIndex);
  503. int endColIndex = Math.Max(item.ColumnRange.StartIndex, item.ColumnRange.EndIndex);
  504. int startRowIndex = Math.Min(item.ItemRange.StartIndex, item.ItemRange.EndIndex);
  505. int endRowIndex = Math.Max(item.ItemRange.StartIndex, item.ItemRange.EndIndex);
  506. if (startColIndex > 0 && startColIndex <= RecipeRows[0].RecipeItems.Count &&
  507. endColIndex > 0 && endColIndex <= RecipeRows[0].RecipeItems.Count &&
  508. startRowIndex >= 0 && startRowIndex < RecipeRows.Count &&
  509. endRowIndex >= 0 && endRowIndex < RecipeRows.Count)
  510. {
  511. for (int m = startRowIndex; m <= endRowIndex; m++)
  512. {
  513. for (int n = startColIndex; n <= endColIndex; n++)
  514. {
  515. int rowIndex = m;
  516. int colIndex = n - 1;
  517. if (RecipeRows[rowIndex].RecipeItems[colIndex].RecipeVariableDefine.CellType == finalCellData.RecipeVariableDefine.CellType)
  518. {
  519. overridedCellsNum++;
  520. RecipeRows[rowIndex].RecipeItems[colIndex].Value = finalCellData.Value;
  521. RecipeRows[rowIndex].RecipeItems[colIndex].InvokePropertyChanged();
  522. }
  523. }
  524. }
  525. }
  526. }
  527. }
  528. }
  529. return overridedCellsNum;
  530. }
  531. /// <summary>
  532. /// Open local recipe operation
  533. /// </summary>
  534. /// <param name="recipeDefineFilePath"></param>
  535. public void OpenLocalRecipe(string recipeVariationName = "")
  536. {
  537. var dlg = new OpenFileDialog();
  538. dlg.DefaultExt = ".rcp";
  539. dlg.Filter = "Recipe File (.rcp)|*.rcp|All (*.*)|*.*";
  540. if (dlg.ShowDialog() == true)
  541. {
  542. try
  543. {
  544. XmlDocument rcpDoc = new XmlDocument();
  545. rcpDoc.Load(dlg.FileName);
  546. string recipeVariation = recipeVariationName;
  547. if (string.IsNullOrEmpty(recipeVariation))
  548. {
  549. var root = rcpDoc.SelectSingleNode("/TableRecipeData") as XmlElement;
  550. recipeVariation = root.Attributes["RecipeVersion"].Value;
  551. }
  552. var startupPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
  553. string dir = System.IO.Path.GetDirectoryName(startupPath);
  554. List<Aitex.Controls.RecipeCompare.Item> map = CustomXmlSerializer.Deserialize<List<Aitex.Controls.RecipeCompare.Item>>(new System.IO.FileInfo(System.IO.Path.Combine(dir, "map.xml")));
  555. Func<Aitex.Controls.RecipeCompare.Item, bool> predicate = item => item.Name.Equals(recipeVariation);
  556. System.IO.FileInfo fi = new System.IO.FileInfo(string.Format("{0}\\config\\{1}.xml", dir, map.Any(predicate) ? map.Single(predicate).No : recipeVariation));
  557. if (fi.Exists)
  558. {
  559. XmlDocument doc = new XmlDocument();
  560. doc.Load(fi.FullName);
  561. string formatXml = doc.SelectSingleNode("/Aitex/TableRecipeFormat").OuterXml;
  562. string recipeXml = rcpDoc.SelectSingleNode("/TableRecipeData").OuterXml;
  563. LoadRecipe(formatXml, recipeXml);
  564. if (OnLocalRecipeOpened != null)
  565. OnLocalRecipeOpened.Invoke(new Tuple<string, string>(recipeVariation, dlg.FileName), null);
  566. }
  567. else
  568. {
  569. MessageBox.Show(string.Format("工艺程序版本{0}的描述文件不存在,无法正确识别该版本的工艺程序文件。", recipeVariation), "工艺程序打开失败",
  570. MessageBoxButton.OK, MessageBoxImage.Error);
  571. }
  572. }
  573. catch (Exception ex)
  574. {
  575. System.Diagnostics.Debug.WriteLine(ex.Message);
  576. MessageBox.Show(string.Format("open recipe {0} failed,please confirm the recipe file is exist and valid。\r\n{1}", dlg.FileName, ex.Message), "Open recipe failed",
  577. MessageBoxButton.OK, MessageBoxImage.Error);
  578. }
  579. }
  580. }
  581. /// <summary>
  582. /// Save recipe file
  583. /// </summary>
  584. private void SaveRecipeFile()
  585. {
  586. try
  587. {
  588. if (Errors != null && Errors.Count > 0)
  589. {
  590. var ret = MessageBox.Show(string.Format("Recipe have {0} error,continue save?", Errors.Count), "Save", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
  591. if (ret != MessageBoxResult.Yes)
  592. return;
  593. }
  594. if (OnSaveRecipeFile != null)
  595. {
  596. IsRecipeModified = false;
  597. OnSaveRecipeFile.Invoke(GetRecipeContentString(), null);
  598. }
  599. }
  600. catch (Exception ex)
  601. {
  602. System.Diagnostics.Debug.WriteLine(ex.Message);
  603. MessageBox.Show("save recipe failed!\r\n\r\n" + ex.Message, "Save", MessageBoxButton.OK, MessageBoxImage.Warning);
  604. }
  605. }
  606. /// <summary>
  607. /// get string typed recipe content
  608. /// </summary>
  609. /// <returns></returns>
  610. public string GetRecipeContentString()
  611. {
  612. if (string.IsNullOrEmpty(UserName))
  613. {
  614. var dlg1 = new Aitex.UI.RecipeEditor.UserNameInput() { Owner = Application.Current.MainWindow };
  615. var ret = dlg1.ShowDialog();
  616. if (ret.HasValue && ret.Value)
  617. {
  618. UserName = dlg1.UserName;
  619. }
  620. }
  621. RecipeHead.LastRevisionTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
  622. RecipeHead.LastModifiedBy = UserName;
  623. InvokePropertyChanged("RecipeHead");
  624. if (RecipeRows == null || RecipeRows.Count == 0 || RecipeRows[0].RecipeItems == null || RecipeRows[0].RecipeItems.Count == 0)
  625. return string.Empty;
  626. //Dictionary<string/*CatalogName*/, Dictionary<string/*GroupName*/, List<RecipeVariableDefine/*StepList*/>>> _recipeReadingFormat;
  627. XmlDocument doc = new XmlDocument();
  628. var rootNode = doc.CreateElement("TableRecipeData");
  629. rootNode.SetAttribute("RecipeVersion", RecipeHead.RecipeVariation);
  630. rootNode.SetAttribute("CreatedBy", RecipeHead.CreatedBy);
  631. rootNode.SetAttribute("CreationTime", RecipeHead.CreationTime);
  632. rootNode.SetAttribute("LastRevisedBy", RecipeHead.LastModifiedBy);
  633. rootNode.SetAttribute("LastRevisionTime", RecipeHead.LastRevisionTime);
  634. if (!string.IsNullOrEmpty(RecipeHead.PressureMode))
  635. {
  636. rootNode.SetAttribute("PressureMode", RecipeHead.PressureMode);
  637. }
  638. if (!string.IsNullOrEmpty(RecipeHead.BasePressure))
  639. {
  640. rootNode.SetAttribute("BasePressure", RecipeHead.BasePressure);
  641. }
  642. if (!string.IsNullOrEmpty(RecipeHead.SubstrateTemp))
  643. {
  644. rootNode.SetAttribute("SubstrateTemp", RecipeHead.SubstrateTemp);
  645. }
  646. if (!string.IsNullOrEmpty(RecipeHead.PumpingPinState))
  647. {
  648. rootNode.SetAttribute("PumpingPinState", RecipeHead.PumpingPinState);
  649. }
  650. if(!string.IsNullOrEmpty(RecipeHead.VentingPinState))
  651. {
  652. rootNode.SetAttribute("VentingPinState", RecipeHead.VentingPinState);
  653. }
  654. if(!string.IsNullOrEmpty(RecipeHead.PinDownPressure))
  655. {
  656. rootNode.SetAttribute("PinDownPressure", RecipeHead.PinDownPressure);
  657. }
  658. if (!string.IsNullOrEmpty(RecipeHead.PumpDownLimit))
  659. {
  660. rootNode.SetAttribute("PumpDownLimit", RecipeHead.PumpDownLimit);
  661. }
  662. if (!string.IsNullOrEmpty(RecipeHead.PurgeActive))
  663. {
  664. rootNode.SetAttribute("PurgeActive", RecipeHead.PurgeActive);
  665. }
  666. if (!string.IsNullOrEmpty(RecipeHead.NotToPurgeOrVent))
  667. {
  668. rootNode.SetAttribute("NotToPurgeOrVent", RecipeHead.NotToPurgeOrVent);
  669. }
  670. rootNode.SetAttribute("Barcode", RecipeHead.Barcode);
  671. rootNode.SetAttribute("Description", RecipeHead.Description);
  672. doc.AppendChild(rootNode);
  673. for (int stepIndex/* 0-> */ = 0; stepIndex < RecipeRows[0].RecipeItems.Count; stepIndex++)
  674. {
  675. var stepNode = doc.CreateElement("Step");
  676. rootNode.AppendChild(stepNode);
  677. foreach (var module in _recipeSavingFormat)
  678. {
  679. var moduleName = module.Key;
  680. XmlElement subNode = stepNode;
  681. if (!string.IsNullOrEmpty(moduleName))
  682. {
  683. string[] pathArr = moduleName.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
  684. for (int i = 0; i < pathArr.Length; i++)
  685. {
  686. var snd = subNode.SelectSingleNode(pathArr[i]) as XmlElement;
  687. if (snd == null)
  688. {
  689. var nd = doc.CreateElement(pathArr[i]);
  690. subNode.AppendChild(nd);
  691. subNode = nd;
  692. }
  693. else
  694. {
  695. subNode = snd;
  696. }
  697. }
  698. }
  699. foreach (var controlName in module.Value)
  700. {
  701. if (controlName == "StepNo")
  702. {
  703. subNode.SetAttribute(controlName, string.Format("第{0}步", stepIndex + 1));
  704. }
  705. else
  706. {
  707. var recipeRow = RecipeRows.First((o) => o.TechnicalName == controlName);
  708. if (recipeRow == null) continue;
  709. /*to compatiable with old recipe editor, always fill 'black space' to loop step*/
  710. if (controlName == "Loop" && string.IsNullOrEmpty(recipeRow.RecipeItems[stepIndex].Value))
  711. subNode.SetAttribute(controlName, " ");
  712. else
  713. {
  714. subNode.SetAttribute(controlName, recipeRow.RecipeItems[stepIndex].Value);
  715. //bool isJump = recipeRow.RecipeItems[stepIndex].IsJump;
  716. //if (isJump)
  717. //{
  718. // string deviceType = recipeRow.RecipeItems[stepIndex].RecipeVariableDefine.DeviceType;
  719. // if (deviceType == "MFC" || deviceType == "PC")
  720. // subNode.SetAttribute(controlName + ".IsJump", isJump.ToString());
  721. //}
  722. }
  723. }
  724. }
  725. }
  726. }
  727. return doc.OuterXml;
  728. }
  729. /// <summary>
  730. /// expand groups
  731. /// </summary>
  732. private void ExpandGroups()
  733. {
  734. try
  735. {
  736. foreach (CollectionViewGroup item in DataGridControl.Items.Groups)
  737. {
  738. DataGridControl.ExpandGroup(item);
  739. }
  740. }
  741. catch (Exception ex)
  742. {
  743. System.Diagnostics.Debug.WriteLine(ex.Message);
  744. }
  745. }
  746. /// <summary>
  747. /// collapse groups
  748. /// </summary>
  749. private void CollapseGroups()
  750. {
  751. try
  752. {
  753. foreach (CollectionViewGroup item in DataGridControl.Items.Groups)
  754. {
  755. DataGridControl.CollapseGroup(item);
  756. }
  757. }
  758. catch (Exception ex)
  759. {
  760. System.Diagnostics.Debug.WriteLine(ex.Message);
  761. }
  762. }
  763. /// <summary>
  764. /// right click context menu
  765. /// </summary>
  766. private void RightClickAction()
  767. {
  768. DataGridControl.ContextMenu = null;
  769. //get selected column information
  770. List<int> selectedColumns = new List<int>();
  771. foreach (var item in DataGridControl.SelectedCellRanges)
  772. {
  773. bool dir = item.ColumnRange.StartIndex <= item.ColumnRange.EndIndex;
  774. if (dir)
  775. {
  776. for (int i = item.ColumnRange.StartIndex; i <= item.ColumnRange.EndIndex; i++)
  777. {
  778. if (i > 0)
  779. if (!selectedColumns.Contains(i)) selectedColumns.Add(i);
  780. }
  781. }
  782. else
  783. {
  784. for (int i = item.ColumnRange.StartIndex; i >= item.ColumnRange.EndIndex; i--)
  785. {
  786. if (i > 0)
  787. if (!selectedColumns.Contains(i)) selectedColumns.Add(i);
  788. }
  789. }
  790. }
  791. selectedColumns.Sort();
  792. //debug only
  793. /*
  794. string s = "";
  795. foreach (var item in selectedColumns)
  796. {
  797. s += "," + item;
  798. }
  799. MessageBox.Show(s);
  800. * */
  801. //generate context menu
  802. ContextMenu cms = new ContextMenu();
  803. if (selectedColumns.Count > 0)
  804. {
  805. string colStrings = "";
  806. foreach (var item in selectedColumns)
  807. {
  808. if (string.IsNullOrEmpty(colStrings))
  809. colStrings = item.ToString();
  810. else
  811. colStrings += "," + item.ToString();
  812. }
  813. MenuItem mi;
  814. cms.Items.Add(new MenuItem() { Header = string.Format(" 当前选中第{0}步", colStrings), FontFamily = new FontFamily("Arial,SimSun"), IsEnabled = false, Background = Brushes.Gray, Foreground = Brushes.White });
  815. //copy
  816. mi = new MenuItem() { Header = " 复制", FontFamily = new FontFamily("Arial,SimSun"), Tag = selectedColumns.ToList() };
  817. mi.Click += (s, e) =>
  818. {
  819. try
  820. {
  821. var list = (s as MenuItem).Tag as List<int>;
  822. _copiedColumnDatas.Clear();
  823. foreach (var colId in list)
  824. {
  825. _copiedColumnDatas.Add(colId/*index from 1*/, new List<SmartCellData>());
  826. for (int i = 0; i < RecipeRows.Count; i++)
  827. {
  828. var oldCellData = RecipeRows[i].RecipeItems[colId - 1];
  829. var newCellData = new SmartCellData() { Value = oldCellData.Value, RecipeVariableDefine = oldCellData.RecipeVariableDefine };
  830. _copiedColumnDatas[colId].Add(newCellData);
  831. }
  832. }
  833. }
  834. catch (Exception ex)
  835. {
  836. System.Diagnostics.Debug.WriteLine(ex.Message);
  837. }
  838. };
  839. cms.Items.Add(mi);
  840. if (selectedColumns.Count < RecipeRows[0].RecipeItems.Count)
  841. {
  842. mi = new MenuItem() { Header = " 剪切", FontFamily = new FontFamily("Arial,SimSun"), Tag = selectedColumns.ToList() };
  843. mi.Click += (s, e) =>
  844. {
  845. try
  846. {
  847. AddUndoHistory("剪切", CloneRecipeRowData(RecipeRows));
  848. var list = (s as MenuItem).Tag as List<int>;
  849. _copiedColumnDatas.Clear();
  850. foreach (var colId in list)
  851. {
  852. _copiedColumnDatas.Add(colId/*index from 1*/, new List<SmartCellData>());
  853. for (int i = 0; i < RecipeRows.Count; i++)
  854. {
  855. var oldCellData = RecipeRows[i].RecipeItems[colId - 1];
  856. var newCellData = new SmartCellData() { Value = oldCellData.Value, RecipeVariableDefine = oldCellData.RecipeVariableDefine };
  857. _copiedColumnDatas[colId].Add(newCellData);
  858. }
  859. }
  860. foreach (var item in RecipeRows)
  861. {
  862. var collection = new ObservableCollection<SmartCellData>();
  863. for (int index = 0; index < item.RecipeItems.Count; index++)
  864. {
  865. if (list.Contains(index + 1))
  866. continue;
  867. collection.Add(item.RecipeItems[index]);
  868. }
  869. item.RecipeItems = collection;
  870. }
  871. RefreshDataGrid();
  872. RefreshCellsDisplay(false);
  873. }
  874. catch (Exception ex)
  875. {
  876. System.Diagnostics.Debug.WriteLine(ex.Message);
  877. }
  878. };
  879. cms.Items.Add(mi);
  880. mi = new MenuItem() { Header = " 删除", FontFamily = new FontFamily("Arial,SimSun"), Tag = selectedColumns.ToList() };
  881. mi.Click += (s, e) =>
  882. {
  883. try
  884. {
  885. AddUndoHistory("删除", CloneRecipeRowData(RecipeRows));
  886. var list = (s as MenuItem).Tag as List<int>;
  887. foreach (var item in RecipeRows)
  888. {
  889. var collection = new ObservableCollection<SmartCellData>();
  890. for (int index = 0; index < item.RecipeItems.Count; index++)
  891. {
  892. if (list.Contains(index + 1))
  893. continue;
  894. collection.Add(item.RecipeItems[index]);
  895. }
  896. item.RecipeItems = collection;
  897. }
  898. RefreshDataGrid();
  899. RefreshCellsDisplay(false);
  900. }
  901. catch (Exception ex)
  902. {
  903. System.Diagnostics.Debug.WriteLine(ex.Message);
  904. }
  905. };
  906. cms.Items.Add(mi);
  907. }
  908. if (selectedColumns.Count == 1 && _copiedColumnDatas.Count > 0)
  909. {
  910. mi = new MenuItem() { Header = string.Format(" 插入第{0}步后", selectedColumns[0]/*, _copiedColumnDatas.Count*/), FontFamily = new FontFamily("Arial,SimSun"), Tag = selectedColumns[0] };
  911. mi.Click += (s, e) =>
  912. {
  913. try
  914. {
  915. AddUndoHistory("插入", CloneRecipeRowData(RecipeRows));
  916. int insertColId = (int)(s as MenuItem).Tag;
  917. for (int rowIndex = 0; rowIndex < RecipeRows.Count; rowIndex++)
  918. {
  919. var collection = new ObservableCollection<SmartCellData>();
  920. for (int index = 0; index < insertColId; index++)
  921. {
  922. collection.Add(RecipeRows[rowIndex].RecipeItems[index]);
  923. }
  924. foreach (var col in _copiedColumnDatas)
  925. {
  926. collection.Add(new SmartCellData() { Value = col.Value[rowIndex].Value, RecipeVariableDefine = col.Value[rowIndex].RecipeVariableDefine });
  927. }
  928. for (int index = insertColId; index < RecipeRows[rowIndex].RecipeItems.Count; index++)
  929. {
  930. collection.Add(RecipeRows[rowIndex].RecipeItems[index]);
  931. }
  932. RecipeRows[rowIndex].RecipeItems = collection;
  933. }
  934. RefreshDataGrid();
  935. RefreshCellsDisplay(false);
  936. }
  937. catch (Exception ex)
  938. {
  939. System.Diagnostics.Debug.WriteLine(ex.Message);
  940. }
  941. };
  942. cms.Items.Add(mi);
  943. }
  944. }
  945. //show context menu
  946. DataGridControl.ContextMenu = cms;
  947. cms.Visibility = Visibility.Visible;
  948. }
  949. /// <summary>
  950. /// Parse recipe content with recipe format
  951. /// </summary>
  952. /// <param name="recipeFormat"></param>
  953. /// <param name="recipeContent"></param>
  954. /// <param name="selectedStepNo"></param>
  955. public void LoadRecipe(string recipeFormat, string recipeContent, int selectedStepNo = -1)
  956. {
  957. CurrentRunningStepNo = selectedStepNo;
  958. IsHideSameContent = false;
  959. IsRecipeModified = false;
  960. RecipeHead = new RecipeEditor.RecipeHead();
  961. DataGridControl.ContextMenu = null;
  962. RecipeInfo = "";
  963. IsBusy = true;
  964. InvokePropertyChanged("IsBusy");
  965. UndoList.Clear();
  966. RedoList.Clear();
  967. InvokePropertyChanged("UndoList");
  968. InvokePropertyChanged("RedoList");
  969. InvokePropertyChanged("IsUndoEnabled");
  970. InvokePropertyChanged("IsRedoEnabled");
  971. try
  972. {
  973. RecipeRows = new ObservableCollection<RecipeRow>();
  974. _recipeReadingFormat = new Dictionary<string, Dictionary<string, List<RecipeVariableDefine>>>();
  975. _recipeSavingFormat = new Dictionary<string, List<string>>();
  976. //parse recipe format
  977. XmlDocument formatXml = new XmlDocument();
  978. formatXml.LoadXml(recipeFormat);
  979. _currentRecipeFormatContent = formatXml.OuterXml;
  980. //reading recipe variation
  981. string recipeVariationName = formatXml.SelectSingleNode("TableRecipeFormat").Attributes["RecipeVersion"].Value;
  982. if (String.Compare(recipeVariationName, _currentRecipeVariationName) != 0)
  983. {
  984. //if variation name is different from previous loaded recipe -> clear all previous copied recipe columns
  985. _copiedColumnDatas.Clear();
  986. }
  987. _currentRecipeVariationName = recipeVariationName;
  988. //reading recipe validation releated parameters
  989. _preDefinedRecipeVars = new Dictionary<string, string>();
  990. foreach (XmlElement nd in formatXml.SelectNodes("/TableRecipeFormat/Validation/Predefine/Item"))
  991. {
  992. _preDefinedRecipeVars.Add(nd.Attributes["VarName"].Value, nd.Attributes["Value"].Value);
  993. }
  994. //reading check variables
  995. _checkVariables = new List<string>();
  996. foreach (XmlElement nd in formatXml.SelectNodes("/TableRecipeFormat/Validation/CheckVariable/Var"))
  997. {
  998. string varName = nd.Attributes["Name"].Value;
  999. _checkVariables.Add(varName);
  1000. }
  1001. //reading validation rules
  1002. _validationRules = new List<Tuple<string, string, string>>();
  1003. foreach (XmlElement nd in formatXml.SelectNodes("/TableRecipeFormat/Validation/Restriction/Rule"))
  1004. {
  1005. string varName = nd.Attributes["VarName"].Value;
  1006. string checkCondition = nd.Attributes["CheckCondition"].Value.Replace("&lt;", "<").Replace("&gt;", ">");
  1007. string message = nd.Attributes["Message"].Value.Replace("'", "\"");
  1008. _validationRules.Add(new Tuple<string, string, string>(varName, checkCondition, message));
  1009. }
  1010. //parsing recipe format xml file
  1011. foreach (XmlElement catalogNode in formatXml.SelectNodes("/TableRecipeFormat/Catalog"))
  1012. {
  1013. string catalogName = catalogNode.Attributes["DisplayName"].Value;
  1014. _recipeReadingFormat.Add(catalogName, new Dictionary<string, List<RecipeVariableDefine>>());
  1015. foreach (XmlElement groupNode in catalogNode.SelectNodes("Group"))
  1016. {
  1017. string groupName = groupNode.Attributes["DisplayName"].Value;
  1018. _recipeReadingFormat[catalogName].Add(groupName, new List<RecipeVariableDefine>());
  1019. foreach (XmlElement stepNode in groupNode.SelectNodes("Step"))
  1020. {
  1021. string stepModuleName = stepNode.Attributes["ModuleName"].Value;
  1022. string stepDeviceType = stepNode.Attributes["DeviceType"].Value;
  1023. string stepDisplayName = stepNode.Attributes["DisplayName"].Value;
  1024. string stepControlName = stepNode.Attributes["ControlName"].Value;
  1025. string stepInputType = stepNode.Attributes["InputType"].Value;
  1026. string stepDescription = stepNode.HasAttribute("Desc") ? stepNode.Attributes["Desc"].Value : "";
  1027. double stepMin = double.Parse(stepNode.HasAttribute("Min") ? stepNode.Attributes["Min"].Value : "0");
  1028. double stepMax = double.Parse(stepNode.HasAttribute("Max") ? stepNode.Attributes["Max"].Value : "0");
  1029. var selectionList = new List<Tuple<string, string>>();
  1030. foreach (XmlElement selectionNode in stepNode.SelectNodes("Item"))
  1031. {
  1032. selectionList.Add(new Tuple<string, string>(selectionNode.Attributes["ControlName"].Value, selectionNode.Attributes["DisplayName"].Value));
  1033. }
  1034. if (!_recipeSavingFormat.ContainsKey(stepModuleName)) _recipeSavingFormat.Add(stepModuleName, new List<string>());
  1035. _recipeSavingFormat[stepModuleName].Add(stepControlName);
  1036. if (stepControlName == "StepNo")
  1037. continue;
  1038. _recipeReadingFormat[catalogName][groupName].Add(new RecipeVariableDefine()
  1039. {
  1040. CellType = (CellType)Enum.Parse(typeof(CellType), stepInputType),
  1041. Description = stepDescription,
  1042. DeviceType = stepDeviceType,
  1043. DropdownItemList = selectionList,
  1044. MaxValue = stepMax,
  1045. //MinValue = stepDeviceType.Equals("MFC",StringComparison.InvariantCultureIgnoreCase)? stepMax*2.0/100: stepMin,
  1046. MinValue = stepMin,
  1047. GroupName = groupName,
  1048. CatalogName = catalogName,
  1049. TechnicalName = stepControlName,
  1050. FriendlyName = stepDisplayName
  1051. });
  1052. }
  1053. }
  1054. }
  1055. //parse recipe content
  1056. XmlDocument contentXml = new XmlDocument();
  1057. contentXml.LoadXml(recipeContent);
  1058. contentXml.DocumentElement.SetAttribute("RecipeVersion", _currentRecipeVariationName);
  1059. //read recipe head
  1060. //em. RecipeVersion="Ace" CreatedBy="tech" CreationTime="2013-02-02T12:36:02" LastRevisedBy="Peter" LastRevisionTime="2013-10-22T13:30:29" Description="5e46af80-49f9-4b4f-b04b-bc911fb292f8"
  1061. RecipeHead.CreatedBy = contentXml.DocumentElement.HasAttribute("CreatedBy") ? contentXml.DocumentElement.Attributes["CreatedBy"].Value : "(无)";
  1062. RecipeHead.CreationTime = contentXml.DocumentElement.HasAttribute("CreationTime") ? contentXml.DocumentElement.Attributes["CreationTime"].Value : "(无)";
  1063. RecipeHead.LastModifiedBy = contentXml.DocumentElement.HasAttribute("LastRevisedBy") ? contentXml.DocumentElement.Attributes["LastRevisedBy"].Value : "(无)";
  1064. RecipeHead.LastRevisionTime = contentXml.DocumentElement.HasAttribute("LastRevisionTime") ? contentXml.DocumentElement.Attributes["LastRevisionTime"].Value : "(无)";
  1065. if (contentXml.DocumentElement.HasAttribute("PressureMode"))
  1066. {
  1067. RecipeHead.PressureMode = contentXml.DocumentElement.Attributes["PressureMode"].Value;
  1068. }
  1069. if (contentXml.DocumentElement.HasAttribute("BasePressure"))
  1070. {
  1071. RecipeHead.BasePressure = contentXml.DocumentElement.Attributes["BasePressure"].Value;
  1072. }
  1073. if (contentXml.DocumentElement.HasAttribute("PumpDownLimit"))
  1074. {
  1075. RecipeHead.PumpDownLimit = contentXml.DocumentElement.Attributes["PumpDownLimit"].Value;
  1076. }
  1077. if (contentXml.DocumentElement.HasAttribute("SubstrateTemp"))
  1078. {
  1079. RecipeHead.SubstrateTemp = contentXml.DocumentElement.Attributes["SubstrateTemp"].Value;
  1080. }
  1081. if (contentXml.DocumentElement.HasAttribute("PumpingPinState"))
  1082. {
  1083. RecipeHead.PumpingPinState = contentXml.DocumentElement.Attributes["PumpingPinState"].Value;
  1084. }
  1085. if(contentXml.DocumentElement.HasAttribute("PinDownPressure"))
  1086. {
  1087. RecipeHead.PinDownPressure = contentXml.DocumentElement.Attributes["PinDownPressure"].Value;
  1088. }
  1089. if(contentXml.DocumentElement.HasAttribute("VentingPinState"))
  1090. {
  1091. RecipeHead.VentingPinState = contentXml.DocumentElement.Attributes["VentingPinState"].Value;
  1092. }
  1093. if (contentXml.DocumentElement.HasAttribute("PurgeActive"))
  1094. {
  1095. RecipeHead.PurgeActive = contentXml.DocumentElement.Attributes["PurgeActive"].Value;
  1096. }
  1097. if (contentXml.DocumentElement.HasAttribute("NotToPurgeOrVent"))
  1098. {
  1099. RecipeHead.NotToPurgeOrVent = contentXml.DocumentElement.Attributes["NotToPurgeOrVent"].Value;
  1100. }
  1101. if (contentXml.DocumentElement.HasAttribute("Barcode"))
  1102. {
  1103. RecipeHead.Barcode = contentXml.DocumentElement.Attributes["Barcode"].Value;
  1104. }
  1105. RecipeHead.RecipeVariation = contentXml.DocumentElement.HasAttribute("RecipeVersion") ? contentXml.DocumentElement.Attributes["RecipeVersion"].Value : "(NULL)";
  1106. RecipeHead.Description = contentXml.DocumentElement.HasAttribute("Description") ? contentXml.DocumentElement.Attributes["Description"].Value : "(NULL)";
  1107. var allRecipeItems = new List<Dictionary<string, string>>();
  1108. foreach (XmlElement stepNode in contentXml.SelectNodes("/TableRecipeData/Step"))
  1109. {
  1110. var stepDic = new Dictionary<string, string>();
  1111. allRecipeItems.Add(stepDic);
  1112. foreach (XmlAttribute att in stepNode.Attributes)
  1113. {
  1114. stepDic.Add(att.Name, att.Value);
  1115. }
  1116. foreach (XmlElement innerStep in stepNode.ChildNodes)
  1117. {
  1118. foreach (XmlAttribute att in innerStep.Attributes)
  1119. {
  1120. stepDic.Add(att.Name, att.Value);
  1121. }
  1122. foreach (XmlElement innerInnerStep in innerStep.ChildNodes)
  1123. {
  1124. foreach (XmlAttribute att in innerInnerStep.Attributes)
  1125. {
  1126. stepDic.Add(att.Name, att.Value);
  1127. }
  1128. }
  1129. }
  1130. }
  1131. //generate view model
  1132. RowVarNameDic = new Dictionary<string, int>();
  1133. int rowIndex = 0;
  1134. foreach (var catalog in _recipeReadingFormat.Keys)
  1135. {
  1136. foreach (var group in _recipeReadingFormat[catalog].Keys)
  1137. {
  1138. foreach (var var1 in _recipeReadingFormat[catalog][group])
  1139. {
  1140. var singleRow = new RecipeRow() { CatalogName = catalog, FriendlyName = /*group + */var1.FriendlyName, TechnicalName = var1.TechnicalName };
  1141. for (int stepNo = 0; stepNo < allRecipeItems.Count; stepNo++)
  1142. {
  1143. var stepCell = new SmartCellData() { RecipeVariableDefine = var1 };
  1144. if (allRecipeItems[stepNo].ContainsKey(var1.TechnicalName))
  1145. {
  1146. stepCell.Value = allRecipeItems[stepNo][var1.TechnicalName];
  1147. //stepCell.ShowsJumpControl = false;
  1148. //if (var1.CellType == CellType.NumInput)
  1149. //{
  1150. // if (var1.DeviceType == "MFC" || var1.DeviceType == "PC")
  1151. // {
  1152. // string jumpString = var1.TechnicalName + ".IsJump";
  1153. // stepCell.IsJump = allRecipeItems[stepNo].ContainsKey(jumpString) ? bool.Parse(allRecipeItems[stepNo][jumpString]) : false;
  1154. // stepCell.ShowsJumpControl = true;
  1155. // }
  1156. //}
  1157. }
  1158. else
  1159. stepCell.Value = "n/a";
  1160. singleRow.RecipeItems.Add(stepCell);
  1161. }
  1162. RecipeRows.Add(singleRow);
  1163. RowVarNameDic.Add(var1.TechnicalName, rowIndex++);
  1164. }
  1165. }
  1166. }
  1167. //refresh datagrid
  1168. RefreshDataGrid();
  1169. //refresh recipe information
  1170. RefreshCellsDisplay();
  1171. if (OnLoadRecipeContent != null)
  1172. OnLoadRecipeContent.Invoke(recipeContent, null);
  1173. }
  1174. catch (Exception ex)
  1175. {
  1176. System.Diagnostics.Debug.WriteLine(ex.Message);
  1177. //LOG.Write("", ex);
  1178. }
  1179. IsBusy = false;
  1180. InvokePropertyChanged("IsBusy");
  1181. }
  1182. /// <summary>
  1183. /// 检查变量ramp rate
  1184. /// </summary>
  1185. /// <param name="stepNo"></param>
  1186. /// <param name="rampEnable"></param>
  1187. /// <param name="varName"></param>
  1188. /// <param name="rampTime"></param>
  1189. /// <param name="maxRampUpRate"></param>
  1190. /// <param name="maxRampDownRate"></param>
  1191. /// <returns>False:check ok, True: check failed</returns>
  1192. public bool CheckRampRate(int stepNo, string rampEnable, string varName, string rampTime, double maxRampUpRate, double maxRampDownRate)
  1193. {
  1194. try
  1195. {
  1196. if (stepNo <= 0) return false;
  1197. int rowIndex = RowVarNameDic[varName];
  1198. double currentValue = double.Parse(RecipeRows[rowIndex].RecipeItems[stepNo].Value);
  1199. //if (varName == "AZone.Setpoint" || varName == "BZone.Setpoint" || varName == "CZone.Setpoint" || varName == "DZone.Setpoint")
  1200. //{
  1201. // int heatControlModeIndex = RowVarNameDic["Heater.Mode"];
  1202. // string curStepHeatCtrlMode = RecipeRows[heatControlModeIndex].RecipeItems[stepNo].Value;
  1203. // string lastStepHeatCtrlMode = RecipeRows[heatControlModeIndex].RecipeItems[stepNo - 1].Value;
  1204. // if (curStepHeatCtrlMode != lastStepHeatCtrlMode)
  1205. // {
  1206. // if (!(lastStepHeatCtrlMode.Equals("CurrentControl") && curStepHeatCtrlMode.Equals("PyroTempControl")))
  1207. // return false;
  1208. // int endbyIndex = RowVarNameDic["EndBy"];
  1209. // int endValueIndex = RowVarNameDic["EndValue"];
  1210. // string endby = RecipeRows[endbyIndex].RecipeItems[stepNo - 1].Value;
  1211. // EndByCondition endbyEnum;
  1212. // if (!Enum.TryParse(endby, out endbyEnum)) return false;
  1213. // if (endbyEnum != EndByCondition.PmTempGt && endbyEnum != EndByCondition.PmTempLt) return false;
  1214. // string end = RecipeRows[endValueIndex].RecipeItems[stepNo - 1].Value;
  1215. // double endValue;
  1216. // if (!double.TryParse(end, out endValue)) return false;
  1217. // return CheckRampRate(rampEnable, rampTime, maxRampUpRate, maxRampDownRate, endValue, currentValue);
  1218. // }
  1219. //}
  1220. double prevValue = double.Parse(RecipeRows[rowIndex].RecipeItems[stepNo - 1].Value);
  1221. return CheckRampRate(rampEnable, rampTime, maxRampUpRate, maxRampDownRate, prevValue, currentValue);
  1222. }
  1223. catch (Exception ex)
  1224. {
  1225. System.Diagnostics.Debug.WriteLine(ex.Message);
  1226. return true;
  1227. }
  1228. }
  1229. bool CheckRampRate(string rampEnable, string rampTime, double maxRampUpRate, double maxRampDownRate, double prevValue, double currentValue)
  1230. {
  1231. bool isRampEnable = bool.Parse(rampEnable);
  1232. //string[] timeStr = rampTime.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
  1233. //string tt = string.Join(":", timeStr);
  1234. TimeSpan timeSpan;
  1235. TimeSpan.TryParse(rampTime, out timeSpan);
  1236. double totalTimeSec = timeSpan.TotalSeconds;
  1237. double diff = currentValue - prevValue;
  1238. if (!isRampEnable || totalTimeSec <= 0)
  1239. {
  1240. if (diff != 0) return true;
  1241. return false;
  1242. }
  1243. else
  1244. {
  1245. double rampRate = diff / totalTimeSec;
  1246. return (rampRate > 0 && rampRate >= maxRampUpRate) || (rampRate < 0 && rampRate <= -maxRampDownRate);
  1247. }
  1248. }
  1249. /// <summary>
  1250. /// Refresh datagrid cell data display
  1251. /// </summary>
  1252. /// <param name="moving2RunningStepPosition">True: moving to current running step position</param>
  1253. public void RefreshCellsDisplay(bool moving2RunningStepPosition = true)
  1254. {
  1255. try
  1256. {
  1257. if (RecipeRows == null || RecipeRows.Count < 2)
  1258. return;
  1259. Errors = new List<Tuple<int, int, string, string>>();
  1260. Dictionary<int, string> dicEndby = new Dictionary<int, string>();
  1261. Dictionary<int, string> dicPressureMode = new Dictionary<int, string>();
  1262. Dictionary<int, string> dicRfMode = new Dictionary<int, string>();
  1263. Dictionary<int, string> dicRfMatchProcessMode = new Dictionary<int, string>();
  1264. Dictionary<int, string> dicSetMatchPositionC1 = new Dictionary<int, string>();
  1265. Dictionary<int, string> dicSetMatchPositionC2 = new Dictionary<int, string>();
  1266. for (int i = 0; i < RecipeRows.Count; i++)
  1267. {
  1268. for (int j = 0; j < RecipeRows[i].RecipeItems.Count; j++)
  1269. {
  1270. var cell = RecipeRows[i].RecipeItems[j];
  1271. cell.RowIndex = i;
  1272. cell.ColIndex = j;
  1273. cell.ErrInfo = string.Empty;
  1274. bool logicEnable = true;
  1275. if (cell.RecipeVariableDefine.TechnicalName == "EndBy")
  1276. dicEndby[j] = cell.Value;
  1277. if (cell.RecipeVariableDefine.TechnicalName == "ThrottleValve.SetMode")
  1278. {
  1279. dicPressureMode[j] = cell.Value;
  1280. }
  1281. if (cell.RecipeVariableDefine.TechnicalName == "PressureControl.SetTVMode")
  1282. {
  1283. dicPressureMode[j] = cell.Value;
  1284. }
  1285. if (cell.RecipeVariableDefine.TechnicalName == "Rf.SetMode")
  1286. dicRfMode[j] = cell.Value;
  1287. if (cell.RecipeVariableDefine.TechnicalName == "Match.SetMatchProcessMode")
  1288. dicRfMatchProcessMode[j] = cell.Value;
  1289. if (cell.RecipeVariableDefine.TechnicalName == "Match.SetMatchPositionC1")
  1290. dicSetMatchPositionC1[j] = cell.Value;
  1291. if (cell.RecipeVariableDefine.TechnicalName == "Match.SetMatchPositionC2")
  1292. dicSetMatchPositionC2[j] = cell.Value;
  1293. if (cell.RecipeVariableDefine.TechnicalName == "Time")
  1294. {
  1295. logicEnable = dicEndby.ContainsKey(j) && (dicEndby[j] == "EndByStepTime" ||
  1296. dicEndby[j] == "EndByHeatUp" ||
  1297. dicEndby[j] == "EndByEndPoint");
  1298. }
  1299. if (cell.RecipeVariableDefine.TechnicalName == "ThrottleValve.SetPosition")
  1300. {
  1301. logicEnable = dicPressureMode.ContainsKey(j) && dicPressureMode[j] == "TVPositionCtrl";
  1302. }
  1303. if (cell.RecipeVariableDefine.TechnicalName == "ThrottleValve.SetPressure")
  1304. {
  1305. logicEnable = dicPressureMode.ContainsKey(j) && dicPressureMode[j] == "TVPressureCtrl";
  1306. }
  1307. if (cell.RecipeVariableDefine.TechnicalName == "PressureControl.SetTVPosition")
  1308. {
  1309. logicEnable = dicPressureMode.ContainsKey(j) && dicPressureMode[j] == "TVPositionCtrl";
  1310. }
  1311. if (cell.RecipeVariableDefine.TechnicalName == "PressureControl.SetTVPressure")
  1312. {
  1313. logicEnable = dicPressureMode.ContainsKey(j) && dicPressureMode[j] == "TVPressureCtrl";
  1314. }
  1315. if (cell.RecipeVariableDefine.TechnicalName == "Rf.SetPulsingFrequency")
  1316. {
  1317. logicEnable = dicRfMode.ContainsKey(j) && dicRfMode[j] == "PulsingMode";
  1318. }
  1319. if (cell.RecipeVariableDefine.TechnicalName == "Rf.SetPulsingDuty")
  1320. {
  1321. logicEnable = dicRfMode.ContainsKey(j) && dicRfMode[j] == "PulsingMode";
  1322. }
  1323. if (cell.RecipeVariableDefine.TechnicalName == "Rf.SetPowerOnTime")
  1324. {
  1325. logicEnable = dicEndby.ContainsKey(j) && dicEndby[j] == "EndByRfTime";
  1326. }
  1327. if (cell.RecipeVariableDefine.TechnicalName == "EPD.SetConfig")
  1328. {
  1329. logicEnable = dicEndby.ContainsKey(j) && dicEndby[j] == "EndByEndPoint";
  1330. if (string.IsNullOrEmpty(cell.Value) || cell.Value.StartsWith("n/a"))
  1331. cell.Value = _defaultEndPointValue;
  1332. }
  1333. if (cell.RecipeVariableDefine.TechnicalName == "Match.SetMatchProcessMode")
  1334. {
  1335. logicEnable = dicRfMatchProcessMode.ContainsKey(j);// && dicRfMatchProcessMode[j] == "TritonPresetMode";
  1336. }
  1337. if (cell.RecipeVariableDefine.TechnicalName == "Match.SetMatchPositionC1")
  1338. {
  1339. logicEnable = dicSetMatchPositionC1.ContainsKey(j);// && dicRfMatchProcessMode[j] == "TritonPresetMode";
  1340. }
  1341. if (cell.RecipeVariableDefine.TechnicalName == "Match.SetMatchPositionC2")
  1342. {
  1343. logicEnable = dicSetMatchPositionC2.ContainsKey(j);// && dicRfMatchProcessMode[j] == "TritonPresetMode";
  1344. }
  1345. cell.IsMasked = !logicEnable;
  1346. //update diff variable numbers
  1347. if (cell.RecipeVariableDefine.TechnicalName == "Ramp")
  1348. {
  1349. //更新当前步骤中Ramp的变量数据
  1350. if (j == 0)
  1351. {
  1352. cell.Tag = 0;
  1353. }
  1354. else
  1355. {
  1356. int rampNum = 0;
  1357. for (int s1 = 0; s1 < RecipeRows.Count; s1++)
  1358. {
  1359. if (RecipeRows[s1].CatalogName == "StepInfo")// RecipeRows[s1].RecipeItems[j].RecipeVariableDefine.CellType == CellType.ReadOnly)
  1360. continue;
  1361. string preValue = RecipeRows[s1].RecipeItems[j - 1].Value;
  1362. string curValue = RecipeRows[s1].RecipeItems[j].Value;
  1363. if (RecipeRows[s1].RecipeItems[j].RecipeVariableDefine.CellType == CellType.NumInput)
  1364. {
  1365. double pd, cd;
  1366. if (double.TryParse(preValue, out pd) && double.TryParse(curValue, out cd))
  1367. if (pd != cd) rampNum++;
  1368. }
  1369. else if (String.Compare(preValue, curValue, false) != 0)
  1370. {
  1371. rampNum++;
  1372. }
  1373. }
  1374. cell.Tag = rampNum;
  1375. }
  1376. cell.InvokePropertyChanged();
  1377. }
  1378. #region mask (hide or show cell content)
  1379. if ((MaskedTechNames != null && MaskedTechNames.Contains(cell.RecipeVariableDefine.TechnicalName)) ||
  1380. (MaskedCatalogNames != null && MaskedCatalogNames.Contains(cell.RecipeVariableDefine.CatalogName)) || !logicEnable)
  1381. cell.IsMasked = true;
  1382. else
  1383. cell.IsMasked = false;
  1384. #endregion mask (hide or show cell content)
  1385. #region check cell data range
  1386. switch (cell.RecipeVariableDefine.CellType)
  1387. {
  1388. case CellType.CheckBox:
  1389. {
  1390. if (string.Compare(cell.Value, "true", true) == 0 || string.Compare(cell.Value, "false", true) == 0)
  1391. {
  1392. cell.ErrInfo = "";
  1393. cell.Background = Brushes.Transparent;
  1394. }
  1395. else
  1396. {
  1397. string reason = string.Format("Value '{0}' not valid", cell.Value);
  1398. Errors.Add(new Tuple<int, int, string, string>(i, j, cell.RecipeVariableDefine.FriendlyName, reason));
  1399. cell.ErrInfo = reason;
  1400. cell.Background = Brushes.Pink;
  1401. }
  1402. }
  1403. break;
  1404. case CellType.EditableSelection:
  1405. {
  1406. cell.ErrInfo = "";
  1407. cell.Background = Brushes.Transparent;
  1408. }
  1409. break;
  1410. case CellType.NumInput:
  1411. {
  1412. double min = cell.RecipeVariableDefine.MinValue;
  1413. double max = cell.RecipeVariableDefine.MaxValue;
  1414. double v;
  1415. if (!double.TryParse(cell.Value, out v))
  1416. {
  1417. string reason = string.Format("Value '{0}' not valid", cell.Value);
  1418. Errors.Add(new Tuple<int, int, string, string>(i, j, cell.RecipeVariableDefine.FriendlyName, reason));
  1419. cell.ErrInfo = reason;
  1420. cell.Background = Brushes.Pink;
  1421. }
  1422. else if (v > max || v < 0 || (v < min && v > max * 0.1 / 100))
  1423. {
  1424. string reason = string.Format("Value'{0}',Out of Range {1}~{2}", cell.Value, min, max);
  1425. Errors.Add(new Tuple<int, int, string, string>(i, j, cell.RecipeVariableDefine.FriendlyName, reason));
  1426. cell.ErrInfo = reason;
  1427. cell.Background = Brushes.Pink;
  1428. }
  1429. else
  1430. {
  1431. cell.ErrInfo = "";
  1432. cell.Background = Brushes.Transparent;
  1433. }
  1434. }
  1435. break;
  1436. case CellType.ReadOnlySelection:
  1437. {
  1438. if (cell.RecipeVariableDefine.DropdownItemList != null && cell.RecipeVariableDefine.DropdownItemList.Find((o) => o.Item1 == cell.Value) != null)
  1439. {
  1440. cell.ErrInfo = "";
  1441. cell.Background = Brushes.Transparent;
  1442. }
  1443. else
  1444. {
  1445. string reason = string.Format("Value'{0}' is not valid", cell.Value);
  1446. Errors.Add(new Tuple<int, int, string, string>(i, j, cell.RecipeVariableDefine.FriendlyName, reason));
  1447. cell.ErrInfo = reason;
  1448. cell.Background = Brushes.Pink;
  1449. }
  1450. }
  1451. break;
  1452. case CellType.ReadOnly:
  1453. case CellType.TextInput:
  1454. cell.ErrInfo = "";
  1455. cell.Background = Brushes.Transparent;
  1456. break;
  1457. case CellType.TimeInput:
  1458. {
  1459. string[] arr = cell.Value.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
  1460. int h, mi, s;
  1461. if (arr.Length == 3 && int.TryParse(arr[0], out h) && int.TryParse(arr[1], out mi) && int.TryParse(arr[2], out s) && h >= 0 && mi >= 0 && mi <= 59 && s >= 0 && s <= 59)
  1462. {
  1463. cell.ErrInfo = "";
  1464. cell.Background = Brushes.Transparent;
  1465. }
  1466. else
  1467. {
  1468. string reason = string.Format("value'{0}' is not valid", cell.Value);
  1469. Errors.Add(new Tuple<int, int, string, string>(i, j, cell.RecipeVariableDefine.FriendlyName, reason));
  1470. cell.ErrInfo = reason;
  1471. cell.Background = Brushes.Pink;
  1472. }
  1473. }
  1474. break;
  1475. }
  1476. #endregion check cell data range
  1477. #region mark data trend / hide same content
  1478. if (j == 0) //step one
  1479. {
  1480. cell.Foreground = Brushes.Black;
  1481. cell.FontWeight = FontWeights.Normal;
  1482. cell.IsHidden = false;
  1483. cell.InvokePropertyChanged();
  1484. cell.IsMasked = !logicEnable;
  1485. continue;
  1486. }
  1487. var preCell = RecipeRows[i].RecipeItems[j - 1];
  1488. if (cell.RecipeVariableDefine.CellType == CellType.NumInput)
  1489. {
  1490. double preValue = 0;
  1491. double.TryParse(preCell.Value.ToString(), out preValue);
  1492. double curValue = 0;
  1493. double.TryParse(cell.Value.ToString(), out curValue);
  1494. if (curValue > preValue)
  1495. {
  1496. cell.Foreground = Brushes.Red;
  1497. cell.FontWeight = FontWeights.Bold;
  1498. }
  1499. else if (curValue < preValue)
  1500. {
  1501. cell.Foreground = Brushes.Blue;
  1502. cell.FontWeight = FontWeights.Bold;
  1503. }
  1504. else
  1505. {
  1506. cell.Foreground = Brushes.Black;
  1507. cell.FontWeight = FontWeights.Normal;
  1508. }
  1509. }
  1510. else
  1511. {
  1512. //not number type
  1513. cell.Foreground = Brushes.Black;
  1514. cell.FontWeight = FontWeights.Normal;
  1515. }
  1516. if (IsHideSameContent && cell.Value == preCell.Value)
  1517. cell.IsHidden = true;
  1518. else
  1519. cell.IsHidden = false;
  1520. //!logicEnable;
  1521. cell.IsMasked = !logicEnable;
  1522. //if (!logicEnable)
  1523. //{
  1524. // cell.Background = Brushes.DarkGray;
  1525. // cell.IsMasked = true;
  1526. //}
  1527. #endregion mark data trend / hide same content
  1528. cell.InvokePropertyChanged();
  1529. }
  1530. }
  1531. #region check loop
  1532. int loopRowId = -1;
  1533. for (int i = 0; i < RecipeRows.Count; i++)
  1534. {
  1535. if (RecipeRows[i].TechnicalName == "Loop")
  1536. {
  1537. loopRowId = i;
  1538. break;
  1539. }
  1540. }
  1541. for (int j = 0; j < RecipeRows[loopRowId].RecipeItems.Count; j++)
  1542. {
  1543. var cell = RecipeRows[loopRowId].RecipeItems[j];
  1544. bool isLoopStart = Regex.IsMatch(cell.Value, @"^Loop\x20\d+$");
  1545. bool isLoopEnd = Regex.IsMatch(cell.Value, @"^Loop End$");
  1546. bool isNullOrEmpty = string.IsNullOrWhiteSpace(cell.Value);
  1547. if (!isLoopEnd && !isLoopStart && !isNullOrEmpty)
  1548. {
  1549. string reason = string.Format("Value '{0}' not valid", cell.Value);
  1550. cell.ErrInfo = reason;
  1551. cell.Background = Brushes.Pink;
  1552. Errors.Add(new Tuple<int, int, string, string>(loopRowId, j, cell.RecipeVariableDefine.FriendlyName, reason));
  1553. }
  1554. if (isLoopEnd)
  1555. {
  1556. string reason = "Loop Start 缺失";
  1557. cell.ErrInfo = reason;
  1558. cell.Background = Brushes.Pink;
  1559. Errors.Add(new Tuple<int, int, string, string>(loopRowId, j, cell.RecipeVariableDefine.FriendlyName, reason));
  1560. }
  1561. else if (isLoopStart)
  1562. {
  1563. for (int k = j + 1; k < RecipeRows[loopRowId].RecipeItems.Count; k++)
  1564. {
  1565. cell = RecipeRows[loopRowId].RecipeItems[k];
  1566. bool isCurStepLoopStart = Regex.IsMatch(cell.Value, @"^Loop\x20\d+$");
  1567. bool isCurStepLoopEnd = Regex.IsMatch(cell.Value, @"^Loop End$");
  1568. isNullOrEmpty = string.IsNullOrWhiteSpace(cell.Value);
  1569. if (!isCurStepLoopEnd && !isCurStepLoopStart && !isNullOrEmpty)
  1570. {
  1571. string reason = string.Format("Value '{0}' not valid", cell.Value);
  1572. cell.ErrInfo = reason;
  1573. cell.Background = Brushes.Pink;
  1574. Errors.Add(new Tuple<int, int, string, string>(loopRowId, k, cell.RecipeVariableDefine.FriendlyName, reason));
  1575. }
  1576. else if (isCurStepLoopStart)
  1577. {
  1578. string reason = "前面循环没有结束,不能设置新的Loop Start标志";
  1579. cell.ErrInfo = reason;
  1580. cell.Background = Brushes.Pink;
  1581. Errors.Add(new Tuple<int, int, string, string>(loopRowId, k, cell.RecipeVariableDefine.FriendlyName, reason));
  1582. }
  1583. else if (isCurStepLoopEnd)
  1584. {
  1585. //mark loop steps with blue background
  1586. for (int m1 = j; m1 <= k; m1++)
  1587. {
  1588. var curCell = RecipeRows[loopRowId].RecipeItems[m1];
  1589. if (curCell.Background == Brushes.Transparent)
  1590. curCell.Background = Brushes.LightGreen;
  1591. curCell.InvokePropertyChanged();
  1592. }
  1593. j = k;
  1594. break;
  1595. }
  1596. if (k == RecipeRows[loopRowId].RecipeItems.Count - 1)
  1597. {
  1598. j = k;
  1599. string reason = "Loop End 缺失";
  1600. cell.ErrInfo = reason;
  1601. cell.Background = Brushes.Pink;
  1602. Errors.Add(new Tuple<int, int, string, string>(loopRowId, k, cell.RecipeVariableDefine.FriendlyName, reason));
  1603. }
  1604. }
  1605. }
  1606. }
  1607. #endregion check loop
  1608. #region recipe parameter validation
  1609. //using (var lua = new LuaInterface.Lua())
  1610. //{
  1611. // //is special recipe?
  1612. // //bool IsSpecialRecipe = true;
  1613. // //{
  1614. // // int heaterModeRowIndex = RowVarNameDic["Heater.Mode"];
  1615. // // int aZoneSetpointIndex = RowVarNameDic["AZone.Setpoint"];
  1616. // // int bZoneSetpointIndex = RowVarNameDic["BZone.Setpoint"];
  1617. // // int cZoneSetpointIndex = RowVarNameDic["CZone.Setpoint"];
  1618. // // int dZoneSetpointIndex = RowVarNameDic.ContainsKey("DZone.Setpoint") ? RowVarNameDic["DZone.Setpoint"] : aZoneSetpointIndex;
  1619. // // for (int stepIndex = 0; stepIndex < RecipeRows[0].RecipeItems.Count; stepIndex++)
  1620. // // {
  1621. // // if (RecipeRows[heaterModeRowIndex].RecipeItems[stepIndex].Value != "CurrentControl" ||
  1622. // // RecipeRows[aZoneSetpointIndex].RecipeItems[stepIndex].Value != "0" ||
  1623. // // RecipeRows[bZoneSetpointIndex].RecipeItems[stepIndex].Value != "0" ||
  1624. // // RecipeRows[cZoneSetpointIndex].RecipeItems[stepIndex].Value != "0" ||
  1625. // // RecipeRows[dZoneSetpointIndex].RecipeItems[stepIndex].Value != "0")
  1626. // // {
  1627. // // IsSpecialRecipe = false;
  1628. // // break;
  1629. // // }
  1630. // // }
  1631. // //}
  1632. // ////set get ramp rate function
  1633. // //lua.RegisterFunction("CheckRampRate", this, GetType().GetMethod("CheckRampRate"));
  1634. // //lua.DoString(string.Format("IsProductionRecipe={0};",(!IsSpecialRecipe).ToString().ToLower()));
  1635. // for (int stepIndex = 0; stepIndex < RecipeRows[0].RecipeItems.Count; stepIndex++)
  1636. // {
  1637. // //set stepNo
  1638. // lua.DoString(string.Format("StepNo={0};", stepIndex));
  1639. // //reading var from current recipe step
  1640. // foreach (var checkVar in _checkVariables)
  1641. // {
  1642. // if (!RowVarNameDic.ContainsKey(checkVar))
  1643. // {
  1644. // System.Diagnostics.Debug.WriteLine("检查不到变量定义," + checkVar);
  1645. // continue;
  1646. // }
  1647. // try
  1648. // {
  1649. // int varId = RowVarNameDic[checkVar];
  1650. // if (RecipeRows[varId].RecipeItems[stepIndex].RecipeVariableDefine.CellType == CellType.NumInput)
  1651. // lua.DoString(string.Format("{0}={1};", RecipeRows[varId].RecipeItems[stepIndex].RecipeVariableDefine.TechnicalName.Replace(".", "_"), RecipeRows[varId].RecipeItems[stepIndex].Value));
  1652. // else
  1653. // lua.DoString(string.Format("{0}=\"{1}\";", RecipeRows[varId].RecipeItems[stepIndex].RecipeVariableDefine.TechnicalName.Replace(".", "_"), RecipeRows[varId].RecipeItems[stepIndex].Value));
  1654. // }
  1655. // catch (Exception ex)
  1656. // {
  1657. // System.Diagnostics.Debug.WriteLine("校验异常," + ex);
  1658. // }
  1659. // }
  1660. // //reading from recipe format file
  1661. // foreach (string key in _preDefinedRecipeVars.Keys)
  1662. // {
  1663. // string varValueString = _preDefinedRecipeVars[key];
  1664. // double varValue;
  1665. // if (double.TryParse(varValueString, out varValue))
  1666. // lua.DoString(string.Format("{0}={1};", key, varValue));
  1667. // else
  1668. // lua.DoString(string.Format("{0}=\"{1}\";", key, varValueString));
  1669. // }
  1670. // //do valation
  1671. // foreach (var rule in _validationRules)
  1672. // {
  1673. // lua.DoString(string.Format("if {0} then hasErr=1 else hasErr=0 end", rule.Item2));
  1674. // bool hasError = ((int)lua.GetNumber("hasErr")) == 1;
  1675. // if (hasError)
  1676. // {
  1677. // lua.DoString(string.Format("message=string.format({0});", rule.Item3));
  1678. // string reason = lua.GetString("message");
  1679. // var rowId = RowVarNameDic[rule.Item1];
  1680. // var cell = RecipeRows[rowId].RecipeItems[stepIndex];
  1681. // cell.ErrInfo = reason;
  1682. // cell.Background = Brushes.Pink;
  1683. // Errors.Add(new Tuple<int, int, string, string>(rowId, stepIndex, cell.RecipeVariableDefine.FriendlyName, reason));
  1684. // cell.InvokePropertyChanged();
  1685. // }
  1686. // }
  1687. // }
  1688. //}
  1689. #endregion recipe parameter validation
  1690. #region update material cell data
  1691. int materialRowId = -1;
  1692. for (int colId = 0; colId < RecipeRows[0].RecipeItems.Count; colId++)
  1693. {
  1694. string materialName = "";
  1695. for (int rowId = 0; rowId < RecipeRows.Count; rowId++)
  1696. {
  1697. string curMo = "";
  1698. if (materialRowId == -1 && RecipeRows[rowId].RecipeItems[colId].RecipeVariableDefine.TechnicalName == "Material")
  1699. {
  1700. materialRowId = rowId;
  1701. }
  1702. var cell = RecipeRows[rowId].RecipeItems[colId];
  1703. if (cell.RecipeVariableDefine.CellType == CellType.ReadOnlySelection && String.Compare(cell.Value, "flow", true) == 0)
  1704. {
  1705. string moName = cell.RecipeVariableDefine.TechnicalName.Split('.')[0].ToLower();
  1706. string displayName = cell.RecipeVariableDefine.FriendlyName.Replace("_", ".").Split('.')[0].ToLower();
  1707. if (moName.Contains("cp2mg_1") || displayName.Contains("cp2mg_1")) curMo = "Mg1";
  1708. else if (moName.Contains("cp2mg_2") || displayName.Contains("cp2mg_2")) curMo = "Mg2";
  1709. else if (moName.Contains("cp2mg_3") || displayName.Contains("cp2mg_3")) curMo = "Mg3";
  1710. else if (moName.Contains("cp2mg_4") || displayName.Contains("cp2mg_4")) curMo = "Mg4";
  1711. else if (moName.Contains("cp2mg") || displayName.Contains("cp2mg")) curMo = "Mg";
  1712. else if (moName.Contains("tmin") || displayName.Contains("tmin")) curMo = "In";
  1713. else if (moName.Contains("tmin_1") || displayName.Contains("tmin_1")) curMo = "In1";
  1714. else if (moName.Contains("tmin_2") || displayName.Contains("tmin_2")) curMo = "In2";
  1715. else if (moName.Contains("tmin_3") || displayName.Contains("tmin_3")) curMo = "In3";
  1716. else if (moName.Contains("tmin_4") || displayName.Contains("tmin_4")) curMo = "In4";
  1717. else if (moName.Contains("tmga") || displayName.Contains("tmga")) curMo = "TMG";
  1718. else if (moName.Contains("tmga_1") || displayName.Contains("tmga_1")) curMo = "TMG1";
  1719. else if (moName.Contains("tmga_2") || displayName.Contains("tmga_2")) curMo = "TMG2";
  1720. else if (moName.Contains("tmga_3") || displayName.Contains("tmga_3")) curMo = "TMG3";
  1721. else if (moName.Contains("tmga_4") || displayName.Contains("tmga_4")) curMo = "TMG4";
  1722. else if (moName.Contains("tega") || displayName.Contains("tega")) curMo = "TEG";
  1723. else if (moName.Contains("tega_1") || displayName.Contains("tega_1")) curMo = "TEG1";
  1724. else if (moName.Contains("tega_2") || displayName.Contains("tega_2")) curMo = "TEG2";
  1725. else if (moName.Contains("tega_3") || displayName.Contains("tega_3")) curMo = "TEG3";
  1726. else if (moName.Contains("tega_4") || displayName.Contains("tega_4")) curMo = "TEG4";
  1727. else if (moName.Contains("tmal") || displayName.Contains("tmal")) curMo = "TAl";
  1728. else if (moName.Contains("tmal_1") || displayName.Contains("tmal_1")) curMo = "TAl1";
  1729. else if (moName.Contains("tmal_2") || displayName.Contains("tmal_2")) curMo = "TAl2";
  1730. else if (moName.Contains("tmal_3") || displayName.Contains("tmal_3")) curMo = "TAl3";
  1731. else if (moName.Contains("tmal_4") || displayName.Contains("tmal_4")) curMo = "TAl4";
  1732. else if (moName.Contains("nh3source") || displayName.Contains("nh3source")) curMo = "NH3";
  1733. else if (moName.Contains("si")) curMo = "Si";
  1734. if (!string.IsNullOrEmpty(curMo))
  1735. {
  1736. if (string.IsNullOrEmpty(materialName))
  1737. materialName = curMo;
  1738. else
  1739. materialName += "|" + curMo;
  1740. }
  1741. }
  1742. }
  1743. if (materialRowId >= 0)
  1744. {
  1745. RecipeRows[materialRowId].RecipeItems[colId].Value = materialName;
  1746. RecipeRows[materialRowId].RecipeItems[colId].InvokePropertyChanged();
  1747. }
  1748. }
  1749. #endregion update material cell data
  1750. #region update column header
  1751. if (DataGridControl.Columns.Count - 1 == RecipeRows[0].RecipeItems.Count)
  1752. {
  1753. var redColHeader = (DataTemplate)DataGridControl.FindResource("columnRedTitleTemplate");
  1754. var blackColHeader = (DataTemplate)DataGridControl.FindResource("columnBlackTitleTemplate");
  1755. for (int j = 0; j < RecipeRows[0].RecipeItems.Count; j++)
  1756. {
  1757. DataGridControl.Columns[j + 1].Title = string.Format("{0}|{2}\r\n{1}", j + 1, RecipeRows[0].RecipeItems[j].Value, RecipeRows[2].RecipeItems[j].Value);
  1758. if (Errors.Find((o) => o.Item2 == j) != null)
  1759. DataGridControl.Columns[j + 1].TitleTemplate = redColHeader;
  1760. else
  1761. DataGridControl.Columns[j + 1].TitleTemplate = blackColHeader;
  1762. }
  1763. }
  1764. #endregion update column header
  1765. #region if running state, highlight current running step, move horizontal bar to current running step
  1766. if (CurrentRunningStepNo > 0 && DataGridControl.Columns.Count > 2)
  1767. {
  1768. for (int rowId = 0; rowId < RecipeRows.Count; rowId++)
  1769. {
  1770. for (int colId = 0; colId < RecipeRows[0].RecipeItems.Count; colId++)
  1771. {
  1772. var cell = RecipeRows[rowId].RecipeItems[colId];
  1773. if (colId + 1 == CurrentRunningStepNo)
  1774. {
  1775. cell.IsRunning = true;
  1776. }
  1777. else
  1778. {
  1779. cell.IsRunning = false;
  1780. }
  1781. cell.InvokePropertyChanged("IsRunning");
  1782. }
  1783. }
  1784. if (moving2RunningStepPosition)
  1785. {
  1786. Task.Factory.StartNew(() =>
  1787. {
  1788. System.Threading.Thread.Sleep(200);
  1789. DataGridControl.Dispatcher.Invoke(new Action(() =>
  1790. {
  1791. double singleWidth = DataGridControl.Columns[1].Width;
  1792. double horizontalOffset = (CurrentRunningStepNo - 2) * singleWidth;
  1793. if (DataGridControl.ScrollViewer != null)
  1794. {
  1795. if (horizontalOffset > DataGridControl.ScrollViewer.ScrollableWidth)
  1796. horizontalOffset = DataGridControl.ScrollViewer.ScrollableWidth;
  1797. if (horizontalOffset < 0)
  1798. horizontalOffset = 0;
  1799. DataGridControl.ScrollViewer.ScrollToHorizontalOffset(horizontalOffset);
  1800. }
  1801. }));
  1802. });
  1803. }
  1804. }
  1805. #endregion if running state, highlight current running step, move horizontal bar to current running step
  1806. //calc recipe time
  1807. CalcRecipeTime();
  1808. //invoke property
  1809. InvokePropertyChanged("Errors");
  1810. }
  1811. catch (Exception ex)
  1812. {
  1813. MessageBox.Show("工艺程序校验出错!\r\n\r\n" + ex.Message, "出错", MessageBoxButton.OK, MessageBoxImage.Error);
  1814. System.Diagnostics.Debug.WriteLine(ex.Message);
  1815. }
  1816. }
  1817. /// <summary>
  1818. /// reload datagrid content
  1819. /// </summary>
  1820. private void RefreshDataGrid()
  1821. {
  1822. try
  1823. {
  1824. //generate columns in Grid
  1825. DataGridControl.CurrentColumn = null;
  1826. if (DataGridControl.Columns.Count > 0)
  1827. DataGridControl.Columns.Clear();
  1828. var template = (DataTemplate)DataGridControl.FindResource("CustomTemplate");
  1829. var rowTemplate = (DataTemplate)DataGridControl.FindResource("RowHeadTemplate");
  1830. DataGridControl.Columns.Add(new Xceed.Wpf.DataGrid.Column()
  1831. {
  1832. Width = 140,
  1833. Title = " ",
  1834. FieldName = ".",
  1835. CellContentTemplate = rowTemplate
  1836. });
  1837. var cellEditor = DataGridControl.DefaultCellEditors[typeof(SmartCellData)];// DefaultCellEditorSelector.SelectCellEditor(typeof(SmartCellData));
  1838. for (int index = 0; index < RecipeRows[0].RecipeItems.Count; index++)
  1839. {
  1840. //var col = new Xceed.Wpf.DataGrid.Column();
  1841. DataGridControl.Columns.Add(new Xceed.Wpf.DataGrid.Column()
  1842. {
  1843. Title = string.Format("【{0}】\r\n{1}", index + 1, RecipeRows[0].RecipeItems[index].Value),
  1844. FieldName = string.Format("RecipeItems[{0}]", index),
  1845. CellContentTemplate = template,
  1846. AllowSort = false,
  1847. Width = 120,
  1848. MaxWidth = 120,
  1849. CellEditor = cellEditor
  1850. });
  1851. }
  1852. InvokePropertyChanged("RecipeRows");
  1853. InvokePropertyChanged("RecipeHead");
  1854. }
  1855. catch (Exception ex)
  1856. {
  1857. System.Diagnostics.Debug.WriteLine(ex.Message);
  1858. }
  1859. }
  1860. /// <summary>
  1861. /// calc recipe total time
  1862. /// </summary>
  1863. private void CalcRecipeTime()
  1864. {
  1865. int timeStepRowId = -1;
  1866. int loopStepRowId = -1;
  1867. for (int i = 0; i < RecipeRows.Count; i++)
  1868. {
  1869. if (RecipeRows[i].TechnicalName == "Time")
  1870. timeStepRowId = i;
  1871. if (RecipeRows[i].TechnicalName == "Loop")
  1872. loopStepRowId = i;
  1873. if (loopStepRowId != -1 && timeStepRowId != -1)
  1874. break;
  1875. }
  1876. TimeSpan tspan = new TimeSpan();
  1877. for (int stepNo = 0; stepNo < RecipeRows[timeStepRowId].RecipeItems.Count; stepNo++)
  1878. {
  1879. string loopStr = RecipeRows[loopStepRowId].RecipeItems[stepNo].Value;
  1880. bool isLoopStart = Regex.IsMatch(loopStr, @"^Loop\x20\d+$");
  1881. if (isLoopStart)
  1882. {
  1883. int loopNum = int.Parse(loopStr.ToLower().Replace("loop", "").Replace(" ", ""));
  1884. TimeSpan ts = new TimeSpan();
  1885. for (int innerStepNo = stepNo; innerStepNo < RecipeRows[timeStepRowId].RecipeItems.Count; innerStepNo++)
  1886. {
  1887. loopStr = RecipeRows[loopStepRowId].RecipeItems[innerStepNo].Value;
  1888. stepNo = innerStepNo;
  1889. string timeDuration = RecipeRows[timeStepRowId].RecipeItems[innerStepNo].Value;
  1890. string[] timeArr = timeDuration.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
  1891. if (timeArr.Length == 3)
  1892. {
  1893. int h, mi, s;
  1894. if (int.TryParse(timeArr[0], out h) && int.TryParse(timeArr[1], out mi) && int.TryParse(timeArr[2], out s))
  1895. {
  1896. var tt = new TimeSpan(h, mi, s);
  1897. ts += tt;
  1898. }
  1899. }
  1900. bool isLoopEnd = Regex.IsMatch(loopStr, @"^Loop End$");
  1901. if (isLoopEnd)
  1902. {
  1903. tspan += new TimeSpan(ts.Ticks * loopNum);
  1904. break;
  1905. }
  1906. }
  1907. }
  1908. else
  1909. {
  1910. string timeDuration = RecipeRows[timeStepRowId].RecipeItems[stepNo].Value;
  1911. string[] timeArr = timeDuration.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
  1912. if (timeArr.Length == 3)
  1913. {
  1914. int h, mi, s;
  1915. if (int.TryParse(timeArr[0], out h) && int.TryParse(timeArr[1], out mi) && int.TryParse(timeArr[2], out s))
  1916. {
  1917. var ts = new TimeSpan(h, mi, s);
  1918. tspan += ts;
  1919. }
  1920. }
  1921. }
  1922. }
  1923. RecipeInfo = string.Format("共{0}步,总时间{1}:{2}:{3}", RecipeRows[0].RecipeItems.Count, (int)tspan.TotalHours, tspan.Minutes.ToString("00"), tspan.Seconds.ToString("00"));
  1924. InvokePropertyChanged("RecipeInfo");
  1925. }
  1926. #region INotifyPropertyChanged
  1927. public event PropertyChangedEventHandler PropertyChanged;
  1928. public void InvokePropertyChanged(string propertyName)
  1929. {
  1930. if (PropertyChanged != null)
  1931. {
  1932. PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
  1933. }
  1934. }
  1935. #endregion INotifyPropertyChanged
  1936. }
  1937. public class RecipeRow
  1938. {
  1939. private ObservableCollection<SmartCellData> _recipeItems = new ObservableCollection<SmartCellData>();
  1940. public RecipeRow(params SmartCellData[] vars)
  1941. {
  1942. foreach (var var in vars)
  1943. _recipeItems.Add(var);
  1944. }
  1945. public string CatalogName { get; set; }
  1946. public string FriendlyName { get; set; }
  1947. public string TechnicalName { get; set; }
  1948. public ObservableCollection<SmartCellData> RecipeItems
  1949. {
  1950. get { return _recipeItems; }
  1951. set { _recipeItems = value; }
  1952. }
  1953. }
  1954. /// <summary>
  1955. /// Recipe head
  1956. /// </summary>
  1957. public class RecipeHead
  1958. {
  1959. public string RecipeVariation { get; set; }
  1960. public string CreationTime { get; set; }
  1961. public string LastRevisionTime { get; set; }
  1962. public string CreatedBy { get; set; }
  1963. public string LastModifiedBy { get; set; }
  1964. public string PressureMode { get; set; }
  1965. public string Description { get; set; }
  1966. public string BasePressure
  1967. {
  1968. get; set;
  1969. }
  1970. public string PumpDownLimit
  1971. {
  1972. get; set;
  1973. }
  1974. public string PurgeActive
  1975. {
  1976. get; set;
  1977. }
  1978. public string NotToPurgeOrVent
  1979. {
  1980. get; set;
  1981. }
  1982. public string Barcode
  1983. {
  1984. get; set;
  1985. }
  1986. public string SubstrateTemp
  1987. {
  1988. get; set;
  1989. }
  1990. public string PumpingPinState
  1991. {
  1992. get; set;
  1993. }
  1994. public string VentingPinState
  1995. {
  1996. get; set;
  1997. }
  1998. public string PinDownPressure
  1999. {
  2000. get; set;
  2001. }
  2002. }
  2003. public class EndPointConfigItem : INotifyPropertyChanged
  2004. {
  2005. public event PropertyChangedEventHandler PropertyChanged;
  2006. public void InvokePropertyChanged(string propertyName)
  2007. {
  2008. if (PropertyChanged != null)
  2009. {
  2010. PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
  2011. }
  2012. }
  2013. public string ExposureTime { get; set; }
  2014. public string WaveLengthA { get; set; }
  2015. public string BinningA { get; set; }
  2016. public string WaveLengthB { get; set; }
  2017. public string BinningB { get; set; }
  2018. public string WaveLengthC { get; set; }
  2019. public string BinningC { get; set; }
  2020. public string WaveLengthD { get; set; }
  2021. public string BinningD { get; set; }
  2022. public string Fd { get; set; }
  2023. public string PrefilterTime { get; set; }
  2024. public string PostfilterTime { get; set; }
  2025. public string AlgorithmType { get; set; }
  2026. public string Criteria { get; set; }
  2027. public string DelayTime { get; set; }
  2028. public string ValidationTime { get; set; }
  2029. public string ValidationValue { get; set; }
  2030. public string TimeWindow { get; set; }
  2031. public string MinimalTime { get; set; }
  2032. public string PostponeTime { get; set; }
  2033. public bool Control { get; set; }
  2034. public bool Normalization { get; set; }
  2035. public bool EnablePostponePercent { get; set; }
  2036. public bool EnableCriterialPercent { get; set; }
  2037. public bool EnableEventTrigger { get; set; }
  2038. public bool IsFaultIfNoTrigger { get; set; }
  2039. public string ToValue()
  2040. {
  2041. return
  2042. $@"ExposureTime={ExposureTime};WaveLengthA={WaveLengthA};BinningA={BinningA};WaveLengthB={WaveLengthB};" +
  2043. $@"BinningB={BinningB};WaveLengthC={WaveLengthC};BinningC={BinningC};WaveLengthD={WaveLengthD};BinningD={BinningD};Fd={Fd};" +
  2044. $@"PrefilterTime={PrefilterTime};PostfilterTime={PostfilterTime};AlgorithmType={AlgorithmType};Criteria={Criteria};DelayTime={DelayTime};ValidationTime={ValidationTime};" +
  2045. $@"ValidationValue={ValidationValue};TimeWindow={TimeWindow};MinimalTime={MinimalTime};PostponeTime={PostponeTime};Control={Control};Normalization={Normalization};" +
  2046. $@"EnablePostponePercent={EnablePostponePercent};EnableCriterialPercent={EnableCriterialPercent};EnableEventTrigger={EnableEventTrigger};IsFaultIfNoTrigger={IsFaultIfNoTrigger};"
  2047. ;
  2048. }
  2049. public void SetValue(string config)
  2050. {
  2051. if (string.IsNullOrEmpty(config))
  2052. return;
  2053. string[] items = config.Split(';');
  2054. foreach (var item in items)
  2055. {
  2056. if (string.IsNullOrEmpty(item))
  2057. continue;
  2058. string[] pairs = item.Split('=');
  2059. if (pairs.Length != 2)
  2060. continue;
  2061. Parallel.ForEach(this.GetType().GetProperties(),
  2062. property =>
  2063. {
  2064. PropertyInfo pi = (PropertyInfo) property;
  2065. if (pi.Name == pairs[0])
  2066. {
  2067. try
  2068. {
  2069. var convertedValue = Convert.ChangeType(pairs[1], pi.PropertyType);
  2070. var originValue = Convert.ChangeType(pi.GetValue(this, null), pi.PropertyType);
  2071. if (originValue != convertedValue)
  2072. {
  2073. pi.SetValue(this, convertedValue, null);
  2074. }
  2075. }
  2076. catch (Exception)
  2077. {
  2078. }
  2079. }
  2080. });
  2081. }
  2082. }
  2083. }
  2084. }