DynamicFormDesignGrid.cs 46 KB

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