DynamicFormDesignGrid.cs 48 KB

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