DynamicFormDesignGrid.cs 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401
  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.Input;
  18. using System.Windows.Markup.Localizer;
  19. using System.Windows.Media;
  20. using System.Windows.Media.Effects;
  21. using System.Windows.Media.Imaging;
  22. using InABox.Clients;
  23. using InABox.Core;
  24. using InABox.WPF;
  25. using Microsoft.CodeAnalysis.CSharp.Syntax;
  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. using PointI = System.Drawing.Point;
  31. using Rectangle = System.Windows.Shapes.Rectangle;
  32. namespace InABox.DynamicGrid;
  33. public class DynamicFormCreateElementArgs : EventArgs
  34. {
  35. public DynamicFormCreateElementArgs(DFLayoutElement element, string name)
  36. {
  37. Element = element;
  38. Name = name;
  39. }
  40. public DFLayoutElement Element { get; }
  41. public string Name { get; }
  42. }
  43. public delegate FrameworkElement DynamicFormCreateElementDelegate(object sender, DynamicFormCreateElementArgs e);
  44. public delegate void DynamicFormAfterDesignDelegate(object sender);
  45. public delegate void DynamicFormAfterRenderDelegate(DynamicFormDesignGrid sender);
  46. public delegate void DynamicFormOnChangedDelegate(DynamicFormDesignGrid sender, string fieldName);
  47. public enum FormMode
  48. {
  49. /// <summary>
  50. /// The form is read-only.
  51. /// </summary>
  52. ReadOnly,
  53. /// <summary>
  54. /// Standard option for when the form is being filled in by the associated employee.
  55. /// </summary>
  56. Filling,
  57. /// <summary>
  58. /// Standard option for when the form is being previewed - that is, it is acting with placeholder values that will not get saved.
  59. /// It is still editable.
  60. /// </summary>
  61. Preview,
  62. /// <summary>
  63. /// 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/>
  64. /// This is only possible if <see cref="CanEditCompletedForms"/> is enabled.
  65. /// </summary>
  66. Editing,
  67. /// <summary>
  68. /// The form layout is being designed
  69. /// </summary>
  70. Designing
  71. }
  72. public class DynamicFormDesignGrid : Grid, IDFRenderer
  73. {
  74. //private bool _designing;
  75. public bool GridInitialized { get; private set; } = false;
  76. //private bool _readonly;
  77. public SolidColorBrush BackgroundBrush { get; set; } = new(Colors.WhiteSmoke);
  78. public SolidColorBrush BorderBrush { get; set; } = new(Colors.Silver);
  79. private readonly Dictionary<Type, IDynamicGrid> elementgrids = new();
  80. private readonly Dictionary<DFLayoutControl, FrameworkElement> elementmap = new();
  81. private readonly Dictionary<DFLayoutControl, Border> borderMap = new();
  82. public SolidColorBrush FieldBrush { get; set; } = new(Colors.LightYellow);
  83. public SolidColorBrush RequiredFieldBrush { get; set; } = new(Colors.Orange);
  84. public DynamicFormDesignGrid()
  85. {
  86. PreviewMouseLeftButtonDown += Grid_PreviewMouseLeftButtonDown;
  87. PreviewMouseMove += Grid_PreviewMouseMove;
  88. PreviewMouseLeftButtonUp += Grid_PreviewMouseLeftButtonUp;
  89. }
  90. #region Backing Properties
  91. private readonly List<DynamicFormElement> _elements = new();
  92. private readonly List<DynamicFormElementAction> _elementActions = new();
  93. private bool _showBorders = true;
  94. private IDigitalFormDataModel? _datamodel;
  95. private DFLayout form = new();
  96. private FormMode _mode;
  97. private IList<DigitalFormVariable> _variables = new List<DigitalFormVariable>();
  98. private bool _isChanged;
  99. private bool _changing = false;
  100. #endregion
  101. #region Public Properties
  102. public bool ShowBorders
  103. {
  104. get => _showBorders || _mode == FormMode.Designing;
  105. set
  106. {
  107. _showBorders = value;
  108. CheckRefresh();
  109. }
  110. }
  111. public IDigitalFormDataModel? DataModel
  112. {
  113. get => _datamodel;
  114. set
  115. {
  116. _datamodel = value;
  117. if(_datamodel != null)
  118. {
  119. var task = Task.Run(() =>
  120. {
  121. var waiting = true;
  122. _datamodel.Load(m => { waiting = false; });
  123. while (waiting) ;
  124. });
  125. task.Wait();
  126. }
  127. CheckRefresh();
  128. }
  129. }
  130. public DFLayout Form
  131. {
  132. get => form;
  133. set
  134. {
  135. form = value;
  136. form.Renderer = this;
  137. CheckRefresh();
  138. }
  139. }
  140. public FormMode Mode
  141. {
  142. get => _mode;
  143. set
  144. {
  145. if (_mode != value)
  146. {
  147. var oldMode = _mode;
  148. if (_mode == FormMode.Designing)
  149. {
  150. OnAfterDesign?.Invoke(this);
  151. }
  152. _mode = value;
  153. CheckRefresh(oldMode != FormMode.Designing);
  154. }
  155. }
  156. }
  157. public bool IsDesigning { get => _mode == FormMode.Designing; }
  158. public bool IsReadOnly { get => _mode == FormMode.ReadOnly; }
  159. public bool IsEditing { get => _mode == FormMode.Editing || _mode == FormMode.Filling; }
  160. public bool IsChanged => _isChanged;
  161. public delegate DigitalFormVariable? CreateVariableHandler(Type fieldType);
  162. public delegate bool EditVariableHandler(DigitalFormVariable variable);
  163. public event CreateVariableHandler? OnCreateVariable;
  164. public event EditVariableHandler? OnEditVariable;
  165. public delegate void CustomiseElementContextMenuHandler(ContextMenu menu, DFLayoutElement element);
  166. public event CustomiseElementContextMenuHandler? CustomiseElementContextMenu;
  167. public IList<DigitalFormVariable> Variables
  168. {
  169. get => _variables;
  170. set
  171. {
  172. _variables = value;
  173. CheckRefresh();
  174. }
  175. }
  176. #endregion
  177. #region Events
  178. public event DynamicFormAfterDesignDelegate? OnAfterDesign;
  179. public event DynamicFormCreateElementDelegate? OnCreateElement;
  180. public event DynamicFormAfterRenderDelegate? OnAfterRender;
  181. public event DynamicFormOnChangedDelegate? OnChanged;
  182. #endregion
  183. #region Rows
  184. class RowData
  185. {
  186. public string RowHeight { get; set; }
  187. public RowData(string rowHeight)
  188. {
  189. RowHeight = rowHeight;
  190. }
  191. }
  192. internal void CollapseRows(FormHeader header, bool collapsed)
  193. {
  194. var startRow = this.GetRow(header) + this.GetRowSpan(header);
  195. var nextRow = elementmap
  196. .Where(x => x.Value is DFHeaderControl headerControl && headerControl.Header != header)
  197. .Select(x => this.GetRow(x.Value))
  198. .Where(x => x >= startRow).DefaultIfEmpty(-1).Min();
  199. if (nextRow == -1)
  200. {
  201. nextRow = RowDefinitions.Count;
  202. }
  203. for (int row = startRow; row < nextRow; ++row)
  204. {
  205. var rowDefinition = RowDefinitions[row];
  206. if(rowDefinition.Tag is not RowData rowData)
  207. {
  208. throw new Exception("Row definition tag is not RowData");
  209. }
  210. if (collapsed)
  211. {
  212. rowDefinition.Height = new GridLength(0);
  213. }
  214. else
  215. {
  216. rowDefinition.Height = StringToGridLength(rowData.RowHeight);
  217. }
  218. }
  219. }
  220. #endregion
  221. #region Elements
  222. class DynamicFormElement
  223. {
  224. public string Caption { get; set; }
  225. public Type ElementType { get; set; }
  226. public string Category { get; set; }
  227. public bool AllowDuplicate { get; set; }
  228. public object? Tag { get; set; }
  229. public Func<object?, DFLayoutElement>? CreateElement { get; set; }
  230. public bool Visible { get; set; }
  231. public DynamicFormElement(string caption, Type elementType, string category, bool allowDuplicate, bool visible, object? tag, Func<object?, DFLayoutElement>? createElement)
  232. {
  233. Caption = caption;
  234. ElementType = elementType;
  235. Category = category;
  236. AllowDuplicate = allowDuplicate;
  237. Tag = tag;
  238. CreateElement = createElement;
  239. Visible = visible;
  240. }
  241. }
  242. class DynamicFormElementAction
  243. {
  244. public string Caption { get; set; }
  245. public Bitmap? Image { get; set; }
  246. public string Category { get; set; }
  247. public object? Tag { get; set; }
  248. public Func<object?, DFLayoutElement?> OnClick { get; set; }
  249. public DynamicFormElementAction(string caption, Bitmap? image, string category, object? tag, Func<object?, DFLayoutElement> onClick)
  250. {
  251. Caption = caption;
  252. Image = image;
  253. Category = category;
  254. Tag = tag;
  255. OnClick = onClick;
  256. }
  257. }
  258. public void ClearElementTypesAndActions()
  259. {
  260. _elements.Clear();
  261. _elementActions.Clear();
  262. }
  263. public void AddElementType<TElement>(string caption, string category, bool allowduplicate = false, bool visible = true)
  264. where TElement : DFLayoutElement
  265. {
  266. AddElementType(typeof(TElement), caption, category, allowduplicate, visible: visible);
  267. }
  268. public void AddElementType<TElement, TTag>(string caption, string category, TTag tag, Func<TTag, TElement> createElement, bool allowduplicate = false, bool visible = true)
  269. where TElement : DFLayoutElement
  270. {
  271. AddElementType(typeof(TElement), caption, category, tag, createElement, allowduplicate, visible: visible);
  272. }
  273. public void AddElementType(Type TElement, string caption, string category, bool allowduplicate = false, bool visible = true)
  274. {
  275. _elements.Add(new DynamicFormElement(caption, TElement, category, allowduplicate, visible, null, null));
  276. }
  277. public void AddElementType<TTag>(Type TElement, string caption, string category, TTag tag, Func<TTag, DFLayoutElement> createElement, bool allowduplicate = false, bool visible = true)
  278. {
  279. _elements.Add(new DynamicFormElement(caption, TElement, category, allowduplicate, visible, tag, x => createElement((TTag)x)));
  280. }
  281. public void AddElementAction<TTag>(string caption, Bitmap? image, string category, TTag tag, Func<TTag, DFLayoutElement?> onClick)
  282. {
  283. _elementActions.Add(new(caption, image, category, tag, x => onClick((TTag)x)));
  284. }
  285. internal FrameworkElement? CreateElement(DFLayoutElement element)
  286. {
  287. var elementType = element.GetType();
  288. if(_elements.FirstOrDefault(x => x.ElementType == elementType) is DynamicFormElement el)
  289. {
  290. return OnCreateElement?.Invoke(this, new DynamicFormCreateElementArgs(element, el.Caption));
  291. }
  292. return null;
  293. }
  294. #endregion
  295. #region Utilities
  296. private static VerticalAlignment GetVerticalAlignment(DFLayoutAlignment alignment)
  297. {
  298. return alignment == DFLayoutAlignment.Start
  299. ? VerticalAlignment.Top
  300. : alignment == DFLayoutAlignment.End
  301. ? VerticalAlignment.Bottom
  302. : alignment == DFLayoutAlignment.Middle
  303. ? VerticalAlignment.Center
  304. : VerticalAlignment.Stretch;
  305. }
  306. private static HorizontalAlignment GetHorizontalAlignment(DFLayoutAlignment alignment)
  307. {
  308. return alignment == DFLayoutAlignment.Start
  309. ? HorizontalAlignment.Left
  310. : alignment == DFLayoutAlignment.End
  311. ? HorizontalAlignment.Right
  312. : alignment == DFLayoutAlignment.Middle
  313. ? HorizontalAlignment.Center
  314. : HorizontalAlignment.Stretch;
  315. }
  316. private static GridLength StringToGridLength(string length)
  317. {
  318. if (string.IsNullOrWhiteSpace(length) || string.Equals(length.ToUpper(), "AUTO"))
  319. return new GridLength(1, GridUnitType.Auto);
  320. if (!double.TryParse(length.Replace("*", ""), out var value))
  321. value = 1.0F;
  322. var type = length.Contains('*') ? GridUnitType.Star : GridUnitType.Pixel;
  323. return new GridLength(value, type);
  324. }
  325. private static string GridLengthToString(GridLength length)
  326. {
  327. if (length.IsStar)
  328. return length.Value == 1.0F ? "*" : string.Format("{0}*", length.Value);
  329. if (length.IsAuto)
  330. return "Auto";
  331. return length.Value.ToString();
  332. }
  333. private static string FormatGridLength(GridLength length, IEnumerable<GridLength> others)
  334. {
  335. if (length.IsStar)
  336. {
  337. double total = 0.0F;
  338. foreach (var other in others.Where(x => x.IsStar))
  339. total += other.Value;
  340. return string.Format("{0:F0}%", total != 0 ? length.Value * 100.0F / total : 0);
  341. }
  342. if (length.IsAuto)
  343. return "Auto";
  344. return string.Format("{0}px", length.Value);
  345. }
  346. private static void AddClick<TTag>(ButtonBase button, TTag tag, Action<TTag> click)
  347. {
  348. button.Tag = tag;
  349. button.Click += (o, e) => click((TTag)(o as FrameworkElement)!.Tag);
  350. }
  351. #endregion
  352. #region Design Mode
  353. #region Selection
  354. private class CellSelection : Border
  355. {
  356. private static readonly System.Windows.Media.Color MainSelectionBorder = Colors.LightBlue;
  357. private int startRow;
  358. private int endRow;
  359. private int startColumn;
  360. private int endColumn;
  361. public int StartRow
  362. {
  363. get => startRow;
  364. set
  365. {
  366. startRow = value;
  367. UpdatePosition();
  368. }
  369. }
  370. public int StartColumn
  371. {
  372. get => startColumn;
  373. set
  374. {
  375. startColumn = value;
  376. UpdatePosition();
  377. }
  378. }
  379. public int EndRow
  380. {
  381. get => endRow;
  382. set
  383. {
  384. endRow = value;
  385. UpdatePosition();
  386. }
  387. }
  388. public int EndColumn
  389. {
  390. get => endColumn;
  391. set
  392. {
  393. endColumn = value;
  394. UpdatePosition();
  395. }
  396. }
  397. public bool Selecting = true;
  398. public enum SelectionTypes
  399. {
  400. Main,
  401. Secondary,
  402. Resizable,
  403. ResizeBackground
  404. }
  405. public SelectionTypes SelectionType;
  406. public enum Direction
  407. {
  408. None,
  409. Left,
  410. Right,
  411. Top,
  412. Bottom,
  413. All
  414. }
  415. public Direction DragDirection;
  416. public bool IsDragging => DragDirection != Direction.None;
  417. public bool IsRowSelection => StartColumn == 0;
  418. public bool IsColumnSelection => StartRow == 0;
  419. public CellSelection(int startRow, int startColumn, int endRow, int endColumn, SelectionTypes selectionType)
  420. {
  421. SelectionType = selectionType;
  422. switch (selectionType)
  423. {
  424. case SelectionTypes.Main:
  425. InitialiseMain();
  426. break;
  427. case SelectionTypes.Secondary:
  428. InitialiseSecondary();
  429. break;
  430. case SelectionTypes.Resizable:
  431. InitializeResizable();
  432. break;
  433. case SelectionTypes.ResizeBackground:
  434. InitializeResizeBackground();
  435. break;
  436. }
  437. this.startRow = startRow;
  438. this.startColumn = startColumn;
  439. this.endRow = endRow;
  440. this.endColumn = endColumn;
  441. UpdatePosition();
  442. }
  443. private void InitialiseMain()
  444. {
  445. var colour = MainSelectionBorder;
  446. BorderBrush = new SolidColorBrush(colour);
  447. Background = new SolidColorBrush(new System.Windows.Media.Color
  448. {
  449. A = (byte)(colour.A / 2),
  450. R = colour.R,
  451. G = colour.G,
  452. B = colour.B
  453. });
  454. SetZIndex(this, 2);
  455. BorderThickness = new Thickness(1);
  456. }
  457. private void InitialiseSecondary()
  458. {
  459. var rectangle = new Rectangle
  460. {
  461. StrokeDashArray = new DoubleCollection { 4, 4 },
  462. Stroke = new SolidColorBrush(Colors.Gray),
  463. StrokeThickness = 1.5
  464. };
  465. rectangle.SetBinding(Rectangle.WidthProperty, new Binding("ActualWidth") { Source = this });
  466. rectangle.SetBinding(Rectangle.HeightProperty, new Binding("ActualHeight") { Source = this });
  467. var brush = new VisualBrush { Visual = rectangle };
  468. BorderBrush = brush;
  469. BorderThickness = new Thickness(1.5);
  470. Margin = new Thickness(3);
  471. }
  472. private void InitializeResizable()
  473. {
  474. var rectangle = new Rectangle
  475. {
  476. StrokeDashArray = new DoubleCollection { 4, 4 },
  477. Stroke = new SolidColorBrush(Colors.Gray),
  478. StrokeThickness = 3
  479. };
  480. rectangle.SetBinding(Rectangle.WidthProperty, new Binding("ActualWidth") { Source = this });
  481. rectangle.SetBinding(Rectangle.HeightProperty, new Binding("ActualHeight") { Source = this });
  482. var brush = new VisualBrush { Visual = rectangle };
  483. BorderBrush = brush;
  484. Background = new SolidColorBrush(Colors.Transparent);
  485. SetZIndex(this, 2);
  486. BorderThickness = new Thickness(10);
  487. MouseMove += Resizable_MouseMove;
  488. }
  489. private void InitializeResizeBackground()
  490. {
  491. var colour = Colors.WhiteSmoke;
  492. Background = new SolidColorBrush(new System.Windows.Media.Color
  493. {
  494. A = (byte)(colour.A / 2),
  495. R = colour.R,
  496. G = colour.G,
  497. B = colour.B
  498. });
  499. SetZIndex(this, 1);
  500. BorderThickness = new Thickness(0);
  501. }
  502. public bool StartDragging(Point position)
  503. {
  504. if (!IsMouseDirectlyOver) return false;
  505. var dX = Math.Min(position.X, ActualWidth - position.X);
  506. var dY = Math.Min(position.Y, ActualHeight - position.Y);
  507. if(Math.Min(dX, dY) < 10)
  508. {
  509. if (dX < dY)
  510. {
  511. DragDirection = position.X < ActualWidth / 2 ? Direction.Left : Direction.Right;
  512. }
  513. else
  514. {
  515. DragDirection = position.Y < ActualHeight / 2 ? Direction.Top : Direction.Bottom;
  516. }
  517. }
  518. else
  519. {
  520. DragDirection = Direction.All;
  521. return false;
  522. }
  523. return true;
  524. }
  525. private void Resizable_MouseMove(object sender, MouseEventArgs e)
  526. {
  527. if (!IsMouseDirectlyOver || IsDragging) return;
  528. var position = e.GetPosition(this);
  529. var dX = Math.Min(position.X, ActualWidth - position.X);
  530. var dY = Math.Min(position.Y, ActualHeight - position.Y);
  531. if (Math.Min(dX, dY) < 10)
  532. {
  533. if (dX < dY)
  534. {
  535. Cursor = Cursors.SizeWE;
  536. }
  537. else
  538. {
  539. Cursor = Cursors.SizeNS;
  540. }
  541. }
  542. else
  543. {
  544. Cursor = Cursors.Arrow;
  545. }
  546. }
  547. public void SetEnd(int endRow, int endColumn)
  548. {
  549. this.endRow = endRow;
  550. this.endColumn = endColumn;
  551. UpdatePosition();
  552. }
  553. public void SetSize(int startRow, int startColumn, int endRow, int endColumn)
  554. {
  555. this.startRow = startRow;
  556. this.startColumn = startColumn;
  557. this.endRow = endRow;
  558. this.endColumn = endColumn;
  559. UpdatePosition();
  560. }
  561. private void UpdatePosition()
  562. {
  563. Grid.SetRow(this, Math.Min(startRow, endRow));
  564. Grid.SetRowSpan(this, Math.Abs(endRow - startRow) + 1);
  565. Grid.SetColumn(this, Math.Min(startColumn, endColumn));
  566. Grid.SetColumnSpan(this, Math.Abs(endColumn - startColumn) + 1);
  567. }
  568. public CellRange ToRange() => new CellRange(StartRow, StartColumn, EndRow, EndColumn);
  569. }
  570. private CellSelection? Selection;
  571. private Dictionary<DFLayoutControl, CellSelection> SelectedItemsSelections = new();
  572. private class Range
  573. {
  574. public int Start { get; set; }
  575. public int End { get; set; }
  576. public int Min => Math.Min(Start, End);
  577. public int Max => Math.Max(Start, End);
  578. public Range(int start, int end)
  579. {
  580. Start = start;
  581. End = end;
  582. }
  583. public override string ToString() => $"{Start} -> {End}";
  584. }
  585. private class CellRange
  586. {
  587. public int StartRow { get; set; }
  588. public int StartColumn { get; set; }
  589. public int EndRow { get; set; }
  590. public int EndColumn { get; set; }
  591. public int MinRow => Math.Min(StartRow, EndRow);
  592. public int MinColumn => Math.Min(StartColumn, EndColumn);
  593. public int MaxRow => Math.Max(StartRow, EndRow);
  594. public int MaxColumn => Math.Max(StartColumn, EndColumn);
  595. public int RowSpan => Math.Abs(EndRow - StartRow) + 1;
  596. public int ColumnSpan => Math.Abs(EndColumn - StartColumn) + 1;
  597. public CellRange(int row, int column)
  598. {
  599. StartRow = row;
  600. EndRow = row;
  601. StartColumn = column;
  602. EndColumn = column;
  603. }
  604. public CellRange(int startRow, int startColumn, int endRow, int endColumn)
  605. {
  606. StartRow = startRow;
  607. EndRow = endRow;
  608. StartColumn = startColumn;
  609. EndColumn = endColumn;
  610. }
  611. public override string ToString() => $"({StartColumn}, {StartRow}) -> ({EndColumn}, {EndRow})";
  612. }
  613. private void ClearSelection()
  614. {
  615. if (Selection is null) return;
  616. Children.Remove(Selection);
  617. Selection = null;
  618. UpdateSecondarySelection();
  619. }
  620. private void StartSelection(int row, int column)
  621. {
  622. if (Selection is not null) ClearSelection();
  623. Selection = new CellSelection(row, column, row, column, CellSelection.SelectionTypes.Main);
  624. Selection.MouseRightButtonDown += Selection_MouseRightButtonDown;
  625. Children.Add(Selection);
  626. UpdateSecondarySelection();
  627. }
  628. private void StartRowSelection(int row)
  629. {
  630. if (Selection is not null) ClearSelection();
  631. Selection = new CellSelection(row, 0, row, ColumnDefinitions.Count - 1, CellSelection.SelectionTypes.Main);
  632. Selection.MouseRightButtonDown += Selection_MouseRightButtonDown;
  633. Children.Add(Selection);
  634. UpdateSecondarySelection();
  635. }
  636. private void StartColumnSelection(int column)
  637. {
  638. if (Selection is not null) ClearSelection();
  639. Selection = new CellSelection(0, column, RowDefinitions.Count - 1, column, CellSelection.SelectionTypes.Main);
  640. Selection.MouseRightButtonDown += Selection_MouseRightButtonDown;
  641. Children.Add(Selection);
  642. UpdateSecondarySelection();
  643. }
  644. private Tuple<int, int> GetRowColIndex(Point point)
  645. {
  646. int rowIdx = -1;
  647. int colIdx = -1;
  648. for(var c = 0; c < ColumnDefinitions.Count; ++c)
  649. {
  650. var column = ColumnDefinitions[c];
  651. if(point.X >= column.Offset && point.X < column.Offset + column.ActualWidth)
  652. {
  653. colIdx = c;
  654. break;
  655. }
  656. }
  657. for(var r = 0; r < RowDefinitions.Count; ++r)
  658. {
  659. var row = RowDefinitions[r];
  660. if(point.Y >= row.Offset && point.Y < row.Offset + row.ActualHeight)
  661. {
  662. rowIdx = r;
  663. break;
  664. }
  665. }
  666. return new Tuple<int, int>(rowIdx, colIdx);
  667. }
  668. private void UpdateSecondarySelection()
  669. {
  670. List<DFLayoutControl> items;
  671. if (Selection is null || Selection.IsRowSelection || Selection.IsColumnSelection)
  672. {
  673. items = new List<DFLayoutControl>();
  674. }
  675. else
  676. {
  677. items = GetSelectedItems().ToList();
  678. }
  679. var removes = new List<DFLayoutControl>();
  680. foreach(var (control, selection) in SelectedItemsSelections)
  681. {
  682. if (!items.Contains(control))
  683. {
  684. removes.Add(control);
  685. Children.Remove(selection);
  686. }
  687. }
  688. foreach(var remove in removes)
  689. {
  690. SelectedItemsSelections.Remove(remove);
  691. }
  692. foreach(var item in items)
  693. {
  694. if (!SelectedItemsSelections.ContainsKey(item))
  695. {
  696. var selection = new CellSelection(
  697. item.Row, item.Column,
  698. item.Row + item.RowSpan - 1, item.Column + item.ColumnSpan - 1,
  699. CellSelection.SelectionTypes.Secondary);
  700. SelectedItemsSelections.Add(item, selection);
  701. Children.Add(selection);
  702. }
  703. }
  704. }
  705. private void ContinueSelection(int row, int column)
  706. {
  707. if (Selection is null) return;
  708. row = Math.Max(row, 1);
  709. column = Math.Max(column, 1);
  710. Selection.Selecting = true;
  711. if (Selection.IsRowSelection)
  712. {
  713. Selection.EndRow = row;
  714. }
  715. else if (Selection.IsColumnSelection)
  716. {
  717. Selection.EndColumn = column;
  718. }
  719. else
  720. {
  721. Selection.SetEnd(row, column);
  722. }
  723. UpdateSecondarySelection();
  724. }
  725. private void Grid_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  726. {
  727. if (!IsDesigning) return;
  728. if(Resizer is not null)
  729. {
  730. if (Resizer.StartDragging(e.GetPosition(Resizer)))
  731. {
  732. Cursor = Resizer.DragDirection switch
  733. {
  734. CellSelection.Direction.All => Cursors.SizeAll,
  735. CellSelection.Direction.Left or CellSelection.Direction.Right => Cursors.SizeWE,
  736. _ => Cursors.SizeNS
  737. };
  738. if(Resizer.DragDirection == CellSelection.Direction.All)
  739. {
  740. StartDragPosition = GetRowColIndex(e.GetPosition(this));
  741. }
  742. }
  743. return;
  744. }
  745. var (row, column) = GetRowColIndex(e.GetPosition(this));
  746. if(Selection is not null && (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))
  747. {
  748. ContinueSelection(row, column);
  749. }
  750. else if(Selection is not null && Selection.Selecting)
  751. {
  752. Selection.Selecting = false;
  753. }
  754. else
  755. {
  756. if (column == 0)
  757. {
  758. if (row == 0) return;
  759. StartRowSelection(row);
  760. }
  761. else if (row == 0)
  762. {
  763. if (column == 0) return;
  764. StartColumnSelection(column);
  765. }
  766. else
  767. {
  768. StartSelection(row, column);
  769. }
  770. }
  771. }
  772. private void Grid_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
  773. {
  774. if (!IsDesigning) return;
  775. var (row, column) = GetRowColIndex(e.GetPosition(this));
  776. if (Resizer is not null)
  777. {
  778. ResizeMouseMove(sender, e);
  779. return;
  780. }
  781. if (Selection is null || !Selection.Selecting) return;
  782. ContinueSelection(row, column);
  783. }
  784. private void Grid_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
  785. {
  786. if(Resizer is not null)
  787. {
  788. Resizer.DragDirection = CellSelection.Direction.None;
  789. Cursor = Cursors.Arrow;
  790. }
  791. else if (Selection is not null)
  792. {
  793. Selection.Selecting = false;
  794. }
  795. }
  796. private IEnumerable<Tuple<DFLayoutControl, FrameworkElement>> GetSelectedMaps(CellRange? range = null)
  797. {
  798. range ??= Selection?.ToRange();
  799. if (range is null) yield break;
  800. var minRow = Math.Min(range.StartRow, range.EndRow);
  801. var maxRow = Math.Max(range.StartRow, range.EndRow);
  802. var minCol = Math.Min(range.StartColumn, range.EndColumn);
  803. var maxCol = Math.Max(range.StartColumn, range.EndColumn);
  804. foreach(var (control, element) in elementmap)
  805. {
  806. if(control.Row <= maxRow && control.Row + control.RowSpan - 1 >= minRow
  807. && control.Column <= maxCol && control.Column + control.ColumnSpan - 1 >= minCol)
  808. {
  809. yield return new(control, element);
  810. }
  811. }
  812. }
  813. private IEnumerable<DFLayoutControl> GetSelectedItems(CellRange? range = null) => GetSelectedMaps(range).Select(x => x.Item1);
  814. private void PopulateSelectionMenu(ContextMenu menu)
  815. {
  816. if (Selection is null) return;
  817. if (Selection.IsRowSelection)
  818. {
  819. var nRows = Math.Abs(Selection.EndRow - Selection.StartRow) + 1;
  820. if (nRows == 1)
  821. {
  822. PopulateRowMenu(menu, Selection.StartRow - 1);
  823. }
  824. else
  825. {
  826. menu.AddItem(nRows == 1 ? "Delete Row" : "Delete Rows", null, new Range(Selection.StartRow - 1, Selection.EndRow - 1), DeleteRows);
  827. }
  828. }
  829. else if (Selection.IsColumnSelection)
  830. {
  831. var nColumns = Math.Abs(Selection.EndColumn - Selection.StartColumn) + 1;
  832. if (nColumns == 1)
  833. {
  834. PopulateColumnMenu(menu, Selection.StartColumn - 1);
  835. }
  836. else
  837. {
  838. menu.AddItem(nColumns == 1 ? "Delete Column" : "Delete Columns", null, new Range(Selection.StartColumn - 1, Selection.EndColumn - 1), DeleteColumns);
  839. }
  840. }
  841. else
  842. {
  843. var selectedItems = GetSelectedItems().ToList();
  844. if (selectedItems.Count == 0)
  845. {
  846. PopulateEmptyCellMenu(menu, Selection.ToRange());
  847. }
  848. if (selectedItems.Count == 1)
  849. {
  850. var item = selectedItems.First();
  851. PopulateElementContextMenu(menu, item);
  852. }
  853. else if (selectedItems.Count > 1)
  854. {
  855. menu.AddItem("Delete Items", null, selectedItems, DeleteElements);
  856. }
  857. }
  858. }
  859. private void Selection_MouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  860. {
  861. if (!IsDesigning || Selection is null) return;
  862. var menu = new ContextMenu();
  863. PopulateSelectionMenu(menu);
  864. if(menu.Items.Count == 0)
  865. {
  866. menu.AddItem("No actions available", null, null, false);
  867. }
  868. menu.IsOpen = true;
  869. }
  870. #endregion
  871. #region Resizing
  872. private CellSelection? Resizer;
  873. private Tuple<int, int> StartDragPosition;
  874. private CellSelection? TopResizeBackground;
  875. private CellSelection? LeftResizeBackground;
  876. private CellSelection? RightResizeBackground;
  877. private CellSelection? BottomResizeBackground;
  878. private DFLayoutControl? ResizingControl;
  879. private CellSelection GetResizeBackground(ref CellSelection? background)
  880. {
  881. if(background is null)
  882. {
  883. background = new CellSelection(0, 0, 0, 0, CellSelection.SelectionTypes.ResizeBackground);
  884. background.PreviewMouseDown += ResizerBackground_PreviewMouseDown;
  885. Children.Add(background);
  886. }
  887. return background;
  888. }
  889. private void ClearResizeBackground(ref CellSelection? background)
  890. {
  891. if(background is not null)
  892. {
  893. Children.Remove(background);
  894. background = null;
  895. }
  896. }
  897. private void ResizerBackground_PreviewMouseDown(object sender, MouseButtonEventArgs e)
  898. {
  899. FinishResize();
  900. }
  901. private void SetResizerBackgroundSize(CellSelection background, int startRow, int startColumn, int endRow, int endColumn)
  902. {
  903. background.SetSize(startRow, startColumn, endRow, endColumn);
  904. background.Visibility = endColumn >= startColumn && endRow >= startRow ? Visibility.Visible : Visibility.Collapsed;
  905. }
  906. private void UpdateResizer(CellRange newSize)
  907. {
  908. if (Resizer is null) return;
  909. Resizer.StartRow = newSize.StartRow;
  910. Resizer.StartColumn = newSize.StartColumn;
  911. Resizer.EndRow = newSize.EndRow;
  912. Resizer.EndColumn = newSize.EndColumn;
  913. SetResizerBackgroundSize(GetResizeBackground(ref LeftResizeBackground), 0, 0, RowDefinitions.Count - 1, newSize.MinColumn - 1);
  914. SetResizerBackgroundSize(GetResizeBackground(ref RightResizeBackground), 0, newSize.MaxColumn + 1, RowDefinitions.Count - 1, ColumnDefinitions.Count - 1);
  915. SetResizerBackgroundSize(GetResizeBackground(ref TopResizeBackground), 0, newSize.MinColumn, newSize.MinRow - 1, newSize.MaxColumn);
  916. SetResizerBackgroundSize(GetResizeBackground(ref BottomResizeBackground), newSize.MaxRow + 1, newSize.MinColumn, RowDefinitions.Count - 1, newSize.MaxColumn);
  917. }
  918. private void ResizeMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
  919. {
  920. if (Resizer is null) return;
  921. if (!Resizer.IsDragging) return;
  922. var (row, column) = GetRowColIndex(e.GetPosition(this));
  923. var newSize = Resizer.ToRange();
  924. switch (Resizer.DragDirection)
  925. {
  926. case CellSelection.Direction.Right:
  927. var startColumn = newSize.MinColumn;
  928. for (int c = column; c >= startColumn; --c)
  929. {
  930. newSize.StartColumn = startColumn;
  931. newSize.EndColumn = Math.Max(c, startColumn);
  932. if (ResizeAllowed(newSize))
  933. {
  934. break;
  935. }
  936. }
  937. break;
  938. case CellSelection.Direction.Left:
  939. var endColumn = newSize.MaxColumn;
  940. for (int c = column; c <= endColumn; ++c)
  941. {
  942. newSize.StartColumn = Math.Min(c, endColumn);
  943. newSize.EndColumn = endColumn;
  944. if (ResizeAllowed(newSize))
  945. {
  946. break;
  947. }
  948. }
  949. break;
  950. case CellSelection.Direction.Bottom:
  951. var startRow = newSize.MinRow;
  952. for (int r = row; r >= startRow; --r)
  953. {
  954. newSize.StartRow = startRow;
  955. newSize.EndRow = Math.Max(r, startRow);
  956. if (ResizeAllowed(newSize))
  957. {
  958. break;
  959. }
  960. }
  961. break;
  962. case CellSelection.Direction.Top:
  963. var endRow = newSize.MaxRow;
  964. for (int r = row; r <= endRow; ++r)
  965. {
  966. newSize.StartRow = Math.Min(r, endRow);
  967. newSize.EndRow = endRow;
  968. if (ResizeAllowed(newSize))
  969. {
  970. break;
  971. }
  972. }
  973. break;
  974. case CellSelection.Direction.None:
  975. return;
  976. }
  977. UpdateResizer(newSize);
  978. }
  979. private bool ResizeAllowed(CellRange range)
  980. {
  981. var items = GetSelectedItems(range).ToList();
  982. if (items.Count > 1) return false;
  983. return items.Count == 0 ||
  984. (items.Count == 1 && items.First() == ResizingControl);
  985. }
  986. private void ClearResize()
  987. {
  988. if (Resizer is null) return;
  989. Children.Remove(Resizer);
  990. Resizer = null;
  991. ResizingControl = null;
  992. ClearResizeBackground(ref LeftResizeBackground);
  993. ClearResizeBackground(ref RightResizeBackground);
  994. ClearResizeBackground(ref TopResizeBackground);
  995. ClearResizeBackground(ref BottomResizeBackground);
  996. }
  997. private void FinishResize()
  998. {
  999. if (Resizer is null) return;
  1000. var range = Resizer.ToRange();
  1001. if(ResizingControl is not null)
  1002. {
  1003. ResizingControl.Row = range.MinRow;
  1004. ResizingControl.Column = range.MinColumn;
  1005. ResizingControl.RowSpan = range.RowSpan;
  1006. ResizingControl.ColumnSpan = range.ColumnSpan;
  1007. }
  1008. ClearResize();
  1009. Render();
  1010. }
  1011. private void ResizeItem(DFLayoutControl control)
  1012. {
  1013. ClearSelection();
  1014. ClearResize();
  1015. Resizer = new CellSelection(
  1016. control.Row, control.Column,
  1017. control.Row + control.RowSpan - 1, control.Column + control.ColumnSpan - 1,
  1018. CellSelection.SelectionTypes.Resizable);
  1019. ResizingControl = control;
  1020. Children.Add(Resizer);
  1021. UpdateResizer(Resizer.ToRange());
  1022. }
  1023. public void HandleKeyDown(KeyEventArgs e)
  1024. {
  1025. if (Resizer is null) return;
  1026. if(e.Key == Key.Enter)
  1027. {
  1028. FinishResize();
  1029. }
  1030. else if(e.Key == Key.Escape)
  1031. {
  1032. ClearResize();
  1033. }
  1034. }
  1035. #endregion
  1036. #region Rows
  1037. private void ShiftDown(int row)
  1038. {
  1039. foreach (var element in form.Elements)
  1040. if (element.Row > row)
  1041. element.Row++;
  1042. else if (element.Row + element.RowSpan - 1 > row)
  1043. element.RowSpan++;
  1044. }
  1045. private void AddRowBeforeClick(int row)
  1046. {
  1047. var length = new GridLength(1.0F, GridUnitType.Auto);
  1048. var result = GridLengthToString(length);
  1049. if (form.RowHeights.Count == 0)
  1050. form.RowHeights.Add(result);
  1051. else
  1052. form.RowHeights.Insert(row, result);
  1053. ShiftDown(row);
  1054. Render();
  1055. }
  1056. private void AddRowAfterClick(int row)
  1057. {
  1058. var length = new GridLength(1.0F, GridUnitType.Auto);
  1059. var result = GridLengthToString(length);
  1060. if (row == form.RowHeights.Count - 1)
  1061. form.RowHeights.Add(result);
  1062. else
  1063. form.RowHeights.Insert(row + 1, result);
  1064. ShiftDown(row + 1);
  1065. Render();
  1066. }
  1067. private void SplitRow(int row)
  1068. {
  1069. foreach (var element in form.Elements)
  1070. if (element.Row > row)
  1071. element.Row++;
  1072. else if (element.Row == row)
  1073. element.RowSpan++;
  1074. else if (element.Row + element.RowSpan - 1 >= row)
  1075. element.RowSpan++;
  1076. }
  1077. private void SplitRowClick(int row)
  1078. {
  1079. var height = StringToGridLength(form.RowHeights[row]);
  1080. var newHeight = height.GridUnitType == GridUnitType.Auto
  1081. ? height
  1082. : new GridLength(height.Value / 2, height.GridUnitType);
  1083. var result = GridLengthToString(newHeight);
  1084. form.RowHeights[row] = result;
  1085. if (row == form.RowHeights.Count - 1)
  1086. form.RowHeights.Add(result);
  1087. else
  1088. form.RowHeights.Insert(row + 1, result);
  1089. SplitRow(row + 1);
  1090. Render();
  1091. }
  1092. private void RowPropertiesClick(int row)
  1093. {
  1094. var length = StringToGridLength(form.RowHeights[row]);
  1095. var editor = new DynamicFormDesignLength(length);
  1096. if (editor.ShowDialog() == true)
  1097. {
  1098. form.RowHeights[row] = GridLengthToString(editor.GridLength);
  1099. Render();
  1100. }
  1101. else
  1102. {
  1103. ClearSelection();
  1104. }
  1105. }
  1106. private void ShiftUp(int row)
  1107. {
  1108. var deletes = new List<DFLayoutControl>();
  1109. foreach (var element in form.Elements)
  1110. if (element.Row > row)
  1111. element.Row--;
  1112. else if (element.Row == row && element.RowSpan <= 1)
  1113. deletes.Add(element);
  1114. else if (element.Row + element.RowSpan - 1 >= row)
  1115. element.RowSpan--;
  1116. foreach (var delete in deletes)
  1117. form.Elements.Remove(delete);
  1118. }
  1119. private void DeleteRows(Range rows)
  1120. {
  1121. for(var row = rows.Max; row >= rows.Min; --row)
  1122. {
  1123. form.RowHeights.RemoveAt(row);
  1124. ShiftUp(row + 1);
  1125. }
  1126. if(form.RowHeights.Count == 0)
  1127. {
  1128. form.RowHeights.Add("Auto");
  1129. }
  1130. Render();
  1131. }
  1132. private void PopulateRowMenu(ContextMenu menu, int row)
  1133. {
  1134. menu.AddItem("Add Row Before", null, row, AddRowBeforeClick);
  1135. menu.AddItem("Add Row After", null, row, AddRowAfterClick);
  1136. menu.AddSeparator();
  1137. menu.AddItem("Split Row", null, row, SplitRowClick);
  1138. var propertiesSeparator = menu.AddSeparator();
  1139. var propertiesMenu = menu.AddItem("Row Properties", null, row, RowPropertiesClick);
  1140. menu.AddSeparator();
  1141. menu.AddItem("Delete Row", null, new Range(row, row), DeleteRows);
  1142. menu.Opened += (o, e) =>
  1143. {
  1144. propertiesSeparator.Visibility = form.RowHeights.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
  1145. propertiesMenu.Visibility = form.RowHeights.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
  1146. };
  1147. }
  1148. private ContextMenu CreateRowMenu(Button button, int row)
  1149. {
  1150. var result = new ContextMenu();
  1151. PopulateRowMenu(result, row);
  1152. button.SetValue(ContextMenuProperty, result);
  1153. return result;
  1154. }
  1155. #endregion
  1156. #region Columns
  1157. private void ShiftRight(int column)
  1158. {
  1159. foreach (var element in form.Elements)
  1160. if (element.Column > column)
  1161. element.Column++;
  1162. else if (element.Column + element.ColumnSpan - 1 > column)
  1163. element.ColumnSpan++;
  1164. }
  1165. private void AddColumnBeforeClick(int column)
  1166. {
  1167. var length = new GridLength(1.0F, form.ColumnWidths.Count == 0 ? GridUnitType.Star : GridUnitType.Auto);
  1168. var result = GridLengthToString(length);
  1169. if (form.ColumnWidths.Count == 0)
  1170. form.ColumnWidths.Add(result);
  1171. else
  1172. form.ColumnWidths.Insert(column, result);
  1173. ShiftRight(column);
  1174. Render();
  1175. }
  1176. private void AddColumnAfterClick(int column)
  1177. {
  1178. var length = new GridLength(1.0F, form.ColumnWidths.Count == 0 ? GridUnitType.Star : GridUnitType.Auto);
  1179. var result = GridLengthToString(length);
  1180. if (column == form.ColumnWidths.Count - 1)
  1181. form.ColumnWidths.Add(result);
  1182. else
  1183. form.ColumnWidths.Insert(column + 1, result);
  1184. ShiftRight(column + 1);
  1185. Render();
  1186. }
  1187. private void SplitColumn(int column)
  1188. {
  1189. foreach (var element in form.Elements)
  1190. if (element.Column > column)
  1191. element.Column++;
  1192. else if (element.Column == column)
  1193. element.ColumnSpan++;
  1194. else if (element.Column + element.ColumnSpan - 1 >= column)
  1195. element.ColumnSpan++;
  1196. }
  1197. private void SplitColumnClick(int column)
  1198. {
  1199. var length = StringToGridLength(form.ColumnWidths[column]);
  1200. var newLength = length.GridUnitType == GridUnitType.Auto
  1201. ? length
  1202. : new GridLength(length.Value / 2, length.GridUnitType);
  1203. var result = GridLengthToString(newLength);
  1204. form.ColumnWidths[column] = result;
  1205. if (column == form.ColumnWidths.Count - 1)
  1206. form.ColumnWidths.Add(result);
  1207. else
  1208. form.ColumnWidths.Insert(column + 1, result);
  1209. SplitColumn(column + 1);
  1210. Render();
  1211. }
  1212. private void ColumnPropertiesClick(int column)
  1213. {
  1214. var length = StringToGridLength(form.ColumnWidths[column]);
  1215. var editor = new DynamicFormDesignLength(length);
  1216. if (editor.ShowDialog() == true)
  1217. {
  1218. form.ColumnWidths[column] = GridLengthToString(editor.GridLength);
  1219. Render();
  1220. }
  1221. else
  1222. {
  1223. ClearSelection();
  1224. }
  1225. }
  1226. private void ShiftLeft(int column)
  1227. {
  1228. var deletes = new List<DFLayoutControl>();
  1229. foreach (var element in form.Elements)
  1230. if (element.Column > column)
  1231. element.Column--;
  1232. else if (element.Column == column && element.ColumnSpan <= 1)
  1233. deletes.Add(element);
  1234. else if (element.Column + element.ColumnSpan - 1 >= column)
  1235. element.ColumnSpan--;
  1236. foreach (var delete in deletes)
  1237. form.Elements.Remove(delete);
  1238. }
  1239. private void DeleteColumns(Range columns)
  1240. {
  1241. for(var column = columns.Max; column >= columns.Min; --column)
  1242. {
  1243. form.ColumnWidths.RemoveAt(column);
  1244. ShiftLeft(column + 1);
  1245. }
  1246. if(form.ColumnWidths.Count == 0)
  1247. {
  1248. form.ColumnWidths.Add("*");
  1249. }
  1250. Render();
  1251. }
  1252. private void PopulateColumnMenu(ContextMenu menu, int column)
  1253. {
  1254. menu.AddItem("Add Column Before", null, column, AddColumnBeforeClick);
  1255. menu.AddItem("Add Column After", null, column, AddColumnAfterClick);
  1256. menu.AddSeparator();
  1257. menu.AddItem("Split Column", null, column, SplitColumnClick);
  1258. var propertiesSeparator = menu.AddSeparator();
  1259. var propertiesMenu = menu.AddItem("Column Properties", null, column, ColumnPropertiesClick);
  1260. menu.AddSeparator();
  1261. menu.AddItem("Delete Column", null, new Range(column, column), DeleteColumns);
  1262. menu.Opened += (o, e) =>
  1263. {
  1264. propertiesSeparator.Visibility = form.ColumnWidths.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
  1265. propertiesMenu.Visibility = form.ColumnWidths.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
  1266. };
  1267. }
  1268. private ContextMenu CreateColumnMenu(Button button, int column)
  1269. {
  1270. var result = new ContextMenu();
  1271. PopulateColumnMenu(result, column);
  1272. button.SetValue(ContextMenuProperty, result);
  1273. return result;
  1274. }
  1275. #endregion
  1276. #region Add Element
  1277. private void AddNewElement<TElement>(DynamicFormElement elementDef, CellRange range)
  1278. where TElement : DFLayoutElement, new()
  1279. {
  1280. TElement? element;
  1281. if (elementDef.CreateElement is not null)
  1282. {
  1283. element = elementDef.CreateElement(elementDef.Tag) as TElement;
  1284. }
  1285. else
  1286. {
  1287. element = new();
  1288. }
  1289. if(element is null)
  1290. {
  1291. return;
  1292. }
  1293. SetControlRange(element, range);
  1294. var result = new FormControlGrid<TElement>().EditItems(new[] { element });
  1295. if (result)
  1296. {
  1297. form.Elements.Add(element);
  1298. Render();
  1299. }
  1300. }
  1301. private void AddElementClick(Tuple<DynamicFormElement, CellRange> tuple)
  1302. {
  1303. var method = typeof(DynamicFormDesignGrid)
  1304. .GetMethod(nameof(AddNewElement), BindingFlags.NonPublic | BindingFlags.Instance)!
  1305. .MakeGenericMethod(tuple.Item1.ElementType);
  1306. method.Invoke(this, new object[] { tuple.Item1, tuple.Item2 });
  1307. }
  1308. private void ElementActionClick(Tuple<DynamicFormElementAction, CellRange> tuple)
  1309. {
  1310. var element = tuple.Item1.OnClick(tuple.Item1.Tag);
  1311. if(element is not null)
  1312. {
  1313. SetControlRange(element, tuple.Item2);
  1314. form.Elements.Add(element);
  1315. Render();
  1316. }
  1317. }
  1318. private void SetControlRange(DFLayoutControl control, CellRange range)
  1319. {
  1320. var minRow = Math.Min(range.StartRow, range.EndRow);
  1321. var maxRow = Math.Max(range.StartRow, range.EndRow);
  1322. var minColumn = Math.Min(range.StartColumn, range.EndColumn);
  1323. var maxColumn = Math.Max(range.StartColumn, range.EndColumn);
  1324. control.Row = minRow;
  1325. control.RowSpan = (maxRow - minRow) + 1;
  1326. control.Column = minColumn;
  1327. control.ColumnSpan = (maxColumn - minColumn) + 1;
  1328. }
  1329. private void CreateLabelClick(CellRange range)
  1330. {
  1331. var label = new DFLayoutLabel();
  1332. SetControlRange(label, range);
  1333. var result = new FormControlGrid<DFLayoutLabel>().EditItems(new[] { label });
  1334. if (result)
  1335. {
  1336. form.Elements.Add(label);
  1337. Render();
  1338. }
  1339. }
  1340. private void CreateHeaderClick(CellRange range)
  1341. {
  1342. var header = new DFLayoutHeader();
  1343. SetControlRange(header, range);
  1344. var result = new FormControlGrid<DFLayoutHeader>().EditItems(new[] { header });
  1345. if (result)
  1346. {
  1347. form.Elements.Add(header);
  1348. Render();
  1349. }
  1350. }
  1351. private void CreateImageClick(CellRange range)
  1352. {
  1353. var image = new DFLayoutImage();
  1354. SetControlRange(image, range);
  1355. var result = new FormControlGrid<DFLayoutImage>().EditItems(new[] { image });
  1356. if (result)
  1357. {
  1358. form.Elements.Add(image);
  1359. Render();
  1360. }
  1361. }
  1362. private void AddVariable(Tuple<DigitalFormVariable, CellRange> tuple)
  1363. {
  1364. if(Activator.CreateInstance(tuple.Item1.FieldType()) is not DFLayoutField field)
  1365. {
  1366. MessageBox.Show(string.Format("{0}: Unknown Type {1}", tuple.Item1.Code, tuple.Item1.VariableType.ToString()));
  1367. return;
  1368. }
  1369. field.Name = tuple.Item1.Code;
  1370. SetControlRange(field, tuple.Item2);
  1371. form.Elements.Add(field);
  1372. form.LoadVariable(tuple.Item1, field);
  1373. Render();
  1374. }
  1375. private void PopulateEmptyCellMenu(ContextMenu menu, CellRange cellRange)
  1376. {
  1377. menu.Items.Clear();
  1378. menu.AddItem("Add Label", null, cellRange, CreateLabelClick);
  1379. menu.AddItem("Add Header", null, cellRange, CreateHeaderClick);
  1380. menu.AddItem("Add Image", null, cellRange, CreateImageClick);
  1381. var fields = menu.AddItem("Add Field", null, null);
  1382. if (OnCreateVariable is not null)
  1383. {
  1384. var variables = fields.AddItem("Create new variable", null, null);
  1385. foreach (var fieldType in DFUtils.GetFieldTypes())
  1386. {
  1387. var caption = fieldType.GetCaption();
  1388. if (string.IsNullOrWhiteSpace(caption))
  1389. {
  1390. caption = CoreUtils.Neatify(fieldType.Name);
  1391. }
  1392. variables.AddItem(caption, null, new Tuple<Type, CellRange>(fieldType, cellRange), (tuple) =>
  1393. {
  1394. var variable = OnCreateVariable?.Invoke(tuple.Item1);
  1395. if (variable is not null)
  1396. {
  1397. _variables.Add(variable);
  1398. AddVariable(new(variable, tuple.Item2));
  1399. }
  1400. });
  1401. }
  1402. }
  1403. var filtered = _variables.Where(x => !x.Hidden && !form.Elements.Any(v => string.Equals((v as DFLayoutField)?.Name, x.Code)));
  1404. fields.AddSeparatorIfNeeded();
  1405. foreach (var variable in filtered)
  1406. fields.AddItem(variable.Code, null, new Tuple<DigitalFormVariable, CellRange>(variable, cellRange), AddVariable);
  1407. fields.RemoveUnnecessarySeparators();
  1408. if(fields.Items.Count == 0)
  1409. {
  1410. menu.Items.Remove(fields);
  1411. }
  1412. var elements = menu.AddItem("Add Object", null, cellRange, null);
  1413. var available = _elements.Where(x => x.Visible && (x.AllowDuplicate || !form.Elements.Any(v => (v as DFLayoutElement)?.GetType() == x.ElementType)))
  1414. .ToArray();
  1415. var cats = available.Select(x => x.Category).Concat(_elementActions.Select(x => x.Category)).Distinct().OrderBy(x => x);
  1416. foreach (var cat in cats)
  1417. {
  1418. var parentMenu = elements;
  1419. if (!string.IsNullOrWhiteSpace(cat))
  1420. {
  1421. parentMenu = elements.AddItem(cat, null, null);
  1422. }
  1423. foreach(var action in _elementActions.Where(x => x.Category == cat))
  1424. {
  1425. parentMenu.AddItem(action.Caption, action.Image, new Tuple<DynamicFormElementAction, CellRange>(action, cellRange), ElementActionClick);
  1426. }
  1427. parentMenu.AddSeparatorIfNeeded();
  1428. foreach (var element in available.Where(x => string.Equals(x.Category, cat)))
  1429. parentMenu.AddItem(element.Caption, null, new Tuple<DynamicFormElement, CellRange>(element, cellRange), AddElementClick);
  1430. parentMenu.RemoveUnnecessarySeparators();
  1431. }
  1432. if (elements.Items.Count == 0)
  1433. menu.Items.Remove(elements);
  1434. }
  1435. private ContextMenu CreateEmptyCellMenu(Border border, int row, int column)
  1436. {
  1437. var result = new ContextMenu();
  1438. result.Opened += (o, e) =>
  1439. {
  1440. PopulateEmptyCellMenu(result, new CellRange(row, column));
  1441. };
  1442. border.SetValue(ContextMenuProperty, result);
  1443. return result;
  1444. }
  1445. #endregion
  1446. #region Element Context Menu
  1447. private void DeleteElements(IEnumerable<DFLayoutControl> controls)
  1448. {
  1449. foreach(var control in controls)
  1450. {
  1451. if (form.Elements.Contains(control))
  1452. {
  1453. form.Elements.Remove(control);
  1454. }
  1455. }
  1456. Render();
  1457. }
  1458. private void DeleteElementClick(DFLayoutControl control)
  1459. {
  1460. if (form.Elements.Contains(control))
  1461. {
  1462. form.Elements.Remove(control);
  1463. Render();
  1464. }
  1465. }
  1466. private void ElementPropertiesClick(DFLayoutControl control)
  1467. {
  1468. if(!elementgrids.TryGetValue(control.GetType(), out var grid))
  1469. {
  1470. var type = typeof(FormControlGrid<>).MakeGenericType(control.GetType());
  1471. grid = (Activator.CreateInstance(type) as IDynamicGrid)!;
  1472. elementgrids[control.GetType()] = grid;
  1473. }
  1474. control.CommitChanges();
  1475. if (grid.EditItems(new[] { control }))
  1476. {
  1477. Render();
  1478. }
  1479. }
  1480. private void EditVariableClick(DFLayoutField field)
  1481. {
  1482. var variable = _variables.FirstOrDefault(x => x.Code == field.Name);
  1483. if (variable is null) return;
  1484. if(OnEditVariable?.Invoke(variable) == true)
  1485. {
  1486. field.LoadFromString(variable.Parameters);
  1487. }
  1488. }
  1489. private void ConvertToHeaderClick(DFLayoutLabel label)
  1490. {
  1491. var header = new DFLayoutHeader
  1492. {
  1493. Row = label.Row,
  1494. RowSpan = label.RowSpan,
  1495. Column = label.Column,
  1496. ColumnSpan = label.ColumnSpan,
  1497. Collapsed = false,
  1498. Header = label.Caption
  1499. };
  1500. header.Style.Synchronise(label.Style);
  1501. header.Style.IsBold = true;
  1502. form.Elements.Remove(label);
  1503. form.Elements.Add(header);
  1504. Render();
  1505. }
  1506. private void ConvertToLabelClick(DFLayoutHeader header)
  1507. {
  1508. var label = new DFLayoutLabel
  1509. {
  1510. Row = header.Row,
  1511. RowSpan = header.RowSpan,
  1512. Column = header.Column,
  1513. ColumnSpan = header.ColumnSpan,
  1514. Caption = header.Header
  1515. };
  1516. label.Style.Synchronise(header);
  1517. label.Style.IsBold = false;
  1518. form.Elements.Remove(header);
  1519. form.Elements.Add(label);
  1520. Render();
  1521. }
  1522. private void PopulateElementContextMenu(ContextMenu menu, DFLayoutControl control)
  1523. {
  1524. var selectedItems = GetSelectedItems().ToList();
  1525. if (selectedItems.Count > 1 && selectedItems.Contains(control))
  1526. {
  1527. PopulateSelectionMenu(menu);
  1528. if(menu.Items.Count > 0) return;
  1529. }
  1530. menu.AddItem("Edit Properties", null, control, ElementPropertiesClick);
  1531. if (OnEditVariable is not null && control is DFLayoutField field)
  1532. {
  1533. menu.AddItem("Edit Variable", null, field, EditVariableClick);
  1534. }
  1535. else if (control is DFLayoutLabel label)
  1536. {
  1537. menu.AddItem("Convert to Header", null, label, ConvertToHeaderClick);
  1538. }
  1539. else if (control is DFLayoutHeader header)
  1540. {
  1541. menu.AddItem("Convert to Label", null, header, ConvertToLabelClick);
  1542. }
  1543. else if(control is DFLayoutElement element)
  1544. {
  1545. CustomiseElementContextMenu?.Invoke(menu, element);
  1546. }
  1547. menu.AddSeparatorIfNeeded();
  1548. menu.AddItem("Resize Item", null, control, ResizeItem);
  1549. menu.AddItem("Delete Item", null, control, DeleteElementClick);
  1550. }
  1551. private ContextMenu CreateElementContextMenu(FrameworkElement element, DFLayoutControl control)
  1552. {
  1553. var result = new ContextMenu();
  1554. result.Opened += (s, e) =>
  1555. {
  1556. result.Items.Clear();
  1557. PopulateElementContextMenu(result, control);
  1558. };
  1559. element.SetValue(ContextMenuProperty, result);
  1560. return result;
  1561. }
  1562. #endregion
  1563. #endregion
  1564. #region Render
  1565. private static void SetDimensions(FrameworkElement element, int row, int column, int rowspan, int colspan, int offset)
  1566. {
  1567. if (column <= 0) return;
  1568. if (row <= 0) return;
  1569. element.MinHeight = 50.0F;
  1570. element.MinWidth = 50.0F;
  1571. element.SetGridPosition(row - offset, column - offset, rowspan, colspan);
  1572. }
  1573. private Border CreateBorder(int row, int column, int rowspan, int colspan, int offset, bool horzstar, bool vertstar)
  1574. {
  1575. var border = new Border();
  1576. if (ShowBorders)
  1577. {
  1578. border.BorderThickness = new Thickness(
  1579. 0.0F,//!IsDesigning && column == 1 - offset ? 0.00F /*0.75F*/ : 0.0F,
  1580. 0.0F,//!IsDesigning && row == 1 - offset ? 0.00F /*0.75F*/ : 0.0F,
  1581. column - offset == ColumnDefinitions.Count - 1 ? horzstar ? 0.00F : 0.75F : 0.75F,
  1582. row - offset == RowDefinitions.Count - 1 ? vertstar ? 0.00F : 0.75F : 0.75F
  1583. );
  1584. border.BorderBrush = BorderBrush;
  1585. }
  1586. border.Background = BackgroundBrush;
  1587. SetDimensions(border, row, column, rowspan, colspan, offset);
  1588. return border;
  1589. }
  1590. private static BitmapImage HeaderClosed =Wpf.Resources.rightarrow.AsBitmapImage(32, 32);
  1591. private static BitmapImage HeaderOpen =Wpf.Resources.downarrow.AsBitmapImage(32, 32);
  1592. private FrameworkElement CreateHeader(DFLayoutHeader header)
  1593. {
  1594. var formHeader = new FormHeader
  1595. {
  1596. Collapsed = header.Collapsed,
  1597. HeaderText = header.Header
  1598. };
  1599. formHeader.CollapsedChanged += (o, c) =>
  1600. {
  1601. CollapseRows(formHeader, c);
  1602. };
  1603. if (IsDesigning)
  1604. {
  1605. formHeader.IsEnabled = false;
  1606. }
  1607. return formHeader;
  1608. }
  1609. // DFLayoutField -> IDynamicFormFieldControl
  1610. private static Dictionary<Type, Type>? _fieldControls;
  1611. private DynamicFormControl? CreateFieldControl(DFLayoutField field)
  1612. {
  1613. if (_fieldControls == null)
  1614. {
  1615. _fieldControls = new();
  1616. foreach (var controlType in CoreUtils.Entities.Where(x => x.IsClass && !x.IsGenericType && x.HasInterface<IDynamicFormFieldControl>()))
  1617. {
  1618. var superDefinition = controlType.GetSuperclassDefinition(typeof(DynamicFormFieldControl<,,,>));
  1619. if (superDefinition != null)
  1620. {
  1621. _fieldControls[superDefinition.GenericTypeArguments[0]] = controlType;
  1622. }
  1623. }
  1624. }
  1625. var fieldControlType = _fieldControls.GetValueOrDefault(field.GetType());
  1626. if (fieldControlType is not null)
  1627. {
  1628. var element = (Activator.CreateInstance(fieldControlType) as DynamicFormControl)!;
  1629. if(element is IDynamicFormFieldControl fieldControl)
  1630. {
  1631. fieldControl.FieldChangedEvent += () =>
  1632. {
  1633. ChangeField(field.Name);
  1634. };
  1635. }
  1636. return element;
  1637. }
  1638. return null;
  1639. }
  1640. private DynamicFormControl? CreateFieldPlaceholder(DFLayoutField field)
  1641. {
  1642. var controlType = typeof(DFFieldPlaceholderControl<>).MakeGenericType(field.GetType());
  1643. return Activator.CreateInstance(controlType) as DynamicFormControl;
  1644. }
  1645. private DynamicFormControl? CreateControl(DFLayoutControl item)
  1646. {
  1647. if (item is DFLayoutField field)
  1648. {
  1649. if (IsDesigning)
  1650. {
  1651. return CreateFieldPlaceholder(field);
  1652. }
  1653. return CreateFieldControl(field);
  1654. }
  1655. else if (item is DFLayoutElement)
  1656. {
  1657. return IsDesigning
  1658. ? new DFElementPlaceholderControl()
  1659. : new DFElementControl();
  1660. }
  1661. else if (item is DFLayoutLabel)
  1662. {
  1663. return new DFLabelControl();
  1664. }
  1665. else if (item is DFLayoutHeader)
  1666. {
  1667. return new DFHeaderControl();
  1668. }
  1669. else if (item is DFLayoutImage)
  1670. {
  1671. return new DFImageControl();
  1672. }
  1673. return null;
  1674. }
  1675. private FrameworkElement? CreateElement(DFLayoutControl item)
  1676. {
  1677. var control = CreateControl(item);
  1678. if(control != null)
  1679. {
  1680. control.FormDesignGrid = this;
  1681. control.SetControl(item);
  1682. }
  1683. return control;
  1684. }
  1685. private Brush GetItemBackgroundBrush(DFLayoutControl item, Color? colour = null)
  1686. {
  1687. if(colour != null)
  1688. {
  1689. var colourValue = colour.Value;
  1690. return new SolidColorBrush(new System.Windows.Media.Color { R = colourValue.R, G = colourValue.G, B = colourValue.B, A = colourValue.A });
  1691. }
  1692. if (item is DFLayoutField field)
  1693. return field.GetPropertyValue<bool>("Required") ? RequiredFieldBrush : FieldBrush;
  1694. else
  1695. return IsDesigning ? FieldBrush : BackgroundBrush;
  1696. }
  1697. private void RenderElement(DFLayoutControl item, int offset, bool horzstar, bool vertstar)
  1698. {
  1699. var border = CreateBorder(item.Row, item.Column, item.RowSpan, item.ColumnSpan, offset, horzstar, vertstar);
  1700. border.Background = GetItemBackgroundBrush(item);
  1701. if (!ShowBorders)
  1702. border.Padding = new Thickness(
  1703. item.Column == 1 ? 4 : 2,
  1704. item.Row == 1 ? 4 : 2,
  1705. item.Column + item.ColumnSpan - 1 == ColumnDefinitions.Count ? 4 : 2,
  1706. item.Row + item.RowSpan - 1 == RowDefinitions.Count ? 4 : 2
  1707. );
  1708. else
  1709. border.Padding = new Thickness(5);
  1710. var element = CreateElement(item);
  1711. border.Child = element;
  1712. Children.Add(border);
  1713. if (IsDesigning)
  1714. {
  1715. CreateElementContextMenu(border, item);
  1716. }
  1717. borderMap[item] = border;
  1718. if (element != null)
  1719. {
  1720. if(item is DFLayoutField)
  1721. {
  1722. element.IsEnabled = element.IsEnabled && !IsReadOnly;
  1723. }
  1724. elementmap[item] = element;
  1725. element.HorizontalAlignment = GetHorizontalAlignment(item.HorizontalAlignment);
  1726. element.VerticalAlignment = GetVerticalAlignment(item.VerticalAlignment);
  1727. if (IsDesigning)
  1728. {
  1729. CreateElementContextMenu(element, item);
  1730. }
  1731. }
  1732. }
  1733. private void AfterRender()
  1734. {
  1735. if (!IsDesigning)
  1736. {
  1737. foreach (var header in elementmap.Where(x => x.Value is DFHeaderControl head).Select(x => x.Value).Cast<DFHeaderControl>())
  1738. {
  1739. if (header.Header.Collapsed)
  1740. {
  1741. CollapseRows(header.Header, true);
  1742. }
  1743. }
  1744. }
  1745. OnAfterRender?.Invoke(this);
  1746. }
  1747. private void Render()
  1748. {
  1749. ClearSelection();
  1750. ClearResize();
  1751. foreach (var item in elementmap.Keys)
  1752. {
  1753. var e = elementmap[item];
  1754. if (VisualTreeHelper.GetParent(e) is Border parent)
  1755. parent.Child = null;
  1756. }
  1757. elementmap.Clear();
  1758. Children.Clear();
  1759. ColumnDefinitions.Clear();
  1760. RowDefinitions.Clear();
  1761. if (form == null)
  1762. return;
  1763. foreach (var column in form.ColumnWidths)
  1764. ColumnDefinitions.Add(new ColumnDefinition { Width = StringToGridLength(column) });
  1765. foreach (var row in form.RowHeights)
  1766. RowDefinitions.Add(new RowDefinition { Height = StringToGridLength(row), Tag = new RowData(row) });
  1767. var horzstar = ColumnDefinitions.Any(x => x.Width.IsStar);
  1768. var vertstar = RowDefinitions.Any(x => x.Height.IsStar);
  1769. var offset = 1;
  1770. if (IsDesigning)
  1771. {
  1772. ColumnDefinitions.Insert(0, new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
  1773. RowDefinitions.Insert(0, new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  1774. var topleft = new Button();
  1775. topleft.SetValue(RowProperty, 0);
  1776. topleft.SetValue(ColumnProperty, 0);
  1777. topleft.Content =
  1778. ""; // new Image() { Source = _designing ? Wpf.Resources.view.AsBitmapImage() : Wpf.Resources.design.AsBitmapImage() };
  1779. topleft.BorderBrush = BorderBrush;
  1780. topleft.BorderThickness = new Thickness(
  1781. 0.00F,
  1782. 0.00F,
  1783. 0.75F,
  1784. 0.75F
  1785. );
  1786. topleft.Background = BackgroundBrush;
  1787. //topleft.Click += (o, e) =>
  1788. //{
  1789. // Designing = !Designing;
  1790. //};
  1791. Children.Add(topleft);
  1792. for (var i = 1; i < ColumnDefinitions.Count; i++)
  1793. {
  1794. var Button = new Button();
  1795. Button.SetValue(RowProperty, 0);
  1796. Button.SetValue(ColumnProperty, i);
  1797. Button.Content = FormatGridLength(ColumnDefinitions[i].Width, ColumnDefinitions.Select(x => x.Width));
  1798. Button.BorderBrush = BorderBrush;
  1799. Button.BorderThickness = new Thickness(
  1800. 0.00F, //(i == 1) ? 0.75F : 0.0F,
  1801. 0.00F, //0.75F,
  1802. i == ColumnDefinitions.Count - 1 ? horzstar ? 0.00F : 0.75F : 0.75F,
  1803. 0.75F
  1804. );
  1805. Button.Background = BackgroundBrush;
  1806. Button.Padding = new Thickness(10);
  1807. Button.MinHeight = 35;
  1808. CreateColumnMenu(Button, i - 1);
  1809. AddClick(Button, i - 1, ColumnPropertiesClick);
  1810. Children.Add(Button);
  1811. }
  1812. for (var i = 1; i < RowDefinitions.Count; i++)
  1813. {
  1814. var Button = new Button();
  1815. Button.SetValue(RowProperty, i);
  1816. Button.SetValue(ColumnProperty, 0);
  1817. Button.Content = FormatGridLength(RowDefinitions[i].Height, RowDefinitions.Select(x => x.Height));
  1818. Button.BorderBrush = BorderBrush;
  1819. Button.BorderThickness = new Thickness(
  1820. 0.00F, //0.75F,
  1821. 0.00F, //(i == 1) ? 0.75F : 0.0F,
  1822. 0.75F,
  1823. i == RowDefinitions.Count - 1 ? vertstar ? 0.00F : 0.75F : 0.75F
  1824. );
  1825. Button.Background = BackgroundBrush;
  1826. Button.Padding = new Thickness(10);
  1827. CreateRowMenu(Button, i - 1);
  1828. AddClick(Button, i - 1, RowPropertiesClick);
  1829. Children.Add(Button);
  1830. }
  1831. offset = 0;
  1832. }
  1833. var filledcells = new HashSet<PointI>();
  1834. foreach (var item in form.GetElements(IsDesigning))
  1835. {
  1836. try
  1837. {
  1838. if(item.Row > 0 && item.Column > 0)
  1839. {
  1840. RenderElement(item, offset, horzstar, vertstar);
  1841. for (var c = item.Column; c < item.Column + item.ColumnSpan; c++)
  1842. for (var r = item.Row; r < item.Row + item.RowSpan; r++)
  1843. filledcells.Add(new PointI(c, r));
  1844. }
  1845. }
  1846. catch (Exception e)
  1847. {
  1848. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1849. }
  1850. }
  1851. for (var c = 1; c <= form.ColumnWidths.Count; c++)
  1852. for (var r = 1; r <= form.RowHeights.Count; r++)
  1853. if (!filledcells.Contains(new(c, r)))
  1854. {
  1855. var border = CreateBorder(r, c, 1, 1, offset, horzstar, vertstar);
  1856. if (IsDesigning)
  1857. {
  1858. CreateEmptyCellMenu(border, r, c);
  1859. }
  1860. Children.Add(border);
  1861. }
  1862. AfterRender();
  1863. }
  1864. #endregion
  1865. /// <summary>
  1866. /// Renders the form; after this is called, any changes to properties triggers a refresh.
  1867. /// </summary>
  1868. /// <remarks>
  1869. /// This should be called before <see cref="LoadValues(DFLoadStorage)"/> or <see cref="SaveValues"/>
  1870. /// </remarks>
  1871. public void Initialize()
  1872. {
  1873. GridInitialized = true;
  1874. CheckRefresh(false);
  1875. }
  1876. public void Refresh()
  1877. {
  1878. CheckRefresh(false);
  1879. }
  1880. private void CheckRefresh(bool keepValues = true)
  1881. {
  1882. if (!GridInitialized) return;
  1883. if (_mode == FormMode.Designing)
  1884. {
  1885. Render();
  1886. }
  1887. else if(keepValues)
  1888. {
  1889. var values = SaveValues();
  1890. Render();
  1891. LoadValues(values.ToLoadStorage());
  1892. }
  1893. else
  1894. {
  1895. Render();
  1896. Form.EvaluateExpressions();
  1897. }
  1898. }
  1899. #region Fields
  1900. private void ChangeField(string fieldName)
  1901. {
  1902. if (!_changing)
  1903. {
  1904. form.ChangeField(fieldName);
  1905. _isChanged = true;
  1906. OnChanged?.Invoke(this, fieldName);
  1907. }
  1908. }
  1909. private IDynamicFormFieldControl? GetFieldControl(DFLayoutField field)
  1910. {
  1911. return elementmap.GetValueOrDefault(field) as IDynamicFormFieldControl;
  1912. }
  1913. private void LoadFieldValue(string fieldName, DFLoadStorageEntry entry)
  1914. {
  1915. var field = form.Elements.FirstOrDefault(x => string.Equals(fieldName, (x as DFLayoutField)?.Name)) as DFLayoutField;
  1916. if (field != null)
  1917. {
  1918. var fieldControl = GetFieldControl(field);
  1919. if (fieldControl != null)
  1920. {
  1921. string? property = (DataModel != null) ? field.GetPropertyValue<string>("Property") : null;
  1922. if (!property.IsNullOrWhiteSpace())
  1923. fieldControl.SetValue(DataModel!.GetEntityValue(property));
  1924. else
  1925. fieldControl.Deserialize(entry);
  1926. }
  1927. }
  1928. }
  1929. public void SetFieldValue(string fieldName, object? value)
  1930. {
  1931. var field = form.Elements.FirstOrDefault(x => string.Equals(fieldName, (x as DFLayoutField)?.Name)) as DFLayoutField;
  1932. if (field != null)
  1933. {
  1934. var fieldControl = GetFieldControl(field);
  1935. if (fieldControl != null)
  1936. {
  1937. string? property = (DataModel != null) ? field.GetPropertyValue<string>("Property") : null;
  1938. if (!property.IsNullOrWhiteSpace())
  1939. fieldControl.SetValue(DataModel!.GetEntityValue(property));
  1940. else
  1941. fieldControl.SetValue(value);
  1942. }
  1943. }
  1944. }
  1945. private void GetFieldValue(DFLayoutField field, DFSaveStorageEntry storage, out object? entityValue)
  1946. {
  1947. var fieldControl = GetFieldControl(field);
  1948. if(fieldControl != null)
  1949. {
  1950. entityValue = fieldControl.GetEntityValue();
  1951. fieldControl.Serialize(storage);
  1952. }
  1953. else
  1954. {
  1955. entityValue = null;
  1956. }
  1957. }
  1958. public object? GetFieldValue(string fieldName)
  1959. {
  1960. var field = form.Elements.Where(x => (x as DFLayoutField)?.Name == fieldName).FirstOrDefault() as DFLayoutField;
  1961. if (field is null)
  1962. {
  1963. return null;
  1964. }
  1965. var fieldControl = GetFieldControl(field);
  1966. return fieldControl?.GetValue();
  1967. }
  1968. public object? GetFieldData(string fieldName, string dataField)
  1969. {
  1970. var field = form.Elements.Where(x => (x as DFLayoutField)?.Name == fieldName).FirstOrDefault() as DFLayoutField;
  1971. if (field is null)
  1972. {
  1973. return null;
  1974. }
  1975. var fieldControl = GetFieldControl(field);
  1976. return fieldControl?.GetData(dataField);
  1977. }
  1978. public void SetFieldColour(string fieldName, Color? colour)
  1979. {
  1980. var field = form.Elements.Where(x => (x as DFLayoutField)?.Name == fieldName).FirstOrDefault() as DFLayoutField;
  1981. if (field is null || !borderMap.TryGetValue(field, out var border))
  1982. {
  1983. return;
  1984. }
  1985. border.Background = GetItemBackgroundBrush(field, colour);
  1986. }
  1987. /// <summary>
  1988. /// Load values into editor; Must be called after <see cref="Initialize"/>.
  1989. /// </summary>
  1990. /// <remarks>
  1991. /// Resets <see cref="IsChanged"/>.
  1992. /// </remarks>
  1993. /// <param name="values">A storage object.</param>
  1994. public void LoadValues(DFLoadStorage values)
  1995. {
  1996. _changing = true;
  1997. InitializeEntityValues();
  1998. foreach (var (key, _) in values.Items())
  1999. {
  2000. if (!key.Contains('.'))
  2001. {
  2002. LoadFieldValue(key, values.GetEntry(key));
  2003. }
  2004. }
  2005. Form.EvaluateExpressions();
  2006. _changing = false;
  2007. _isChanged = false;
  2008. }
  2009. public void InitializeEntityValues()
  2010. {
  2011. _changing = true;
  2012. foreach (var field in form.Elements.OfType<DFLayoutField>())
  2013. {
  2014. var property = DataModel != null ? field.GetPropertyValue<string>("Property") : null;
  2015. if (!property.IsNullOrWhiteSpace())
  2016. {
  2017. var fieldControl = GetFieldControl(field);
  2018. if(fieldControl != null)
  2019. {
  2020. fieldControl.SetValue(DataModel!.GetEntityValue(property));
  2021. }
  2022. }
  2023. }
  2024. Form.EvaluateExpressions();
  2025. _changing = false;
  2026. _isChanged = false;
  2027. }
  2028. /// <summary>
  2029. /// Takes values from editors and saves them to a dictionary; must be called after <see cref="Initialize"/>.
  2030. /// </summary>
  2031. /// <returns>A dictionary of <see cref="DigitalFormVariable.Code"/> -> value.</returns>
  2032. public DFSaveStorage SaveValues()
  2033. {
  2034. var result = new DFSaveStorage();
  2035. foreach (var formElement in form.Elements)
  2036. if (formElement is DFLayoutField field)
  2037. {
  2038. GetFieldValue(field, result.GetEntry(field.Name), out var entityValue);
  2039. if(DataModel != null)
  2040. {
  2041. var property = field.GetPropertyValue<string>("Property");
  2042. if (!string.IsNullOrWhiteSpace(property))
  2043. DataModel.SetEntityValue(property, entityValue);
  2044. }
  2045. }
  2046. return result;
  2047. }
  2048. public bool Validate(out List<string> messages)
  2049. {
  2050. messages = new List<string>();
  2051. var valid = true;
  2052. foreach(var formElement in form.Elements)
  2053. {
  2054. if(formElement is DFLayoutField field)
  2055. {
  2056. var fieldControl = GetFieldControl(field);
  2057. if(fieldControl != null && !fieldControl.Validate(out var message))
  2058. {
  2059. messages.Add(message);
  2060. valid = false;
  2061. }
  2062. }
  2063. }
  2064. return valid;
  2065. }
  2066. #endregion
  2067. }