DynamicFormDesignGrid.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  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 FrameworkElement)!.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 = 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 DFHeaderControl head).Select(x => x.Value).Cast<DFHeaderControl>())
  822. {
  823. if (header.Header.Collapsed)
  824. {
  825. CollapseRows(header.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, out Dictionary<string, object?>? additionalValues)
  1021. {
  1022. var fieldControl = GetFieldControl(field);
  1023. if(fieldControl != null)
  1024. {
  1025. entityValue = fieldControl.GetEntityValue();
  1026. additionalValues = fieldControl.GetAdditionalValues();
  1027. return fieldControl.GetValue();
  1028. }
  1029. entityValue = null;
  1030. additionalValues = null;
  1031. return null;
  1032. }
  1033. public object? GetFieldValue(string fieldName)
  1034. {
  1035. var field = form.Elements.Where(x => (x as DFLayoutField)?.Name == fieldName).FirstOrDefault() as DFLayoutField;
  1036. if (field is null)
  1037. {
  1038. return null;
  1039. }
  1040. return GetFieldValue(field, out var entityValue, out var additionalValues);
  1041. }
  1042. private object? GetFieldData(DFLayoutField field, string dataField)
  1043. {
  1044. var fieldControl = GetFieldControl(field);
  1045. if (fieldControl is not null)
  1046. {
  1047. return fieldControl.GetData(dataField);
  1048. }
  1049. return null;
  1050. }
  1051. public object? GetFieldData(string fieldName, string dataField)
  1052. {
  1053. var field = form.Elements.Where(x => (x as DFLayoutField)?.Name == fieldName).FirstOrDefault() as DFLayoutField;
  1054. if (field is null)
  1055. {
  1056. return null;
  1057. }
  1058. return GetFieldData(field, dataField);
  1059. }
  1060. /// <summary>
  1061. /// Load values into editor; Must be called after <see cref="Initialize"/>.
  1062. /// </summary>
  1063. /// <remarks>
  1064. /// Resets <see cref="IsChanged"/>.
  1065. /// </remarks>
  1066. /// <param name="values">A dictionary of <see cref="DigitalFormVariable.Code"/> -> value.</param>
  1067. public void LoadValues(Dictionary<string, object> values)
  1068. {
  1069. _changing = true;
  1070. foreach (var (name, value) in values)
  1071. {
  1072. SetFieldValue(name, value);
  1073. }
  1074. Form.EvaluateExpressions();
  1075. _changing = false;
  1076. _isChanged = false;
  1077. }
  1078. /// <summary>
  1079. /// Takes values from editors and saves them to a dictionary; must be called after <see cref="Initialize"/>.
  1080. /// </summary>
  1081. /// <returns>A dictionary of <see cref="DigitalFormVariable.Code"/> -> value.</returns>
  1082. public Dictionary<string, object> SaveValues()
  1083. {
  1084. var result = new Dictionary<string, object>();
  1085. foreach (var formElement in form.Elements)
  1086. if (formElement is DFLayoutField field)
  1087. {
  1088. var value = GetFieldValue(field, out var entityValue, out var additionalValues);
  1089. if (value != null)
  1090. result[field.Name] = value;
  1091. if(additionalValues is not null)
  1092. {
  1093. foreach(var (fieldName, fieldValue) in additionalValues)
  1094. {
  1095. if(fieldValue is not null)
  1096. {
  1097. result[$"{field.Name}.{fieldName}"] = fieldValue;
  1098. }
  1099. }
  1100. }
  1101. if(DataModel != null)
  1102. {
  1103. var property = field.GetPropertyValue<string>("Property");
  1104. if (!string.IsNullOrWhiteSpace(property))
  1105. DataModel.SetEntityValue(property, entityValue);
  1106. }
  1107. }
  1108. return result;
  1109. }
  1110. public bool Validate(out List<string> messages)
  1111. {
  1112. messages = new List<string>();
  1113. var valid = true;
  1114. foreach(var formElement in form.Elements)
  1115. {
  1116. if(formElement is DFLayoutField field)
  1117. {
  1118. var fieldControl = GetFieldControl(field);
  1119. if(fieldControl != null && !fieldControl.Validate(out var message))
  1120. {
  1121. messages.Add(message);
  1122. valid = false;
  1123. }
  1124. }
  1125. }
  1126. return valid;
  1127. }
  1128. #endregion
  1129. }
  1130. }