DynamicFormLayoutGrid.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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("^\\s*\\[(?<VAR>[^:\\]]+)(?::(?<TYPE>[^\\]]+))?\\]$");
  108. public static DFLayout LoadLayout(ISpreadsheet spreadsheet)
  109. {
  110. var sheet = spreadsheet.GetSheet(0);
  111. var cells = GetCells(sheet);
  112. int firstRow = int.MaxValue;
  113. int lastRow = 0;
  114. int firstCol = int.MaxValue;
  115. int lastCol = 0;
  116. foreach (var cell in cells)
  117. {
  118. firstCol = Math.Min(cell.Column, firstCol);
  119. lastCol = Math.Max(cell.Column + cell.ColumnSpan - 1, lastCol);
  120. firstRow = Math.Min(cell.Row, firstRow);
  121. lastRow = Math.Max(cell.Row + cell.RowSpan - 1, lastRow);
  122. }
  123. var layout = new DFLayout();
  124. var columnWidths = new Dictionary<int, float>();
  125. var colOffset = 0;
  126. for (int col = firstCol; col <= lastCol; ++col)
  127. {
  128. var width = sheet.GetColumnWidth(col);
  129. if(width == float.MinValue)
  130. {
  131. layout.ColumnWidths.Add("10*");
  132. }
  133. else if(width <= 0f)
  134. {
  135. DeleteColumn(cells, col);
  136. }
  137. else
  138. {
  139. layout.ColumnWidths.Add($"{width}*");
  140. }
  141. }
  142. /*var rowHeights = new Dictionary<int, float>();
  143. for (int row = firstRow; row <= lastRow; ++row)
  144. {
  145. rowHeights[row] = sheet.GetRowHeight(row);
  146. }
  147. var totalHeight = rowHeights.Values.Sum();*/
  148. for(int row = firstRow; row <= lastRow; ++row)
  149. {
  150. layout.RowHeights.Add("Auto");
  151. }
  152. foreach(var cell in cells)
  153. {
  154. var style = cell.InnerCell.GetStyle();
  155. if (string.IsNullOrWhiteSpace(cell.Content) && style.Foreground == Color.Empty) continue;
  156. DFLayoutControl? control;
  157. var match = VariableRegex.Match(cell.Content);
  158. if (match.Success)
  159. {
  160. var variableName = match.Groups["VAR"];
  161. var variableType = match.Groups["TYPE"];
  162. Type? fieldType = null;
  163. if (variableType.Success)
  164. {
  165. fieldType = DFUtils.GetFieldType(variableType.Value);
  166. }
  167. fieldType ??= typeof(DFLayoutStringField);
  168. var field = (Activator.CreateInstance(fieldType) as DFLayoutField)!;
  169. field.Name = variableName.Value;
  170. control = field;
  171. }
  172. else
  173. {
  174. var font = style.Font;
  175. control = new DFLayoutLabel
  176. {
  177. Caption = cell.Content,
  178. Style = new DFLayoutTextStyle
  179. {
  180. FontSize = font.FontSize,
  181. IsItalic = font.Italic,
  182. IsBold = font.Bold,
  183. Underline = font.Underline switch
  184. {
  185. Scripting.UnderlineType.None => UnderlineType.None,
  186. Scripting.UnderlineType.Single or Scripting.UnderlineType.SingleAccounting => UnderlineType.Single,
  187. Scripting.UnderlineType.Double or Scripting.UnderlineType.DoubleAccounting => UnderlineType.Double,
  188. _ => UnderlineType.None
  189. },
  190. BackgroundColour = style.Foreground,
  191. ForegroundColour = font.Colour
  192. }
  193. };
  194. }
  195. if(control is not null)
  196. {
  197. control.Row = cell.Row - firstRow + 1;
  198. control.Column = cell.Column - firstCol + 1 - colOffset;
  199. control.RowSpan = cell.RowSpan;
  200. control.ColumnSpan = cell.ColumnSpan;
  201. layout.Elements.Add(control);
  202. }
  203. }
  204. return layout;
  205. }
  206. }
  207. public abstract class DynamicFormLayoutGrid<T> : DynamicOneToManyGrid<DigitalForm, DigitalFormLayout> where T : Entity, IRemotable, IPersistent, new()
  208. {
  209. private readonly BitmapImage design = Properties.Resources.design.AsBitmapImage();
  210. public DynamicFormLayoutGrid()
  211. {
  212. Options.AddRange(DynamicGridOption.RecordCount, DynamicGridOption.ImportData);
  213. ActionColumns.Add(new DynamicImageColumn(DesignImage, DesignClick));
  214. //AddButton("Design", PRSDesktop.Resources.design.AsBitmapImage(), DesignClick);
  215. HiddenColumns.Add(x => x.Layout);
  216. AddButton("Auto Generate", null, AutoGenerate_Click);
  217. AddButton("Duplicate", null, Duplicate_Click);
  218. }
  219. private DFLayout LoadLayoutFromSpreadsheet(ISpreadsheet spreadsheet)
  220. {
  221. return FormLayoutImporter.LoadLayout(spreadsheet);
  222. }
  223. protected override void DoImport()
  224. {
  225. var dialog = new OpenFileDialog();
  226. dialog.Filter = "Excel Spreadsheet (.xlsx)|*.xlsx";
  227. if (dialog.ShowDialog() == true)
  228. {
  229. try
  230. {
  231. DFLayout layout;
  232. using (var fs = new FileStream(dialog.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
  233. {
  234. layout = LoadLayoutFromSpreadsheet(new Spreadsheet(fs));
  235. }
  236. var dfLayout = CreateItem();
  237. dfLayout.Layout = layout.SaveLayout();
  238. if(EditItems(new DigitalFormLayout[] { dfLayout }))
  239. {
  240. var newVariables = new List<DigitalFormVariable>();
  241. foreach (var element in layout.Elements)
  242. {
  243. if(element is DFLayoutField field)
  244. {
  245. var variable = new DigitalFormVariable
  246. {
  247. Code = field.Name,
  248. Description = field.Name
  249. };
  250. variable.SetFieldType(field.GetType());
  251. newVariables.Add(variable);
  252. }
  253. }
  254. if(newVariables.Count > 0)
  255. {
  256. var variables = GetVariableGrid();
  257. if (variables is not null)
  258. {
  259. var save = new List<DigitalFormVariable>();
  260. foreach(var newVariable in newVariables)
  261. {
  262. var variable = variables.GetVariable(newVariable.Code);
  263. if(variable is not null)
  264. {
  265. if(variable.FieldType() != newVariable.FieldType())
  266. {
  267. MessageBox.Show($"Variable [{newVariable.Code}] already exists with a different type!");
  268. }
  269. }
  270. else
  271. {
  272. save.Add(newVariable);
  273. }
  274. }
  275. variables.SaveItems(save.ToArray());
  276. variables.Refresh(false, true);
  277. }
  278. }
  279. Refresh(false, true);
  280. }
  281. }
  282. catch(Exception e)
  283. {
  284. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  285. MessageBox.Show($"Error: {e.Message}");
  286. }
  287. }
  288. }
  289. private bool Duplicate_Click(Button btn, CoreRow[] rows)
  290. {
  291. if (!rows.Any()) return false;
  292. SaveItems(rows.Select(x =>
  293. {
  294. var layout = x.ToObject<DigitalFormLayout>();
  295. layout.ID = Guid.Empty;
  296. return layout;
  297. }).ToArray());
  298. return true;
  299. }
  300. private bool AutoGenerate_Click(Button btn, CoreRow[] rows)
  301. {
  302. var menu = new ContextMenu();
  303. menu.AddItem("Desktop Layout", null, AddDesktop_Click);
  304. menu.AddItem("Mobile Layout", null, AddMobile_Click);
  305. menu.IsOpen = true;
  306. return false;
  307. }
  308. private BitmapImage? DesignImage(CoreRow? row)
  309. {
  310. return row != null ? design : null;
  311. }
  312. private void AddMobile_Click()
  313. {
  314. var item = CreateItem();
  315. item.Layout = DFLayout.GenerateAutoMobileLayout(GetVariables()).SaveLayout();
  316. item.Type = DFLayoutType.Mobile;
  317. if (EditItems(new[] { item }))
  318. {
  319. SaveItem(item);
  320. Refresh(false, true);
  321. DoChanged();
  322. }
  323. }
  324. private void AddDesktop_Click()
  325. {
  326. var item = CreateItem();
  327. item.Layout = DFLayout.GenerateAutoDesktopLayout(GetVariables()).SaveLayout();
  328. item.Type = DFLayoutType.Desktop;
  329. if (EditItems(new[] { item }))
  330. {
  331. SaveItem(item);
  332. Refresh(false, true);
  333. DoChanged();
  334. }
  335. }
  336. private DynamicVariableGrid? GetVariableGrid()
  337. => EditorGrid.Pages?.FirstOrDefault(x => x is DynamicVariableGrid)
  338. as DynamicVariableGrid;
  339. private List<DigitalFormVariable> GetVariables()
  340. => GetVariableGrid()?.Items.ToList() ?? new List<DigitalFormVariable>();
  341. private void Design(DigitalFormLayout layout)
  342. {
  343. var variables = GetVariables();
  344. var newVariables = new List<DigitalFormVariable>();
  345. var form = new DynamicFormDesignWindow
  346. {
  347. Type = layout.Type
  348. };
  349. form.OnCreateVariable += (fieldType) =>
  350. {
  351. if (DynamicVariableUtils.CreateAndEdit(Item, GetVariables(), fieldType, out var variable))
  352. {
  353. newVariables.Add(variable);
  354. return variable;
  355. }
  356. return null;
  357. };
  358. /*form.OnEditVariable += (variable) =>
  359. {
  360. var properties = variable.CreateProperties();
  361. if (DynamicVariableUtils.EditProperties(Item, GetVariables(), properties.GetType(), properties))
  362. {
  363. variable.SaveProperties(properties);
  364. return true;
  365. }
  366. return false;
  367. };*/
  368. form.LoadLayout(layout, variables);
  369. form.Initialize();
  370. if (form.ShowDialog() == true)
  371. {
  372. layout.Layout = form.SaveLayout();
  373. SaveItem(layout);
  374. var grid = GetVariableGrid();
  375. if (grid is not null)
  376. {
  377. grid.SaveItems(newVariables.ToArray());
  378. grid.Refresh(false, true);
  379. }
  380. }
  381. }
  382. private bool DesignClick(CoreRow? row)
  383. {
  384. if (row == null)
  385. return false;
  386. Design(LoadItem(row));
  387. return false;
  388. }
  389. //public override void SaveItem(DigitalFormLayout item)
  390. //{
  391. // bool bActive = item.Active;
  392. // foreach (var other in Items.Where(x=>(x != item) && (x.Type == item.Type)))
  393. // {
  394. // if (item.Active)
  395. // {
  396. // if (other.Active)
  397. // other.Active = false;
  398. // }
  399. // else
  400. // bActive = bActive || other.Active;
  401. // }
  402. // if (!bActive)
  403. // item.Active = true;
  404. // base.SaveItem(item);
  405. //}
  406. protected override void DoDoubleClick(object sender)
  407. {
  408. DesignClick(SelectedRows.FirstOrDefault());
  409. }
  410. }
  411. }