DynamicFormDesignGrid.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Drawing;
  6. using System.Drawing.Design;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Threading.Tasks;
  12. using System.Windows;
  13. using System.Windows.Controls;
  14. using System.Windows.Controls.Primitives;
  15. using System.Windows.Data;
  16. using System.Windows.Documents;
  17. using System.Windows.Media;
  18. using System.Windows.Media.Effects;
  19. using System.Windows.Media.Imaging;
  20. using InABox.Clients;
  21. using InABox.Core;
  22. using InABox.DynamicGrid.Properties;
  23. using InABox.WPF;
  24. using Microsoft.Win32;
  25. using Syncfusion.Windows.Shared;
  26. using Color = System.Drawing.Color;
  27. using Image = System.Windows.Controls.Image;
  28. using Point = System.Windows.Point;
  29. namespace InABox.DynamicGrid
  30. {
  31. public class DynamicFormCreateElementArgs : EventArgs
  32. {
  33. public DynamicFormCreateElementArgs(DFLayoutElement element)
  34. {
  35. Element = element;
  36. }
  37. public DFLayoutElement Element { get; }
  38. }
  39. public delegate FrameworkElement DynamicFormCreateElementDelegate(object sender, DynamicFormCreateElementArgs e);
  40. public delegate void DynamicFormAfterDesignDelegate(object sender);
  41. public delegate void DynamicFormAfterRenderDelegate(DynamicFormDesignGrid sender);
  42. public delegate void DynamicFormOnChangedDelegate(DynamicFormDesignGrid sender, string fieldName);
  43. public enum FormMode
  44. {
  45. /// <summary>
  46. /// The form is read-only.
  47. /// </summary>
  48. ReadOnly,
  49. /// <summary>
  50. /// Standard option for when the form is being filled in by the associated employee.
  51. /// </summary>
  52. Filling,
  53. /// <summary>
  54. /// Standard option for when the form is being previewed - that is, it is acting with placeholder values that will not get saved.
  55. /// It is still editable.
  56. /// </summary>
  57. Preview,
  58. /// <summary>
  59. /// Once the form has been completed, or the person editing is not the employee the form applies to, then they are put in Editing Mode.<br/>
  60. /// This is only possible if <see cref="CanEditCompletedForms"/> is enabled.
  61. /// </summary>
  62. Editing,
  63. /// <summary>
  64. /// The form layout is being designed
  65. /// </summary>
  66. Designing
  67. }
  68. public class DynamicFormDesignGrid : Grid, IDFRenderer
  69. {
  70. //private bool _designing;
  71. public bool GridInitialized { get; private set; } = false;
  72. //private bool _readonly;
  73. private readonly SolidColorBrush BackgroundBrush = new(Colors.WhiteSmoke);
  74. private readonly SolidColorBrush BorderBrush = new(Colors.Silver);
  75. private readonly Dictionary<Type, IDynamicGrid> elementgrids = new();
  76. private readonly Dictionary<DFLayoutControl, FrameworkElement> elementmap = new();
  77. private readonly SolidColorBrush FieldBrush = new(Colors.LightYellow);
  78. private readonly SolidColorBrush RequiredFieldBrush = new(Colors.Orange);
  79. #region Backing Properties
  80. private readonly List<DynamicFormElement> _elements = new();
  81. private bool _showBorders = true;
  82. private IDigitalFormDataModel? _datamodel;
  83. private DFLayout form = new();
  84. private FormMode _mode;
  85. private DigitalFormVariable[] _variables = Array.Empty<DigitalFormVariable>();
  86. private bool _isChanged;
  87. private bool _changing = false;
  88. #endregion
  89. #region Public Properties
  90. public bool ShowBorders
  91. {
  92. get => _showBorders || _mode == FormMode.Designing;
  93. set
  94. {
  95. _showBorders = value;
  96. CheckRefresh();
  97. }
  98. }
  99. public IDigitalFormDataModel? DataModel
  100. {
  101. get => _datamodel;
  102. set
  103. {
  104. _datamodel = value;
  105. if(_datamodel != null)
  106. {
  107. var task = Task.Run(() =>
  108. {
  109. var waiting = true;
  110. _datamodel.Load(m => { waiting = false; });
  111. while (waiting) ;
  112. });
  113. task.Wait();
  114. }
  115. CheckRefresh();
  116. }
  117. }
  118. public DFLayout Form
  119. {
  120. get => form;
  121. set
  122. {
  123. form = value;
  124. form.Renderer = this;
  125. CheckRefresh();
  126. }
  127. }
  128. public FormMode Mode
  129. {
  130. get => _mode;
  131. set
  132. {
  133. if (_mode != value)
  134. {
  135. var oldMode = _mode;
  136. if (_mode == FormMode.Designing)
  137. {
  138. OnAfterDesign?.Invoke(this);
  139. }
  140. _mode = value;
  141. CheckRefresh(oldMode != FormMode.Designing);
  142. }
  143. }
  144. }
  145. public bool IsDesigning { get => _mode == FormMode.Designing; }
  146. public bool IsReadOnly { get => _mode == FormMode.ReadOnly; }
  147. public bool IsEditing { get => _mode == FormMode.Editing || _mode == FormMode.Filling; }
  148. public bool IsChanged => _isChanged;
  149. public DigitalFormVariable[] Variables
  150. {
  151. get => _variables;
  152. set
  153. {
  154. _variables = value;
  155. CheckRefresh();
  156. }
  157. }
  158. #endregion
  159. #region Events
  160. public event DynamicFormAfterDesignDelegate? OnAfterDesign;
  161. public event DynamicFormCreateElementDelegate? OnCreateElement;
  162. public event DynamicFormAfterRenderDelegate? OnAfterRender;
  163. public event DynamicFormOnChangedDelegate? OnChanged;
  164. #endregion
  165. #region Rows
  166. class RowData
  167. {
  168. public string RowHeight { get; set; }
  169. public RowData(string rowHeight)
  170. {
  171. RowHeight = rowHeight;
  172. }
  173. }
  174. internal void CollapseRows(FormHeader header, bool collapsed)
  175. {
  176. var startRow = this.GetRow(header) + this.GetRowSpan(header);
  177. var nextRow = elementmap
  178. .Where(x => x.Value is DFHeaderControl headerControl && headerControl.Header != header)
  179. .Select(x => this.GetRow(x.Value))
  180. .Where(x => x >= startRow).DefaultIfEmpty(-1).Min();
  181. if (nextRow == -1)
  182. {
  183. nextRow = RowDefinitions.Count;
  184. }
  185. for (int row = startRow; row < nextRow; ++row)
  186. {
  187. var rowDefinition = RowDefinitions[row];
  188. if(rowDefinition.Tag is not RowData rowData)
  189. {
  190. throw new Exception("Row definition tag is not RowData");
  191. }
  192. if (collapsed)
  193. {
  194. rowDefinition.Height = new GridLength(0);
  195. }
  196. else
  197. {
  198. rowDefinition.Height = StringToGridLength(rowData.RowHeight);
  199. }
  200. }
  201. }
  202. #endregion
  203. #region Elements
  204. class DynamicFormElement
  205. {
  206. public string Caption { get; set; }
  207. public Type ElementType { get; set; }
  208. public string Category { get; set; }
  209. public FrameworkElement? Element { get; set; }
  210. public bool AllowDuplicate { get; set; }
  211. public DynamicFormElement(string caption, Type elementType, string category, FrameworkElement? element, bool allowDuplicate)
  212. {
  213. Caption = caption;
  214. ElementType = elementType;
  215. Category = category;
  216. Element = element;
  217. AllowDuplicate = allowDuplicate;
  218. }
  219. }
  220. public void AddElement<TElement>(string caption, string category, bool allowduplicate = false)
  221. where TElement : DFLayoutElement
  222. {
  223. AddElement(typeof(TElement), caption, category, allowduplicate);
  224. }
  225. public void AddElement(Type TElement, string caption, string category, bool allowduplicate = false)
  226. {
  227. _elements.Add(new DynamicFormElement(caption, TElement, category, null, allowduplicate));
  228. }
  229. internal FrameworkElement? CreateElement(DFLayoutElement element)
  230. {
  231. var elementType = element.GetType();
  232. if(_elements.Any(x => x.ElementType == elementType))
  233. {
  234. return OnCreateElement?.Invoke(this, new DynamicFormCreateElementArgs(element));
  235. }
  236. return null;
  237. }
  238. #endregion
  239. #region Utilities
  240. private static VerticalAlignment GetVerticalAlignment(DFLayoutAlignment alignment)
  241. {
  242. return alignment == DFLayoutAlignment.Start
  243. ? VerticalAlignment.Top
  244. : alignment == DFLayoutAlignment.End
  245. ? VerticalAlignment.Bottom
  246. : alignment == DFLayoutAlignment.Middle
  247. ? VerticalAlignment.Center
  248. : VerticalAlignment.Stretch;
  249. }
  250. private static HorizontalAlignment GetHorizontalAlignment(DFLayoutAlignment alignment)
  251. {
  252. return alignment == DFLayoutAlignment.Start
  253. ? HorizontalAlignment.Left
  254. : alignment == DFLayoutAlignment.End
  255. ? HorizontalAlignment.Right
  256. : alignment == DFLayoutAlignment.Middle
  257. ? HorizontalAlignment.Center
  258. : HorizontalAlignment.Stretch;
  259. }
  260. private static GridLength StringToGridLength(string length)
  261. {
  262. if (string.IsNullOrWhiteSpace(length) || string.Equals(length.ToUpper(), "AUTO"))
  263. return new GridLength(1, GridUnitType.Auto);
  264. if (!double.TryParse(length.Replace("*", ""), out var value))
  265. value = 1.0F;
  266. var type = length.Contains('*') ? GridUnitType.Star : GridUnitType.Pixel;
  267. return new GridLength(value, type);
  268. }
  269. private static string GridLengthToString(GridLength length)
  270. {
  271. if (length.IsStar)
  272. return length.Value == 1.0F ? "*" : string.Format("{0}*", length.Value);
  273. if (length.IsAuto)
  274. return "Auto";
  275. return length.Value.ToString();
  276. }
  277. private static string FormatGridLength(GridLength length, IEnumerable<GridLength> others)
  278. {
  279. if (length.IsStar)
  280. {
  281. double total = 0.0F;
  282. foreach (var other in others.Where(x => x.IsStar))
  283. total += other.Value;
  284. return string.Format("{0:F0}%", total != 0 ? length.Value * 100.0F / total : 0);
  285. }
  286. if (length.IsAuto)
  287. return "Auto";
  288. return string.Format("{0}px", length.Value);
  289. }
  290. private static MenuItem CreateMenuItem<TTag>(string caption, TTag tag, Action<TTag>? click)
  291. {
  292. var result = new MenuItem { Header = caption, Tag = tag };
  293. if (click != null)
  294. result.Click += (o, e) => click((TTag)(o as MenuItem)!.Tag);
  295. return result;
  296. }
  297. private static void AddClick<TTag>(ButtonBase button, TTag tag, Action<TTag> click)
  298. {
  299. button.Tag = tag;
  300. button.Click += (o, e) => click((TTag)(o as MenuItem)!.Tag);
  301. }
  302. #endregion
  303. #region Design Mode
  304. #region Rows
  305. private void ShiftDown(int row)
  306. {
  307. foreach (var element in form.Elements)
  308. if (element.Row > row)
  309. element.Row++;
  310. else if (element.Row + element.RowSpan - 1 > row)
  311. element.RowSpan++;
  312. }
  313. private void AddRowBeforeClick(int row)
  314. {
  315. var length = new GridLength(1.0F, GridUnitType.Auto);
  316. var result = GridLengthToString(length);
  317. if (form.RowHeights.Count == 0)
  318. form.RowHeights.Add(result);
  319. else
  320. form.RowHeights.Insert(row, result);
  321. ShiftDown(row);
  322. Render();
  323. }
  324. private void AddRowAfterClick(int row)
  325. {
  326. var length = new GridLength(1.0F, GridUnitType.Auto);
  327. var result = GridLengthToString(length);
  328. if (row == form.RowHeights.Count - 1)
  329. form.RowHeights.Add(result);
  330. else
  331. form.RowHeights.Insert(row + 1, result);
  332. ShiftDown(row + 1);
  333. Render();
  334. }
  335. private void SplitRow(int row)
  336. {
  337. foreach (var element in form.Elements)
  338. if (element.Row > row)
  339. element.Row++;
  340. else if (element.Row == row)
  341. element.RowSpan++;
  342. else if (element.Row + element.RowSpan - 1 >= row)
  343. element.RowSpan++;
  344. }
  345. private void SplitRowClick(int row)
  346. {
  347. var result = form.RowHeights[row];
  348. if (row == form.RowHeights.Count - 1)
  349. form.RowHeights.Add(result);
  350. else
  351. form.RowHeights.Insert(row + 1, result);
  352. SplitRow(row + 1);
  353. Render();
  354. }
  355. private void RowPropertiesClick(int row)
  356. {
  357. var length = StringToGridLength(form.RowHeights[row]);
  358. var editor = new DynamicFormDesignLength(length);
  359. if (editor.ShowDialog() == true)
  360. {
  361. form.RowHeights[row] = GridLengthToString(editor.GridLength);
  362. Render();
  363. }
  364. }
  365. private void ShiftUp(int row)
  366. {
  367. var deletes = new List<DFLayoutControl>();
  368. foreach (var element in form.Elements)
  369. if (element.Row > row)
  370. element.Row--;
  371. else if (element.Row == row)
  372. deletes.Add(element);
  373. else if (element.Row + element.RowSpan - 1 >= row)
  374. element.RowSpan--;
  375. foreach (var delete in deletes)
  376. form.Elements.Remove(delete);
  377. }
  378. private void DeleteRowClick(int row)
  379. {
  380. form.RowHeights.RemoveAt(row);
  381. ShiftUp(row + 1);
  382. Render();
  383. }
  384. private ContextMenu CreateRowMenu(Button button, int row)
  385. {
  386. var result = new ContextMenu();
  387. result.Items.Add(CreateMenuItem("Add Row Before", row, AddRowBeforeClick));
  388. result.Items.Add(CreateMenuItem("Add Row After", row, AddRowAfterClick));
  389. result.Items.Add(new Separator());
  390. result.Items.Add(CreateMenuItem("Split Row", row, SplitRowClick));
  391. var propertiesSeparator = new Separator();
  392. var propertiesMenu = CreateMenuItem("Row Properties", row, RowPropertiesClick);
  393. result.Items.Add(propertiesSeparator);
  394. result.Items.Add(propertiesMenu);
  395. result.Items.Add(new Separator());
  396. result.Items.Add(CreateMenuItem("Delete Row", row, DeleteRowClick));
  397. result.Opened += (o, e) =>
  398. {
  399. propertiesSeparator.Visibility = form.RowHeights.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
  400. propertiesMenu.Visibility = form.RowHeights.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
  401. };
  402. button.SetValue(ContextMenuProperty, result);
  403. return result;
  404. }
  405. #endregion
  406. #region Columns
  407. private void ShiftRight(int column)
  408. {
  409. foreach (var element in form.Elements)
  410. if (element.Column > column)
  411. element.Column++;
  412. else if (element.Column + element.ColumnSpan - 1 > column)
  413. element.ColumnSpan++;
  414. }
  415. private void AddColumnBeforeClick(int column)
  416. {
  417. var length = new GridLength(1.0F, form.ColumnWidths.Count == 0 ? GridUnitType.Star : GridUnitType.Auto);
  418. var result = GridLengthToString(length);
  419. if (form.ColumnWidths.Count == 0)
  420. form.ColumnWidths.Add(result);
  421. else
  422. form.ColumnWidths.Insert(column, result);
  423. ShiftRight(column);
  424. Render();
  425. }
  426. private void AddColumnAfterClick(int column)
  427. {
  428. var length = new GridLength(1.0F, form.ColumnWidths.Count == 0 ? GridUnitType.Star : GridUnitType.Auto);
  429. var result = GridLengthToString(length);
  430. if (column == form.ColumnWidths.Count - 1)
  431. form.ColumnWidths.Add(result);
  432. else
  433. form.ColumnWidths.Insert(column + 1, result);
  434. ShiftRight(column + 1);
  435. Render();
  436. }
  437. private void SplitColumn(int column)
  438. {
  439. foreach (var element in form.Elements)
  440. if (element.Column > column)
  441. element.Column++;
  442. else if (element.Column == column)
  443. element.ColumnSpan++;
  444. else if (element.Column + element.ColumnSpan - 1 >= column)
  445. element.ColumnSpan++;
  446. }
  447. private void SplitColumnClick(int column)
  448. {
  449. var result = form.ColumnWidths[column];
  450. if (column == form.ColumnWidths.Count - 1)
  451. form.ColumnWidths.Add(result);
  452. else
  453. form.ColumnWidths.Insert(column + 1, result);
  454. SplitColumn(column + 1);
  455. Render();
  456. }
  457. private void ColumnPropertiesClick(int column)
  458. {
  459. var length = StringToGridLength(form.ColumnWidths[column]);
  460. var editor = new DynamicFormDesignLength(length);
  461. if (editor.ShowDialog() == true)
  462. {
  463. form.ColumnWidths[column] = GridLengthToString(editor.GridLength);
  464. Render();
  465. }
  466. }
  467. private void ShiftLeft(int column)
  468. {
  469. var deletes = new List<DFLayoutControl>();
  470. foreach (var element in form.Elements)
  471. if (element.Column > column)
  472. element.Column--;
  473. else if (element.Column == column)
  474. deletes.Add(element);
  475. else if (element.Column + element.ColumnSpan - 1 >= column)
  476. element.ColumnSpan--;
  477. foreach (var delete in deletes)
  478. form.Elements.Remove(delete);
  479. }
  480. private void DeleteColumnClick(int column)
  481. {
  482. form.ColumnWidths.RemoveAt(column);
  483. ShiftLeft(column + 1);
  484. Render();
  485. }
  486. private ContextMenu CreateColumnMenu(Button button, int column)
  487. {
  488. var result = new ContextMenu();
  489. result.Items.Add(CreateMenuItem("Add Column Before", column, AddColumnBeforeClick));
  490. result.Items.Add(CreateMenuItem("Add Column After", column, AddColumnAfterClick));
  491. result.Items.Add(new Separator());
  492. result.Items.Add(CreateMenuItem("Split Column", column, SplitColumnClick));
  493. var propertiesSeparator = new Separator();
  494. var propertiesMenu = CreateMenuItem("Column Properties", column, ColumnPropertiesClick);
  495. result.Items.Add(propertiesSeparator);
  496. result.Items.Add(propertiesMenu);
  497. result.Items.Add(new Separator());
  498. result.Items.Add(CreateMenuItem("Delete Column", column, DeleteColumnClick));
  499. result.Opened += (o, e) =>
  500. {
  501. propertiesSeparator.Visibility = form.ColumnWidths.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
  502. propertiesMenu.Visibility = form.ColumnWidths.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
  503. };
  504. button.SetValue(ContextMenuProperty, result);
  505. return result;
  506. }
  507. #endregion
  508. #region Add Element
  509. private void AddNewElement<TElement>(int row, int column)
  510. where TElement : DFLayoutElement, new()
  511. {
  512. var element = new TElement();
  513. element.Row = row;
  514. element.Column = column;
  515. var result = new FormControlGrid<TElement>().EditItems(new[] { element });
  516. if (result)
  517. {
  518. form.Elements.Add(element);
  519. Render();
  520. }
  521. }
  522. private void AddElementClick(Tuple<Type, int, int> tuple)
  523. {
  524. var method = typeof(DynamicFormDesignGrid)
  525. .GetMethod(nameof(AddNewElement), BindingFlags.NonPublic | BindingFlags.Instance)!
  526. .MakeGenericMethod(tuple.Item1);
  527. method.Invoke(this, new object[] { tuple.Item3, tuple.Item2 });
  528. }
  529. private void CreateLabelClick(Point point)
  530. {
  531. var label = new DFLayoutLabel
  532. {
  533. Row = (int)point.Y,
  534. Column = (int)point.X
  535. };
  536. var result = new FormControlGrid<DFLayoutLabel>().EditItems(new[] { label });
  537. if (result)
  538. {
  539. form.Elements.Add(label);
  540. Render();
  541. }
  542. }
  543. private void CreateHeaderClick(Point point)
  544. {
  545. var header = new DFLayoutHeader
  546. {
  547. Row = (int)point.Y,
  548. Column = (int)point.X
  549. };
  550. var result = new FormControlGrid<DFLayoutHeader>().EditItems(new[] { header });
  551. if (result)
  552. {
  553. form.Elements.Add(header);
  554. Render();
  555. }
  556. }
  557. private void CreateImageClick(Point point)
  558. {
  559. var image = new DFLayoutImage
  560. {
  561. Row = (int)point.Y,
  562. Column = (int)point.X
  563. };
  564. var result = new FormControlGrid<DFLayoutImage>().EditItems(new[] { image });
  565. if (result)
  566. {
  567. form.Elements.Add(image);
  568. Render();
  569. }
  570. }
  571. private void AddVariableClick(Tuple<DigitalFormVariable, int, int> tuple)
  572. {
  573. if(Activator.CreateInstance(tuple.Item1.FieldType()) is not DFLayoutField field)
  574. {
  575. MessageBox.Show(string.Format("{0}: Unknown Type {1}", tuple.Item1.Code, tuple.Item1.VariableType.ToString()));
  576. return;
  577. }
  578. field.Name = tuple.Item1.Code;
  579. field.Column = tuple.Item2;
  580. field.Row = tuple.Item3;
  581. form.Elements.Add(field);
  582. form.LoadVariable(tuple.Item1, field);
  583. Render();
  584. }
  585. private ContextMenu CreateEmptyCellMenu(Border border, int row, int column)
  586. {
  587. var result = new ContextMenu();
  588. result.Opened += (o, e) =>
  589. {
  590. result.Items.Clear();
  591. result.Items.Add(CreateMenuItem("Add Label", new Point(column, row), CreateLabelClick));
  592. result.Items.Add(CreateMenuItem("Add Header", new Point(column, row), CreateHeaderClick));
  593. result.Items.Add(CreateMenuItem("Add Image", new Point(column, row), CreateImageClick));
  594. var fields = CreateMenuItem("Add Field", new Point(column, row), null);
  595. var filtered = _variables.Where(x => !form.Elements.Any(v => string.Equals((v as DFLayoutField)?.Name, x.Code)));
  596. foreach (var variable in filtered)
  597. fields.Items.Add(CreateMenuItem(variable.Code, new Tuple<DigitalFormVariable, int, int>(variable, column, row),
  598. AddVariableClick));
  599. if (fields.Items.Count > 0)
  600. result.Items.Add(fields);
  601. var elements = CreateMenuItem("Add Object", new Point(column, row), null);
  602. var available = _elements.Where(x => x.AllowDuplicate || !form.Elements.Any(v => (v as DFLayoutElement)?.GetType() == x.ElementType)).ToArray();
  603. var cats = available.Select(x => x.Category).Distinct().OrderBy(x => x);
  604. foreach (var cat in cats)
  605. {
  606. var menu = elements;
  607. if (!string.IsNullOrWhiteSpace(cat))
  608. {
  609. menu = new MenuItem { Header = cat };
  610. elements.Items.Add(menu);
  611. }
  612. foreach (var element in available.Where(x => string.Equals(x.Category, cat)))
  613. menu.Items.Add(CreateMenuItem(element.Caption, new Tuple<Type, int, int>(element.ElementType, column, row), AddElementClick));
  614. }
  615. if (elements.Items.Count > 0)
  616. result.Items.Add(elements);
  617. };
  618. border.SetValue(ContextMenuProperty, result);
  619. return result;
  620. }
  621. #endregion
  622. #region Element Context Menu
  623. private void DeleteElementClick(DFLayoutControl control)
  624. {
  625. if (form.Elements.Contains(control))
  626. {
  627. form.Elements.Remove(control);
  628. Render();
  629. }
  630. }
  631. private void ElementPropertiesClick(DFLayoutControl control)
  632. {
  633. if(!elementgrids.TryGetValue(control.GetType(), out var grid))
  634. {
  635. var type = typeof(FormControlGrid<>).MakeGenericType(control.GetType());
  636. grid = (Activator.CreateInstance(type) as IDynamicGrid)!;
  637. elementgrids[control.GetType()] = grid;
  638. }
  639. if (grid.EditItems(new[] { control }))
  640. Render();
  641. }
  642. private ContextMenu CreateElementContextMenu(FrameworkElement element, DFLayoutControl control)
  643. {
  644. var result = new ContextMenu();
  645. result.Items.Add(CreateMenuItem("Edit Properties", control, ElementPropertiesClick));
  646. result.Items.Add(new Separator());
  647. result.Items.Add(CreateMenuItem("Delete Item", control, DeleteElementClick));
  648. element.SetValue(ContextMenuProperty, result);
  649. return result;
  650. }
  651. #endregion
  652. #endregion
  653. #region Render
  654. private static void SetDimensions(FrameworkElement element, int row, int column, int rowspan, int colspan, int offset)
  655. {
  656. if (column <= 0) return;
  657. if (row <= 0) return;
  658. element.MinHeight = 50.0F;
  659. element.MinWidth = 50.0F;
  660. element.SetGridPosition(row - offset, column - offset, rowspan, colspan);
  661. }
  662. private Border CreateBorder(int row, int column, int rowspan, int colspan, int offset, bool horzstar, bool vertstar)
  663. {
  664. var border = new Border();
  665. if (ShowBorders)
  666. {
  667. border.BorderThickness = new Thickness(
  668. 0.0F,//!IsDesigning && column == 1 - offset ? 0.00F /*0.75F*/ : 0.0F,
  669. 0.0F,//!IsDesigning && row == 1 - offset ? 0.00F /*0.75F*/ : 0.0F,
  670. column - offset == ColumnDefinitions.Count - 1 ? horzstar ? 0.00F : 0.75F : 0.75F,
  671. row - offset == RowDefinitions.Count - 1 ? vertstar ? 0.00F : 0.75F : 0.75F
  672. );
  673. border.BorderBrush = BorderBrush;
  674. }
  675. border.Background = BackgroundBrush;
  676. SetDimensions(border, row, column, rowspan, colspan, offset);
  677. return border;
  678. }
  679. private static BitmapImage HeaderClosed = Properties.Resources.rightarrow.AsBitmapImage(32, 32);
  680. private static BitmapImage HeaderOpen = Properties.Resources.downarrow.AsBitmapImage(32, 32);
  681. private FrameworkElement CreateHeader(DFLayoutHeader header)
  682. {
  683. var formHeader = new FormHeader
  684. {
  685. Collapsed = header.Collapsed,
  686. HeaderText = header.Header
  687. };
  688. formHeader.CollapsedChanged += (o, c) =>
  689. {
  690. CollapseRows(formHeader, c);
  691. };
  692. if (IsDesigning)
  693. {
  694. formHeader.IsEnabled = false;
  695. }
  696. return formHeader;
  697. }
  698. // DFLayoutField -> IDynamicFormFieldControl
  699. private static Dictionary<Type, Type>? _fieldControls;
  700. private DynamicFormControl? CreateFieldControl(DFLayoutField field)
  701. {
  702. if (_fieldControls == null)
  703. {
  704. _fieldControls = new();
  705. foreach (var controlType in CoreUtils.TypeList(
  706. AppDomain.CurrentDomain.GetAssemblies(),
  707. x => x.IsClass
  708. && !x.IsAbstract
  709. && !x.IsGenericType
  710. && x.IsAssignableTo(typeof(IDynamicFormFieldControl))))
  711. {
  712. var superDefinition = controlType.GetSuperclassDefinition(typeof(DynamicFormFieldControl<,,>));
  713. if (superDefinition != null)
  714. {
  715. _fieldControls[superDefinition.GenericTypeArguments[0]] = controlType;
  716. }
  717. }
  718. }
  719. var fieldControlType = _fieldControls.GetValueOrDefault(field.GetType());
  720. if (fieldControlType is not null)
  721. {
  722. var element = (Activator.CreateInstance(fieldControlType) as DynamicFormControl)!;
  723. if(element is IDynamicFormFieldControl fieldControl)
  724. {
  725. fieldControl.FieldChangedEvent += () =>
  726. {
  727. ChangeField(field.Name);
  728. };
  729. }
  730. return element;
  731. }
  732. return null;
  733. }
  734. private DynamicFormControl? CreateFieldPlaceholder(DFLayoutField field)
  735. {
  736. var controlType = typeof(DFFieldPlaceholderControl<>).MakeGenericType(field.GetType());
  737. return Activator.CreateInstance(controlType) as DynamicFormControl;
  738. }
  739. private DynamicFormControl? CreateControl(DFLayoutControl item)
  740. {
  741. if (item is DFLayoutField field)
  742. {
  743. if (IsDesigning)
  744. {
  745. return CreateFieldPlaceholder(field);
  746. }
  747. return CreateFieldControl(field);
  748. }
  749. else if (item is DFLayoutElement)
  750. {
  751. return IsDesigning
  752. ? new DFElementPlaceholderControl()
  753. : new DFElementControl();
  754. }
  755. else if (item is DFLayoutLabel)
  756. {
  757. return new DFLabelControl();
  758. }
  759. else if (item is DFLayoutHeader)
  760. {
  761. return new DFHeaderControl();
  762. }
  763. else if (item is DFLayoutImage)
  764. {
  765. return new DFImageControl();
  766. }
  767. return null;
  768. }
  769. private FrameworkElement? CreateElement(DFLayoutControl item)
  770. {
  771. var control = CreateControl(item);
  772. if(control != null)
  773. {
  774. control.FormDesignGrid = this;
  775. control.SetControl(item);
  776. }
  777. return control;
  778. }
  779. private void RenderElement(DFLayoutControl item, int offset, bool horzstar, bool vertstar)
  780. {
  781. var border = CreateBorder(item.Row, item.Column, item.RowSpan, item.ColumnSpan, offset, horzstar, vertstar);
  782. if (item is DFLayoutField field)
  783. border.Background = field.GetPropertyValue<bool>("Required") ? RequiredFieldBrush : FieldBrush;
  784. else
  785. border.Background = IsDesigning ? FieldBrush : BackgroundBrush;
  786. if (!ShowBorders)
  787. border.Padding = new Thickness(
  788. item.Column == 1 ? 4 : 2,
  789. item.Row == 1 ? 4 : 2,
  790. item.Column + item.ColumnSpan - 1 == ColumnDefinitions.Count ? 4 : 2,
  791. item.Row + item.RowSpan - 1 == RowDefinitions.Count ? 4 : 2
  792. );
  793. else
  794. border.Padding = new Thickness(5);
  795. var element = CreateElement(item);
  796. border.Child = element;
  797. Children.Add(border);
  798. if (IsDesigning)
  799. {
  800. CreateElementContextMenu(border, item);
  801. }
  802. if (element != null)
  803. {
  804. if(item is DFLayoutField)
  805. {
  806. element.IsEnabled = !IsReadOnly;
  807. }
  808. elementmap[item] = element;
  809. element.HorizontalAlignment = GetHorizontalAlignment(item.HorizontalAlignment);
  810. element.VerticalAlignment = GetVerticalAlignment(item.VerticalAlignment);
  811. if (IsDesigning)
  812. {
  813. CreateElementContextMenu(element, item);
  814. }
  815. }
  816. }
  817. private void AfterRender()
  818. {
  819. if (!IsDesigning)
  820. {
  821. foreach (var header in elementmap.Where(x => x.Value is FormHeader head).Select(x => x.Value).Cast<FormHeader>())
  822. {
  823. if (header.Collapsed)
  824. {
  825. CollapseRows(header, true);
  826. }
  827. }
  828. }
  829. OnAfterRender?.Invoke(this);
  830. }
  831. private void Render()
  832. {
  833. foreach (var item in elementmap.Keys)
  834. {
  835. var e = elementmap[item];
  836. if (VisualTreeHelper.GetParent(e) is Border parent)
  837. parent.Child = null;
  838. }
  839. elementmap.Clear();
  840. Children.Clear();
  841. ColumnDefinitions.Clear();
  842. RowDefinitions.Clear();
  843. if (form == null)
  844. return;
  845. foreach (var column in form.ColumnWidths)
  846. ColumnDefinitions.Add(new ColumnDefinition { Width = StringToGridLength(column) });
  847. foreach (var row in form.RowHeights)
  848. RowDefinitions.Add(new RowDefinition { Height = StringToGridLength(row), Tag = new RowData(row) });
  849. var horzstar = ColumnDefinitions.Any(x => x.Width.IsStar);
  850. var vertstar = RowDefinitions.Any(x => x.Height.IsStar);
  851. var offset = 1;
  852. if (IsDesigning)
  853. {
  854. ColumnDefinitions.Insert(0, new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
  855. RowDefinitions.Insert(0, new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  856. var topleft = new Button();
  857. topleft.SetValue(RowProperty, 0);
  858. topleft.SetValue(ColumnProperty, 0);
  859. topleft.Content =
  860. ""; // new Image() { Source = _designing ? Properties.Resources.view.AsBitmapImage() : Properties.Resources.design.AsBitmapImage() };
  861. topleft.BorderBrush = BorderBrush;
  862. topleft.BorderThickness = new Thickness(
  863. 0.00F,
  864. 0.00F,
  865. 0.75F,
  866. 0.75F
  867. );
  868. topleft.Background = BackgroundBrush;
  869. //topleft.Click += (o, e) =>
  870. //{
  871. // Designing = !Designing;
  872. //};
  873. Children.Add(topleft);
  874. for (var i = 1; i < ColumnDefinitions.Count; i++)
  875. {
  876. var Button = new Button();
  877. Button.SetValue(RowProperty, 0);
  878. Button.SetValue(ColumnProperty, i);
  879. Button.Content = FormatGridLength(ColumnDefinitions[i].Width, ColumnDefinitions.Select(x => x.Width));
  880. Button.BorderBrush = BorderBrush;
  881. Button.BorderThickness = new Thickness(
  882. 0.00F, //(i == 1) ? 0.75F : 0.0F,
  883. 0.00F, //0.75F,
  884. i == ColumnDefinitions.Count - 1 ? horzstar ? 0.00F : 0.75F : 0.75F,
  885. 0.75F
  886. );
  887. Button.Background = BackgroundBrush;
  888. Button.Padding = new Thickness(10);
  889. Button.MinHeight = 35;
  890. CreateColumnMenu(Button, i - 1);
  891. AddClick(Button, i - 1, ColumnPropertiesClick);
  892. Children.Add(Button);
  893. }
  894. for (var i = 1; i < RowDefinitions.Count; i++)
  895. {
  896. var Button = new Button();
  897. Button.SetValue(RowProperty, i);
  898. Button.SetValue(ColumnProperty, 0);
  899. Button.Content = FormatGridLength(RowDefinitions[i].Height, RowDefinitions.Select(x => x.Height));
  900. Button.BorderBrush = BorderBrush;
  901. Button.BorderThickness = new Thickness(
  902. 0.00F, //0.75F,
  903. 0.00F, //(i == 1) ? 0.75F : 0.0F,
  904. 0.75F,
  905. i == RowDefinitions.Count - 1 ? vertstar ? 0.00F : 0.75F : 0.75F
  906. );
  907. Button.Background = BackgroundBrush;
  908. Button.Padding = new Thickness(10);
  909. CreateRowMenu(Button, i - 1);
  910. AddClick(Button, i - 1, RowPropertiesClick);
  911. Children.Add(Button);
  912. }
  913. offset = 0;
  914. }
  915. var filledcells = new List<Point>();
  916. foreach (var item in form.Elements)
  917. {
  918. try
  919. {
  920. if(item.Row > 0 && item.Column > 0)
  921. {
  922. RenderElement(item, offset, horzstar, vertstar);
  923. for (var c = item.Column; c < item.Column + item.ColumnSpan; c++)
  924. for (var r = item.Row; r < item.Row + item.RowSpan; r++)
  925. filledcells.Add(new Point(c, r));
  926. }
  927. }
  928. catch (Exception e)
  929. {
  930. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  931. }
  932. }
  933. for (var c = 1; c <= form.ColumnWidths.Count; c++)
  934. for (var r = 1; r <= form.RowHeights.Count; r++)
  935. if (!filledcells.Any(x => x.X.Equals(c) && x.Y.Equals(r)))
  936. {
  937. var border = CreateBorder(r, c, 1, 1, offset, horzstar, vertstar);
  938. if (IsDesigning)
  939. {
  940. CreateEmptyCellMenu(border, r, c);
  941. }
  942. Children.Add(border);
  943. }
  944. AfterRender();
  945. }
  946. #endregion
  947. /// <summary>
  948. /// Renders the form; after this is called, any changes to properties triggers a refresh.
  949. /// </summary>
  950. /// <remarks>
  951. /// This should be called before <see cref="LoadValues(Dictionary{string, object})"/> or <see cref="SaveValues"/>
  952. /// </remarks>
  953. public void Initialize()
  954. {
  955. GridInitialized = true;
  956. CheckRefresh(false);
  957. }
  958. private void CheckRefresh(bool keepValues = true)
  959. {
  960. if (!GridInitialized) return;
  961. if (_mode == FormMode.Designing)
  962. {
  963. Render();
  964. }
  965. else if(keepValues)
  966. {
  967. var values = SaveValues();
  968. Render();
  969. LoadValues(values);
  970. }
  971. else
  972. {
  973. Render();
  974. Form.EvaluateExpressions();
  975. }
  976. }
  977. #region Fields
  978. private void ChangeField(string fieldName)
  979. {
  980. if (!_changing)
  981. {
  982. form.ChangeField(fieldName);
  983. _isChanged = true;
  984. OnChanged?.Invoke(this, fieldName);
  985. }
  986. }
  987. private IDynamicFormFieldControl? GetFieldControl(DFLayoutField field)
  988. {
  989. return elementmap.GetValueOrDefault(field) as IDynamicFormFieldControl;
  990. }
  991. public void SetFieldValue(string fieldName, object? value)
  992. {
  993. var field = form.Elements.FirstOrDefault(x => string.Equals(fieldName, (x as DFLayoutField)?.Name)) as DFLayoutField;
  994. if (field != null)
  995. {
  996. value = field.ParseValue(value);
  997. var fieldControl = GetFieldControl(field);
  998. if (fieldControl != null)
  999. {
  1000. string? property = null;
  1001. if(DataModel != null)
  1002. {
  1003. property = field.GetPropertyValue<string>("Property");
  1004. if (!string.IsNullOrWhiteSpace(property))
  1005. {
  1006. value = DataModel.GetEntityValue(property);
  1007. }
  1008. }
  1009. if (string.IsNullOrWhiteSpace(property))
  1010. {
  1011. fieldControl.SetValue(value);
  1012. }
  1013. else
  1014. {
  1015. fieldControl.SetEntityValue(value);
  1016. }
  1017. }
  1018. }
  1019. }
  1020. private object? GetFieldValue(DFLayoutField field, out object? entityValue)
  1021. {
  1022. var fieldControl = GetFieldControl(field);
  1023. if(fieldControl != null)
  1024. {
  1025. entityValue = fieldControl.GetEntityValue();
  1026. return fieldControl.GetValue();
  1027. }
  1028. entityValue = null;
  1029. return null;
  1030. }
  1031. public object? GetFieldValue(string fieldName)
  1032. {
  1033. var field = form.Elements.Where(x => (x as DFLayoutField)?.Name == fieldName).FirstOrDefault() as DFLayoutField;
  1034. if (field == null)
  1035. {
  1036. return null;
  1037. }
  1038. return GetFieldValue(field, out var entityValue);
  1039. }
  1040. /// <summary>
  1041. /// Load values into editor; Must be called after <see cref="Initialize"/>.
  1042. /// </summary>
  1043. /// <remarks>
  1044. /// Resets <see cref="IsChanged"/>.
  1045. /// </remarks>
  1046. /// <param name="values">A dictionary of <see cref="DigitalFormVariable.Code"/> -> value.</param>
  1047. public void LoadValues(Dictionary<string, object> values)
  1048. {
  1049. _changing = true;
  1050. foreach (var (name, value) in values)
  1051. {
  1052. SetFieldValue(name, value);
  1053. }
  1054. Form.EvaluateExpressions();
  1055. _changing = false;
  1056. _isChanged = false;
  1057. }
  1058. /// <summary>
  1059. /// Takes values from editors and saves them to a dictionary; must be called after <see cref="Initialize"/>.
  1060. /// </summary>
  1061. /// <returns>A dictionary of <see cref="DigitalFormVariable.Code"/> -> value.</returns>
  1062. public Dictionary<string, object> SaveValues()
  1063. {
  1064. var result = new Dictionary<string, object>();
  1065. foreach (var formElement in form.Elements)
  1066. if (formElement is DFLayoutField field)
  1067. {
  1068. var value = GetFieldValue(field, out var entityValue);
  1069. if (value != null)
  1070. result[field.Name] = value;
  1071. if(DataModel != null)
  1072. {
  1073. var property = field.GetPropertyValue<string>("Property");
  1074. if (!string.IsNullOrWhiteSpace(property))
  1075. DataModel.SetEntityValue(property, entityValue);
  1076. }
  1077. }
  1078. return result;
  1079. }
  1080. public bool Validate(out List<string> messages)
  1081. {
  1082. messages = new List<string>();
  1083. var valid = true;
  1084. foreach(var formElement in form.Elements)
  1085. {
  1086. if(formElement is DFLayoutField field)
  1087. {
  1088. var fieldControl = GetFieldControl(field);
  1089. if(fieldControl != null && !fieldControl.Validate(out var message))
  1090. {
  1091. messages.Add(message);
  1092. valid = false;
  1093. }
  1094. }
  1095. }
  1096. return valid;
  1097. }
  1098. #endregion
  1099. }
  1100. }