DynamicFormLayoutGrid.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text.RegularExpressions;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Media.Imaging;
  10. using InABox.Core;
  11. using InABox.DynamicGrid;
  12. using InABox.Scripting;
  13. using InABox.WPF;
  14. using Microsoft.Win32;
  15. using Org.BouncyCastle.Asn1.Mozilla;
  16. using Syncfusion.UI.Xaml.Spreadsheet;
  17. using Syncfusion.Windows.Shared;
  18. using UnderlineType = InABox.Core.UnderlineType;
  19. namespace InABox.DynamicGrid
  20. {
  21. public static class FormLayoutImporter
  22. {
  23. private class Cell
  24. {
  25. public string Content { get; set; }
  26. public int Row { get; set; }
  27. public int Column { get; set; }
  28. public int RowSpan { get; set; } = 1;
  29. public int ColumnSpan { get; set; } = 1;
  30. public ICell InnerCell { get; set; }
  31. public Cell(int row, int column, string content, ICell cell)
  32. {
  33. Row = row;
  34. Column = column;
  35. Content = content;
  36. InnerCell = cell;
  37. }
  38. }
  39. private static void DeleteColumn(List<Cell> cells, int column)
  40. {
  41. foreach(var cell in cells)
  42. {
  43. if(cell.Column <= column && cell.Column + cell.ColumnSpan - 1 >= column)
  44. {
  45. --cell.ColumnSpan;
  46. }
  47. else if(cell.Column > column)
  48. {
  49. --cell.Column;
  50. }
  51. }
  52. cells.RemoveAll(x => x.ColumnSpan < 0);
  53. }
  54. private static List<Cell> GetCells(ISheet sheet)
  55. {
  56. var grid = new Dictionary<int, Dictionary<int, Cell>>();
  57. for (int rowIdx = sheet.FirstRow; rowIdx <= sheet.LastRow; ++rowIdx)
  58. {
  59. var row = sheet.GetRow(rowIdx);
  60. if (row is not null && row.FirstColumn >= 0)
  61. {
  62. var rowCells = new Dictionary<int, Cell>();
  63. for (int colIdx = row.FirstColumn; colIdx <= row.LastColumn; ++colIdx)
  64. {
  65. var cell = row.GetCell(colIdx);
  66. if (cell is not null)
  67. {
  68. rowCells.Add(colIdx, new Cell(rowIdx, colIdx, cell.GetValue(), cell));
  69. }
  70. }
  71. grid.Add(rowIdx, rowCells);
  72. }
  73. }
  74. foreach (var region in sheet.GetMergedCells())
  75. {
  76. for (int r = region.FirstRow; r <= region.LastRow; ++r)
  77. {
  78. if (!grid.TryGetValue(r, out var row)) continue;
  79. for (int c = region.FirstColumn; c <= region.LastColumn; ++c)
  80. {
  81. if ((r - region.FirstRow) + (c - region.FirstColumn) != 0)
  82. {
  83. row.Remove(c);
  84. }
  85. }
  86. if (row.Count == 0)
  87. {
  88. grid.Remove(r);
  89. }
  90. }
  91. if (grid.TryGetValue(region.FirstRow, out var cRow) && cRow.TryGetValue(region.FirstColumn, out var cCell))
  92. {
  93. cCell.RowSpan = region.LastRow - region.FirstRow + 1;
  94. cCell.ColumnSpan = region.LastColumn - region.FirstColumn + 1;
  95. }
  96. }
  97. var cells = new List<Cell>();
  98. foreach (var row in grid.Values)
  99. {
  100. foreach (var cell in row.Values)
  101. {
  102. cells.Add(cell);
  103. }
  104. }
  105. return cells;
  106. }
  107. private static Regex VariableRegex = new(@"^\[(?<VAR>[^:\]]+)(?::(?<TYPE>[^:\]]*))?(?::(?<PROPERTIES>[^\]]*))?\]$");
  108. private static Regex HeaderRegex = new(@"^{(?<HEADER>[^:}]+)(?::(?<COLLAPSED>[^}]*))?}$");
  109. public static DFLayout LoadLayout(ISpreadsheet spreadsheet)
  110. {
  111. var sheet = spreadsheet.GetSheet(0);
  112. var cells = GetCells(sheet);
  113. int firstRow = int.MaxValue;
  114. int lastRow = 0;
  115. int firstCol = int.MaxValue;
  116. int lastCol = 0;
  117. foreach (var cell in cells)
  118. {
  119. firstCol = Math.Min(cell.Column, firstCol);
  120. lastCol = Math.Max(cell.Column + cell.ColumnSpan - 1, lastCol);
  121. firstRow = Math.Min(cell.Row, firstRow);
  122. lastRow = Math.Max(cell.Row + cell.RowSpan - 1, lastRow);
  123. }
  124. var layout = new DFLayout();
  125. var columnWidths = new Dictionary<int, float>();
  126. var colOffset = 0;
  127. for (int col = firstCol; col <= lastCol; ++col)
  128. {
  129. var width = sheet.GetColumnWidth(col);
  130. if(width == float.MinValue)
  131. {
  132. layout.ColumnWidths.Add("10*");
  133. }
  134. else if(width <= 0f)
  135. {
  136. DeleteColumn(cells, col);
  137. }
  138. else
  139. {
  140. layout.ColumnWidths.Add($"{width}*");
  141. }
  142. }
  143. for (int row = firstRow; row <= lastRow; ++row)
  144. {
  145. float height = sheet.GetRowHeight(row);
  146. float defaultheight = sheet.GetDefaultRowHeight();
  147. float multiplier = defaultheight == 0 ? 1.0F : height/defaultheight;
  148. var final = Math.Round(multiplier * 10,0) * 5;
  149. layout.RowHeights.Add($"{final}");
  150. }
  151. foreach(var cell in cells)
  152. {
  153. var style = cell.InnerCell.GetStyle();
  154. if (string.IsNullOrWhiteSpace(cell.Content) && style.Foreground == Color.Empty) continue;
  155. DFLayoutControl? control;
  156. String content = cell.Content?.Trim() ?? "";
  157. var headermatch = HeaderRegex.Match(content);
  158. var variablematch = VariableRegex.Match(content);
  159. if (headermatch.Success)
  160. {
  161. var text = headermatch.Groups["HEADER"];
  162. var collapsed = headermatch.Groups["COLLAPSED"];
  163. var header = new DFLayoutHeader()
  164. {
  165. Header = text.Value,
  166. Collapsed = collapsed.Success ? String.Equals(collapsed.Value.ToUpper(),"COLLAPSED") : false,
  167. Style = CreateStyle(style)
  168. };
  169. control = header;
  170. }
  171. else if (variablematch.Success)
  172. {
  173. var variableName = variablematch.Groups["VAR"];
  174. var variableType = variablematch.Groups["TYPE"];
  175. var variableProps = variablematch.Groups["PROPERTIES"];
  176. Type? fieldType = null;
  177. if (variableType.Success)
  178. fieldType = DFUtils.GetFieldType(variableType.Value);
  179. fieldType ??= typeof(DFLayoutStringField);
  180. var field = (Activator.CreateInstance(fieldType) as DFLayoutField)!;
  181. field.Name = variableName.Value;
  182. if (variableProps.Success)
  183. {
  184. if (field is DFLayoutOptionField option)
  185. option.Properties.Options = variableProps.Value;
  186. // need to populate other variable types here
  187. }
  188. control = field;
  189. }
  190. else
  191. {
  192. control = new DFLayoutLabel
  193. {
  194. Caption = cell.Content,
  195. Style = CreateStyle(style)
  196. };
  197. }
  198. if(control is not null)
  199. {
  200. control.Row = cell.Row - firstRow + 1;
  201. control.Column = cell.Column - firstCol + 1 - colOffset;
  202. control.RowSpan = cell.RowSpan;
  203. control.ColumnSpan = cell.ColumnSpan;
  204. layout.Elements.Add(control);
  205. }
  206. }
  207. return layout;
  208. }
  209. private static DFLayoutTextStyle CreateStyle(ICellStyle style)
  210. {
  211. if (style == null)
  212. return new DFLayoutTextStyle();
  213. var result = new DFLayoutTextStyle
  214. {
  215. FontSize = style.Font.FontSize,
  216. IsItalic = style.Font.Italic,
  217. IsBold = style.Font.Bold,
  218. Underline = style.Font.Underline switch
  219. {
  220. Scripting.UnderlineType.None => UnderlineType.None,
  221. Scripting.UnderlineType.Single or Scripting.UnderlineType.SingleAccounting => UnderlineType.Single,
  222. Scripting.UnderlineType.Double or Scripting.UnderlineType.DoubleAccounting => UnderlineType.Double,
  223. _ => UnderlineType.None
  224. },
  225. BackgroundColour = style.Background,
  226. ForegroundColour = style.Font.Colour
  227. };
  228. return result;
  229. }
  230. }
  231. public abstract class DynamicFormLayoutGrid<T> : DynamicOneToManyGrid<DigitalForm, DigitalFormLayout> where T : Entity, IRemotable, IPersistent, new()
  232. {
  233. private readonly BitmapImage design = Properties.Resources.design.AsBitmapImage();
  234. public DynamicFormLayoutGrid()
  235. {
  236. Options.AddRange(DynamicGridOption.RecordCount, DynamicGridOption.ImportData);
  237. ActionColumns.Add(new DynamicImageColumn(DesignImage, DesignClick));
  238. //AddButton("Design", PRSDesktop.Resources.design.AsBitmapImage(), DesignClick);
  239. HiddenColumns.Add(x => x.Layout);
  240. AddButton("Auto Generate", null, AutoGenerate_Click);
  241. AddButton("Duplicate", null, Duplicate_Click);
  242. }
  243. private DFLayout LoadLayoutFromSpreadsheet(ISpreadsheet spreadsheet)
  244. {
  245. return FormLayoutImporter.LoadLayout(spreadsheet);
  246. }
  247. protected override void DoImport()
  248. {
  249. var dialog = new OpenFileDialog();
  250. dialog.Filter = "Excel Spreadsheet (.xlsx)|*.xlsx";
  251. if (dialog.ShowDialog() == true)
  252. {
  253. try
  254. {
  255. DFLayout layout;
  256. Dictionary<String, String> variablegroups = new Dictionary<string, string>();
  257. using (var fs = new FileStream(dialog.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
  258. {
  259. layout = LoadLayoutFromSpreadsheet(new Spreadsheet(fs));
  260. }
  261. var dfLayout = CreateItem();
  262. dfLayout.Code = Path.GetFileNameWithoutExtension(dialog.FileName).ToUpper();
  263. dfLayout.Description = $"Imported From {Path.GetFileName(dialog.FileName)}";
  264. dfLayout.Layout = layout.SaveLayout();
  265. if(EditItems(new DigitalFormLayout[] { dfLayout }))
  266. {
  267. var newVariables = new List<DigitalFormVariable>();
  268. String group = "";
  269. foreach (var element in layout.Elements)
  270. {
  271. if (element is DFLayoutHeader header)
  272. {
  273. group = header.Header;
  274. }
  275. else if (element is DFLayoutField field)
  276. {
  277. var variable = new DigitalFormVariable();
  278. variable.SetFieldType(field.GetType());
  279. variable.SaveProperties(field.GetProperties());
  280. variable.Group = group;
  281. variable.Code = field.Name;
  282. variable.Description = field.Name;
  283. newVariables.Add(variable);
  284. }
  285. }
  286. if(newVariables.Count > 0)
  287. {
  288. var variables = GetVariableGrid();
  289. if (variables is not null)
  290. {
  291. var save = new List<DigitalFormVariable>();
  292. foreach(var newVariable in newVariables)
  293. {
  294. var variable = variables.GetVariable(newVariable.Code);
  295. if(variable is not null)
  296. {
  297. if(variable.FieldType() != newVariable.FieldType())
  298. {
  299. MessageBox.Show($"Variable [{newVariable.Code}] already exists with a different type!");
  300. }
  301. }
  302. else
  303. {
  304. save.Add(newVariable);
  305. }
  306. }
  307. variables.SaveItems(save.ToArray());
  308. variables.Refresh(false, true);
  309. }
  310. }
  311. Refresh(false, true);
  312. }
  313. }
  314. catch(Exception e)
  315. {
  316. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  317. MessageBox.Show($"Error: {e.Message}");
  318. }
  319. }
  320. }
  321. private bool Duplicate_Click(Button btn, CoreRow[] rows)
  322. {
  323. if (!rows.Any()) return false;
  324. SaveItems(rows.Select(x =>
  325. {
  326. var layout = x.ToObject<DigitalFormLayout>();
  327. layout.ID = Guid.Empty;
  328. return layout;
  329. }).ToArray());
  330. return true;
  331. }
  332. private bool AutoGenerate_Click(Button btn, CoreRow[] rows)
  333. {
  334. var menu = new ContextMenu();
  335. menu.AddItem("Desktop Layout", null, AddDesktop_Click);
  336. menu.AddItem("Mobile Layout", null, AddMobile_Click);
  337. menu.IsOpen = true;
  338. return false;
  339. }
  340. private BitmapImage? DesignImage(CoreRow? row)
  341. {
  342. return row != null ? design : null;
  343. }
  344. private void AddMobile_Click()
  345. {
  346. var item = CreateItem();
  347. item.Layout = DFLayout.GenerateAutoMobileLayout(GetVariables()).SaveLayout();
  348. item.Type = DFLayoutType.Mobile;
  349. if (EditItems(new[] { item }))
  350. {
  351. SaveItem(item);
  352. Refresh(false, true);
  353. DoChanged();
  354. }
  355. }
  356. private void AddDesktop_Click()
  357. {
  358. var item = CreateItem();
  359. item.Layout = DFLayout.GenerateAutoDesktopLayout(GetVariables()).SaveLayout();
  360. item.Type = DFLayoutType.Desktop;
  361. if (EditItems(new[] { item }))
  362. {
  363. SaveItem(item);
  364. Refresh(false, true);
  365. DoChanged();
  366. }
  367. }
  368. private DynamicVariableGrid? GetVariableGrid()
  369. => EditorGrid.Pages?.FirstOrDefault(x => x is DynamicVariableGrid)
  370. as DynamicVariableGrid;
  371. private List<DigitalFormVariable> GetVariables()
  372. => GetVariableGrid()?.Items.ToList() ?? new List<DigitalFormVariable>();
  373. private void Design(DigitalFormLayout layout)
  374. {
  375. var variables = GetVariables();
  376. var newVariables = new List<DigitalFormVariable>();
  377. var form = new DynamicFormDesignWindow
  378. {
  379. Type = layout.Type
  380. };
  381. form.OnCreateVariable += (fieldType) =>
  382. {
  383. if (DynamicVariableUtils.CreateAndEdit(Item, GetVariables(), fieldType, out var variable))
  384. {
  385. newVariables.Add(variable);
  386. return variable;
  387. }
  388. return null;
  389. };
  390. /*form.OnEditVariable += (variable) =>
  391. {
  392. var properties = variable.CreateProperties();
  393. if (DynamicVariableUtils.EditProperties(Item, GetVariables(), properties.GetType(), properties))
  394. {
  395. variable.SaveProperties(properties);
  396. return true;
  397. }
  398. return false;
  399. };*/
  400. form.LoadLayout(layout, variables);
  401. form.Initialize();
  402. if (form.ShowDialog() == true)
  403. {
  404. layout.Layout = form.SaveLayout();
  405. SaveItem(layout);
  406. var grid = GetVariableGrid();
  407. if (grid is not null)
  408. {
  409. grid.SaveItems(newVariables.ToArray());
  410. grid.Refresh(false, true);
  411. }
  412. }
  413. }
  414. private bool DesignClick(CoreRow? row)
  415. {
  416. if (row == null)
  417. return false;
  418. Design(LoadItem(row));
  419. return false;
  420. }
  421. //public override void SaveItem(DigitalFormLayout item)
  422. //{
  423. // bool bActive = item.Active;
  424. // foreach (var other in Items.Where(x=>(x != item) && (x.Type == item.Type)))
  425. // {
  426. // if (item.Active)
  427. // {
  428. // if (other.Active)
  429. // other.Active = false;
  430. // }
  431. // else
  432. // bActive = bActive || other.Active;
  433. // }
  434. // if (!bActive)
  435. // item.Active = true;
  436. // base.SaveItem(item);
  437. //}
  438. protected override void DoDoubleClick(object sender)
  439. {
  440. DesignClick(SelectedRows.FirstOrDefault());
  441. }
  442. }
  443. }