DigitalFormUtils.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using FastReport;
  7. using FastReport.Table;
  8. using FastReport.Utils;
  9. using InABox.Core;
  10. using InABox.Scripting;
  11. using InABox.Wpf.Reports;
  12. using UnderlineType = InABox.Core.UnderlineType;
  13. namespace InABox.DynamicGrid
  14. {
  15. public static class DigitalFormUtils
  16. {
  17. #region Layout Importer
  18. private class Cell
  19. {
  20. public string Content { get; set; }
  21. public int Row { get; set; }
  22. public int Column { get; set; }
  23. public int RowSpan { get; set; } = 1;
  24. public int ColumnSpan { get; set; } = 1;
  25. public ICell InnerCell { get; set; }
  26. public Cell(int row, int column, string content, ICell cell)
  27. {
  28. Row = row;
  29. Column = column;
  30. Content = content;
  31. InnerCell = cell;
  32. }
  33. }
  34. private static void DeleteColumn(List<Cell> cells, int column)
  35. {
  36. foreach(var cell in cells)
  37. {
  38. if(cell.Column <= column && cell.Column + cell.ColumnSpan - 1 >= column)
  39. {
  40. --cell.ColumnSpan;
  41. }
  42. else if(cell.Column > column)
  43. {
  44. --cell.Column;
  45. }
  46. }
  47. cells.RemoveAll(x => x.ColumnSpan < 0);
  48. }
  49. private static List<Cell> GetCells(ISheet sheet)
  50. {
  51. var grid = new Dictionary<int, Dictionary<int, Cell>>();
  52. for (int rowIdx = sheet.FirstRow; rowIdx <= sheet.LastRow; ++rowIdx)
  53. {
  54. var row = sheet.GetRow(rowIdx);
  55. if (row is not null && row.FirstColumn >= 0)
  56. {
  57. var rowCells = new Dictionary<int, Cell>();
  58. for (int colIdx = row.FirstColumn; colIdx <= row.LastColumn; ++colIdx)
  59. {
  60. var cell = row.GetCell(colIdx);
  61. if (cell is not null)
  62. {
  63. rowCells.Add(colIdx, new Cell(rowIdx, colIdx, cell.GetValue(), cell));
  64. }
  65. }
  66. grid.Add(rowIdx, rowCells);
  67. }
  68. }
  69. foreach (var region in sheet.GetMergedCells())
  70. {
  71. for (int r = region.FirstRow; r <= region.LastRow; ++r)
  72. {
  73. if (!grid.TryGetValue(r, out var row)) continue;
  74. for (int c = region.FirstColumn; c <= region.LastColumn; ++c)
  75. {
  76. if ((r - region.FirstRow) + (c - region.FirstColumn) != 0)
  77. {
  78. row.Remove(c);
  79. }
  80. }
  81. if (row.Count == 0)
  82. {
  83. grid.Remove(r);
  84. }
  85. }
  86. if (grid.TryGetValue(region.FirstRow, out var cRow) && cRow.TryGetValue(region.FirstColumn, out var cCell))
  87. {
  88. cCell.RowSpan = region.LastRow - region.FirstRow + 1;
  89. cCell.ColumnSpan = region.LastColumn - region.FirstColumn + 1;
  90. }
  91. }
  92. var cells = new List<Cell>();
  93. foreach (var row in grid.Values)
  94. {
  95. foreach (var cell in row.Values)
  96. {
  97. cells.Add(cell);
  98. }
  99. }
  100. return cells;
  101. }
  102. private static Regex VariableRegex = new(@"^\[(?<VAR>[^:\]]+)(?::(?<TYPE>[^:\]]*))?(?::(?<PROPERTIES>[^\]]*))?\]$");
  103. private static Regex HeaderRegex = new(@"^{(?<HEADER>[^:}]+)(?::(?<COLLAPSED>[^}]*))?}$");
  104. public static DFLayout LoadLayout(ISpreadsheet spreadsheet)
  105. {
  106. var sheet = spreadsheet.GetSheet(0);
  107. var cells = GetCells(sheet);
  108. int firstRow = int.MaxValue;
  109. int lastRow = 0;
  110. int firstCol = int.MaxValue;
  111. int lastCol = 0;
  112. foreach (var cell in cells)
  113. {
  114. firstCol = Math.Min(cell.Column, firstCol);
  115. lastCol = Math.Max(cell.Column + cell.ColumnSpan - 1, lastCol);
  116. firstRow = Math.Min(cell.Row, firstRow);
  117. lastRow = Math.Max(cell.Row + cell.RowSpan - 1, lastRow);
  118. }
  119. var layout = new DFLayout();
  120. var columnWidths = new Dictionary<int, float>();
  121. var colOffset = 0;
  122. for (int col = firstCol; col <= lastCol; ++col)
  123. {
  124. var width = sheet.GetColumnWidth(col);
  125. if(width == float.MinValue)
  126. {
  127. layout.ColumnWidths.Add("10*");
  128. }
  129. else if(width <= 0f)
  130. {
  131. DeleteColumn(cells, col);
  132. }
  133. else
  134. {
  135. layout.ColumnWidths.Add($"{width}*");
  136. }
  137. }
  138. for (int row = firstRow; row <= lastRow; ++row)
  139. layout.RowHeights.Add("Auto");
  140. foreach(var cell in cells)
  141. {
  142. var style = cell.InnerCell.GetStyle();
  143. if (string.IsNullOrWhiteSpace(cell.Content) && style.Foreground == Color.Empty) continue;
  144. DFLayoutControl? control;
  145. String content = cell.Content?.Trim() ?? "";
  146. var headermatch = HeaderRegex.Match(content);
  147. var variablematch = VariableRegex.Match(content);
  148. if (headermatch.Success)
  149. {
  150. var text = headermatch.Groups["HEADER"];
  151. var collapsed = headermatch.Groups["COLLAPSED"];
  152. var header = new DFLayoutHeader()
  153. {
  154. Header = text.Value,
  155. Collapsed = collapsed.Success ? String.Equals(collapsed.Value.ToUpper(),"COLLAPSED") : false,
  156. Style = CreateStyle(style)
  157. };
  158. control = header;
  159. }
  160. else if (variablematch.Success)
  161. {
  162. var variableName = variablematch.Groups["VAR"];
  163. var variableType = variablematch.Groups["TYPE"];
  164. var variableProps = variablematch.Groups["PROPERTIES"];
  165. Type? fieldType = null;
  166. if (variableType.Success)
  167. fieldType = DFUtils.GetFieldType(variableType.Value);
  168. fieldType ??= typeof(DFLayoutStringField);
  169. var field = (Activator.CreateInstance(fieldType) as DFLayoutField)!;
  170. field.Name = variableName.Value;
  171. if (variableProps.Success)
  172. {
  173. if (field is DFLayoutOptionField option)
  174. option.Properties.Options = variableProps.Value;
  175. if (field is DFLayoutStringField text)
  176. text.Properties.TextWrapping = style.WrapText;
  177. // need to populate other variable types here
  178. }
  179. control = field;
  180. }
  181. else
  182. {
  183. control = new DFLayoutLabel
  184. {
  185. Caption = cell.Content,
  186. Style = CreateStyle(style)
  187. };
  188. }
  189. if(control is not null)
  190. {
  191. control.Row = cell.Row - firstRow + 1;
  192. control.Column = cell.Column - firstCol + 1 - colOffset;
  193. control.RowSpan = cell.RowSpan;
  194. control.ColumnSpan = cell.ColumnSpan;
  195. layout.Elements.Add(control);
  196. }
  197. }
  198. return layout;
  199. }
  200. private static DFLayoutTextStyle CreateStyle(ICellStyle style)
  201. {
  202. if (style == null)
  203. return new DFLayoutTextStyle();
  204. var result = new DFLayoutTextStyle
  205. {
  206. FontSize = style.Font.FontSize,
  207. IsItalic = style.Font.Italic,
  208. IsBold = style.Font.Bold,
  209. Underline = style.Font.Underline switch
  210. {
  211. Scripting.UnderlineType.None => UnderlineType.None,
  212. Scripting.UnderlineType.Single or Scripting.UnderlineType.SingleAccounting => UnderlineType.Single,
  213. Scripting.UnderlineType.Double or Scripting.UnderlineType.DoubleAccounting => UnderlineType.Double,
  214. _ => UnderlineType.None
  215. },
  216. BackgroundColour = style.Background,
  217. ForegroundColour = style.Font.Colour,
  218. HorizontalTextAlignment = style.HorizontalAlignment switch
  219. {
  220. CellAlignment.Middle => DFLayoutAlignment.Middle,
  221. CellAlignment.End => DFLayoutAlignment.End,
  222. CellAlignment.Justify => DFLayoutAlignment.Stretch,
  223. _ => DFLayoutAlignment.Start
  224. },
  225. VerticalTextAlignment = style.VerticalAlignment switch
  226. {
  227. CellAlignment.Start => DFLayoutAlignment.Start,
  228. CellAlignment.End => DFLayoutAlignment.End,
  229. CellAlignment.Justify => DFLayoutAlignment.Stretch,
  230. _ => DFLayoutAlignment.Middle
  231. },
  232. TextWrapping = style.WrapText
  233. };
  234. return result;
  235. }
  236. #endregion
  237. #region Report Generator
  238. public static Report? GenerateReport(DigitalFormLayout layout, DataModel model)
  239. {
  240. var report = ReportUtils.SetupReport(null, model, true);
  241. var dfLayout = new DFLayout();
  242. dfLayout.LoadLayout(layout.Layout);
  243. var page = new ReportPage();
  244. page.Name = "Page1";
  245. page.PaperWidth = 210;
  246. page.PaperHeight = 297;
  247. page.Landscape = false;
  248. page.LeftMargin = 10;
  249. page.TopMargin = 10;
  250. page.RightMargin = 10;
  251. page.BottomMargin = 10;
  252. report.Pages.Add(page);
  253. DataBand band = new DataBand();
  254. band.Name = "Data1";
  255. band.Height = Units.Millimeters * (page.PaperHeight - (page.TopMargin + page.BottomMargin));
  256. band.Width = Units.Millimeters * (page.PaperWidth - (page.LeftMargin + page.RightMargin));
  257. band.PrintIfDatasourceEmpty = true;
  258. band.DataSource = report.GetDataSource("Form_Data");
  259. page.AddChild(band);
  260. TableObject table = new TableObject();
  261. table.ColumnCount = dfLayout.ColumnWidths.Count;
  262. table.RowCount = dfLayout.RowHeights.Count;
  263. ProcessColumnWidths(band.Width, dfLayout.ColumnWidths, table.Columns);
  264. ProcessRowHeights(band.Height, dfLayout.RowHeights, table.Rows);
  265. band.AddChild(table);
  266. foreach(var element in dfLayout.Elements)
  267. {
  268. var row = table.Rows[element.Row-1];
  269. var cell = row.ChildObjects[element.Column-1] as TableCell;
  270. cell.Border.Lines = BorderLines.All;
  271. cell.ColSpan = element.ColumnSpan;
  272. cell.RowSpan = element.RowSpan;
  273. if (element is DFLayoutField field)
  274. {
  275. cell.Text = $"[Form_Data.{field.Name}]";
  276. cell.Font = new System.Drawing.Font(cell.Font.FontFamily, 8F);
  277. }
  278. else if (element is DFLayoutLabel label)
  279. {
  280. cell.Text = label.Description;
  281. ApplyStyle(cell, label.Style);
  282. }
  283. else if (element is DFLayoutHeader header)
  284. {
  285. cell.Text = header.Header;
  286. ApplyStyle(cell, header.Style);
  287. }
  288. }
  289. return report;
  290. }
  291. private static void ApplyStyle(TableCell cell, DFLayoutTextStyle style)
  292. {
  293. cell.FillColor = style.BackgroundColour;
  294. FontStyle fontstyle = System.Drawing.FontStyle.Regular;
  295. if (style.IsBold)
  296. fontstyle = fontstyle | System.Drawing.FontStyle.Bold;
  297. if (style.IsItalic)
  298. fontstyle = fontstyle | System.Drawing.FontStyle.Italic;
  299. float fontsize = (float)style.FontSize * 8F / 12F;
  300. fontsize = fontsize == 0F ? 8F : fontsize;
  301. cell.Font = new System.Drawing.Font(cell.Font.FontFamily, fontsize, fontstyle);
  302. cell.HorzAlign = style.HorizontalTextAlignment switch
  303. {
  304. DFLayoutAlignment.Start => HorzAlign.Left,
  305. DFLayoutAlignment.Middle => HorzAlign.Center,
  306. DFLayoutAlignment.End => HorzAlign.Right,
  307. DFLayoutAlignment.Stretch => HorzAlign.Justify
  308. };
  309. cell.VertAlign = style.VerticalTextAlignment switch
  310. {
  311. DFLayoutAlignment.Start => VertAlign.Top,
  312. DFLayoutAlignment.Middle => VertAlign.Center,
  313. DFLayoutAlignment.End => VertAlign.Bottom,
  314. DFLayoutAlignment.Stretch => VertAlign.Center
  315. };
  316. cell.WordWrap = style.TextWrapping;
  317. }
  318. private static void ProcessRowHeights(float bandheight, List<string> values, TableRowCollection rows)
  319. {
  320. float fixedtotal = 0F;
  321. for (int iFixed = 0; iFixed < values.Count; iFixed++)
  322. {
  323. if (!values[iFixed].Contains("*"))
  324. {
  325. if (!float.TryParse(values[iFixed], out float value))
  326. value = 4F;
  327. rows[iFixed].Height = Units.Millimeters * value;
  328. fixedtotal += Units.Millimeters * value;
  329. }
  330. }
  331. Dictionary<int, float> starvalues = new Dictionary<int, float>();
  332. float startotal = 0F;
  333. for (int iStar = 0; iStar < values.Count; iStar++)
  334. {
  335. float fstartotal = 0F;
  336. if (values[iStar].Contains("*"))
  337. {
  338. if (!float.TryParse(values[iStar].Replace("*", ""), out float value))
  339. value += 1;
  340. starvalues[iStar] = value;
  341. startotal += value;
  342. }
  343. }
  344. foreach (var key in starvalues.Keys)
  345. rows[key].Height = (starvalues[key] / startotal) * (bandheight - fixedtotal);
  346. }
  347. private static void ProcessColumnWidths(float bandwidth, List<string> values, TableColumnCollection columns)
  348. {
  349. float fixedtotal = 0F;
  350. for (int iFixed = 0; iFixed < values.Count; iFixed++)
  351. {
  352. if (!values[iFixed].Contains("*"))
  353. {
  354. if (!float.TryParse(values[iFixed], out float value))
  355. value = 20F;
  356. columns[iFixed].Width = Units.Millimeters * value;
  357. fixedtotal += Units.Millimeters * value;
  358. }
  359. }
  360. Dictionary<int, float> starvalues = new Dictionary<int, float>();
  361. float startotal = 0F;
  362. for (int iStar = 0; iStar < values.Count; iStar++)
  363. {
  364. float fstartotal = 0F;
  365. if (values[iStar].Contains("*"))
  366. {
  367. if (!float.TryParse(values[iStar].Replace("*", ""), out float value))
  368. value += 1;
  369. starvalues[iStar] = value;
  370. startotal += value;
  371. }
  372. }
  373. foreach (var key in starvalues.Keys)
  374. columns[key].Width = (starvalues[key] / startotal) * (bandwidth - fixedtotal);
  375. }
  376. #endregion
  377. #region Data Model
  378. private static List<Type>? _entityForms;
  379. public static DataModel? GetDataModel(String appliesto, IEnumerable<DigitalFormVariable> variables)
  380. {
  381. _entityForms ??= CoreUtils.Entities
  382. .Where(x => x.IsSubclassOfRawGeneric(typeof(EntityForm<,>)))
  383. .ToList();
  384. var entityForm = _entityForms
  385. .Where(x => x.GetSuperclassDefinition(typeof(EntityForm<,>))?.GenericTypeArguments[0].Name == appliesto)
  386. .FirstOrDefault();
  387. if(entityForm is not null)
  388. {
  389. var model = (Activator.CreateInstance(typeof(DigitalFormReportDataModel<>).MakeGenericType(entityForm), Filter.Create(entityForm).None(), null) as DataModel)!;
  390. (model as IDigitalFormReportDataModel)!.Variables = variables.ToArray();
  391. return model;
  392. }
  393. return null;
  394. }
  395. #endregion
  396. }
  397. }