DynamicVariableGrid.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using InABox.Core;
  9. using InABox.Wpf;
  10. using InABox.WPF;
  11. using MathNet.Numerics;
  12. using NPOI.OpenXmlFormats;
  13. using NPOI.SS.Formula.Functions;
  14. using NPOI.Util.Collections;
  15. namespace InABox.DynamicGrid
  16. {
  17. internal class DynamicVariableGrid : DynamicOneToManyGrid<DigitalForm, DigitalFormVariable>
  18. {
  19. private bool ShowHidden = false;
  20. private Button ShowHiddenButton;
  21. private Button HideButton;
  22. protected override void Init()
  23. {
  24. base.Init();
  25. ShowHiddenButton = AddButton("Show Hidden", null, ToggleHidden_Click);
  26. HideButton = AddButton("Hide Variable", null, Hide_Click);
  27. HideButton.IsEnabled = false;
  28. HiddenColumns.Add(x => x.Hidden);
  29. HiddenColumns.Add(x => x.Code);
  30. HiddenColumns.Add(x => x.VariableType);
  31. HiddenColumns.Add(x => x.Parameters);
  32. HiddenColumns.Add(x => x.Required);
  33. HiddenColumns.Add(x => x.Secure);
  34. HiddenColumns.Add(x => x.Retain);
  35. }
  36. protected override void DoReconfigure(DynamicGridOptions options)
  37. {
  38. base.DoReconfigure(options);
  39. options.MultiSelect = true;
  40. }
  41. public DigitalFormVariable? GetVariable(string code)
  42. {
  43. return Items.Where(x => x.Code == code).FirstOrDefault();
  44. }
  45. private static bool ShouldHide(CoreRow[] rows)
  46. {
  47. return rows.Any(x => !x.Get<DigitalFormVariable, bool>(x => x.Hidden));
  48. }
  49. private bool Hide_Click(Button btn, CoreRow[] rows)
  50. {
  51. if(rows.Length == 0)
  52. {
  53. MessageBox.Show("No rows selected");
  54. return false;
  55. }
  56. var hide = ShouldHide(rows);
  57. var items = LoadItems(rows);
  58. foreach (var item in items)
  59. {
  60. item.Hidden = hide;
  61. }
  62. if(items.Length > 0)
  63. {
  64. SaveItems(items);
  65. return true;
  66. }
  67. return false;
  68. }
  69. protected override void SelectItems(CoreRow[]? rows)
  70. {
  71. base.SelectItems(rows);
  72. if(rows is null)
  73. {
  74. HideButton.IsEnabled = false;
  75. }
  76. else
  77. {
  78. HideButton.IsEnabled = true;
  79. HideButton.Content = (ShouldHide(rows) ? "Hide Variable" : "Un-hide Variable") + (rows.Length > 1 ? "s" : "");
  80. }
  81. }
  82. private bool ToggleHidden_Click(Button btn, CoreRow[] rows)
  83. {
  84. ShowHidden = !ShowHidden;
  85. ShowHiddenButton.Content = ShowHidden ? "Hide Hidden" : "Show Hidden";
  86. return true;
  87. }
  88. private void CreateMenu(ContextMenu parent, string header, Type type)
  89. {
  90. parent.AddItem(header, null, type, (itemtype) =>
  91. {
  92. if(DynamicVariableUtils.CreateAndEdit(Item, Items, itemtype, out var variable))
  93. {
  94. SaveItem(variable);
  95. Refresh(false, true);
  96. }
  97. });
  98. }
  99. protected override void DoAdd(bool openEditorOnDirectEdit = false)
  100. {
  101. var menu = new ContextMenu();
  102. foreach(var fieldType in DFUtils.GetFieldTypes())
  103. {
  104. var caption = fieldType.GetCaption();
  105. if (string.IsNullOrWhiteSpace(caption))
  106. {
  107. caption = CoreUtils.Neatify(fieldType.Name);
  108. }
  109. CreateMenu(menu, caption, fieldType);
  110. }
  111. menu.IsOpen = true;
  112. }
  113. /*public override DigitalFormVariable LoadItem(CoreRow row)
  114. {
  115. return Items.FirstOrDefault(r => r.ID.Equals(row.Get<DigitalFormVariable, Guid>(c => c.ID)));
  116. }*/
  117. protected override void DoEdit()
  118. {
  119. if (!SelectedRows.Any())
  120. return;
  121. var variable = LoadItem(SelectedRows.First());
  122. var properties = variable.CreateProperties();
  123. if (DynamicVariableUtils.EditProperties(Item, Items, properties.GetType(), properties))
  124. {
  125. variable.SaveProperties(properties);
  126. SaveItem(variable);
  127. Refresh(false, true);
  128. }
  129. }
  130. protected override void DoDelete()
  131. {
  132. var rows = SelectedRows.ToArray();
  133. if (rows.Any())
  134. if (CanDeleteItems(rows))
  135. if (MessageBox.Show("Are you sure you want to delete this variable? This will all cause data associated with this variable to be lost.\n(If you want to just hide the variable, set it to 'Hidden' instead.)", "Confirm Deletion", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
  136. {
  137. DeleteItems(rows);
  138. SelectedRows = Array.Empty<CoreRow>();
  139. DoChanged();
  140. Refresh(false, true);
  141. SelectItems(null);
  142. }
  143. }
  144. protected override bool FilterRecord(CoreRow row)
  145. {
  146. return ShowHidden || !row.Get<DigitalFormVariable, bool>(x => x.Hidden);
  147. }
  148. }
  149. public class DFLookupFilterNode : ComboBox, ICustomValueNode
  150. {
  151. public DFLookupFilterNode(Type entityType, CustomFilterValue? selectedValue)
  152. {
  153. var properties = CoreUtils.PropertyList(entityType, x => x.GetCustomAttribute<DoNotSerialize>() == null, true).Keys.ToList();
  154. properties.Sort();
  155. Items.Add("");
  156. foreach (var property in properties)
  157. {
  158. Items.Add(property);
  159. }
  160. Value = selectedValue;
  161. SelectionChanged += DFLookupFilterNode_SelectionChanged;
  162. VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
  163. VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
  164. MinWidth = 50;
  165. }
  166. private void DFLookupFilterNode_SelectionChanged(object sender, SelectionChangedEventArgs e)
  167. {
  168. var text = SelectedItem as string;
  169. if (text.IsNullOrWhiteSpace())
  170. {
  171. _value = null;
  172. }
  173. else
  174. {
  175. _value = new CustomFilterValue(System.Text.Encoding.UTF8.GetBytes(text));
  176. }
  177. ValueChanged?.Invoke(this, Value);
  178. }
  179. private CustomFilterValue? _value;
  180. public CustomFilterValue? Value
  181. {
  182. get => _value;
  183. set
  184. {
  185. if(value is not null)
  186. {
  187. var text = System.Text.Encoding.UTF8.GetString(value.Data);
  188. SelectedItem = text;
  189. _value = value;
  190. }
  191. else
  192. {
  193. SelectedItem = null;
  194. _value = null;
  195. }
  196. }
  197. }
  198. public FrameworkElement FrameworkElement => this;
  199. public event ICustomValueNode.ValueChangedHandler? ValueChanged;
  200. }
  201. public static class DynamicVariableUtils
  202. {
  203. public static bool CreateAndEdit(
  204. DigitalForm form, IList<DigitalFormVariable> variables,
  205. Type fieldType,
  206. [NotNullWhen(true)] out DigitalFormVariable? variable)
  207. {
  208. var fieldBaseType = fieldType.GetSuperclassDefinition(typeof(DFLayoutField<>));
  209. if (fieldBaseType != null)
  210. {
  211. var propertiesType = fieldBaseType.GetGenericArguments()[0];
  212. var properties = (Activator.CreateInstance(propertiesType) as DFLayoutFieldProperties)!;
  213. if (DynamicVariableUtils.EditProperties(form, variables, propertiesType, properties))
  214. {
  215. variable = new DigitalFormVariable();
  216. variable.SaveProperties(fieldType, properties);
  217. return true;
  218. }
  219. }
  220. variable = null;
  221. return false;
  222. }
  223. public static bool EditProperties(DigitalForm form, IList<DigitalFormVariable> variables, Type type, DFLayoutFieldProperties item)
  224. {
  225. var editor = new DynamicEditorForm(type);
  226. if (item is DFLayoutLookupFieldProperties)
  227. {
  228. var appliesToType = DFUtils.FormEntityType(form);
  229. editor.OnReconfigureEditors = grid =>
  230. {
  231. var filter = grid.FindEditor("Filter");
  232. if(filter is FilterEditorControl filterEditor)
  233. {
  234. var config = new FilterEditorConfiguration();
  235. config.OnCreateCustomValueNode += (type, prop, op, value) =>
  236. {
  237. if (appliesToType is not null)
  238. {
  239. return new DFLookupFilterNode(appliesToType, value);
  240. }
  241. else
  242. {
  243. return null;
  244. }
  245. };
  246. filterEditor.Configuration = config;
  247. }
  248. };
  249. editor.OnFormCustomiseEditor += (sender, items, column, editor) => LookupEditor_OnFormCustomiseEditor(sender, variables, items, column, editor);
  250. editor.OnEditorValueChanged += (sender, name, value) =>
  251. {
  252. var result = DynamicGridUtils.UpdateEditorValue(new[] { item }, name, value);
  253. if (name == "LookupType")
  254. {
  255. var grid = (sender as EmbeddedDynamicEditorForm)?.Editor!;
  256. var edit = grid.FindEditor("Filter");
  257. if (edit is FilterEditorControl filter)
  258. {
  259. filter.FilterType = value is string str ?
  260. CoreUtils.GetEntityOrNull(str) :
  261. null;
  262. }
  263. var propertiesEditor = grid.FindEditor(nameof(DFLayoutLookupFieldProperties.AdditionalProperties));
  264. if (propertiesEditor is MultiLookupEditorControl multi && multi.EditorDefinition is MultiLookupEditor combo)
  265. {
  266. combo.Clear();
  267. multi.Configure();
  268. }
  269. }
  270. OnEditorValueChanged(sender, name, value);
  271. return new();
  272. };
  273. }
  274. else
  275. {
  276. editor.OnFormCustomiseEditor += (sender, items, column, editor) => Editor_OnFormCustomiseEditor(sender, variables, column, editor);
  277. editor.OnEditorValueChanged += (sender, name, value) =>
  278. {
  279. var result = DynamicGridUtils.UpdateEditorValue(new[] { item }, name, value);
  280. OnEditorValueChanged(sender, name, value);
  281. return result;
  282. };
  283. }
  284. editor.OnCreateEditorControl += Editor_OnCreateEditorControl;
  285. editor.OnDefineLookups += o =>
  286. {
  287. var def = (o.EditorDefinition as ILookupEditor)!;
  288. var colname = o.ColumnName;
  289. // Nope, there is nothing dodgy about this at all
  290. // I am not breaking any rules by passing in the QA Form instance, rather than the Field instance
  291. // so that I can get access to the "AppliesTo" property, and thus the list of properties that can be updated
  292. // Nothing to see here, I promise!
  293. CoreTable? values;
  294. if (o.ColumnName == "Property")
  295. {
  296. values = def.Values(colname, new[] { form });
  297. }
  298. else
  299. {
  300. values = def.Values(colname, new[] { item });
  301. }
  302. o.LoadLookups(values);
  303. };
  304. var thisVariable = variables.Where(x => x.Code == item.Code).ToList();
  305. editor.OnValidateData += (sender, items) =>
  306. {
  307. var errors = new List<string>();
  308. foreach(var item in items.Cast<DFLayoutFieldProperties>())
  309. {
  310. // Check Codes
  311. if (string.IsNullOrWhiteSpace(item.Code))
  312. {
  313. errors.Add("[Code] may not be blank!");
  314. }
  315. else
  316. {
  317. var codeVars = variables.Where(x => x.Code == item.Code).ToList();
  318. if(codeVars.Count > 1)
  319. {
  320. errors.Add($"Duplicate code [{item.Code}]");
  321. }
  322. else if(codeVars.Count == 1)
  323. {
  324. if (!thisVariable.Contains(codeVars.First()))
  325. {
  326. errors.Add($"There is already a variable with code [{item.Code}]");
  327. }
  328. }
  329. }
  330. // Check Read-Only property
  331. if(item.ReadOnlyProperty && item.Property.IsNullOrWhiteSpace() && item.Expression.IsNullOrWhiteSpace())
  332. {
  333. errors.Add("A field cannot be read-only if [Property] or [Expression] have not been set.");
  334. }
  335. }
  336. return errors;
  337. };
  338. editor.Items = new BaseObject[] { item };
  339. return editor.ShowDialog() == true;
  340. }
  341. private static void Editor_OnCreateEditorControl(string column, BaseEditor editor, IDynamicEditorControl control)
  342. {
  343. var properties = (control.Host.GetItems()[0] as DFLayoutFieldProperties)!;
  344. if(column == nameof(DFLayoutFieldProperties.ReadOnlyProperty))
  345. {
  346. if (properties.Property.IsNullOrWhiteSpace())
  347. {
  348. control.IsEnabled = false;
  349. }
  350. }
  351. }
  352. private static void Editor_OnFormCustomiseEditor(IDynamicEditorForm sender, IList<DigitalFormVariable> vars, DynamicGridColumn column, BaseEditor editor)
  353. {
  354. var properties = (sender.Items[0] as DFLayoutFieldProperties)!;
  355. if ((column.ColumnName == "Expression" || column.ColumnName == "ColourExpression") && editor is ExpressionEditor exp)
  356. {
  357. var variables = new List<string>();
  358. foreach (var variable in vars)
  359. {
  360. //variables.Add(variable.Code);
  361. foreach (var col in variable.GetVariableColumns())
  362. {
  363. variables.Add(col.ColumnName);
  364. }
  365. }
  366. variables.Remove(properties.Code);
  367. variables.Sort();
  368. exp.VariableNames = variables;
  369. }
  370. }
  371. private static void LookupEditor_OnFormCustomiseEditor(IDynamicEditorForm sender, IList<DigitalFormVariable> vars, object[] items, DynamicGridColumn column, BaseEditor editor)
  372. {
  373. if (column.ColumnName == "Filter" && editor is FilterEditor fe)
  374. {
  375. var properties = (items[0] as DFLayoutLookupFieldProperties)!;
  376. var lookupType = properties.LookupType;
  377. var entityType = CoreUtils.GetEntityOrNull(lookupType);
  378. fe.Type = entityType;
  379. }
  380. Editor_OnFormCustomiseEditor(sender, vars, column, editor);
  381. }
  382. private static void OnEditorValueChanged(IDynamicEditorForm sender, string name, object value)
  383. {
  384. if(name == nameof(DFLayoutFieldProperties.Property))
  385. {
  386. var properties = (sender.Items[0] as DFLayoutFieldProperties)!;
  387. var grid = (sender as EmbeddedDynamicEditorForm)?.Editor!;
  388. var edit = grid.FindEditor(nameof(DFLayoutFieldProperties.ReadOnlyProperty));
  389. if (edit is not null)
  390. {
  391. edit.IsEnabled = !properties.Property.IsNullOrWhiteSpace() && !grid.ReadOnly && edit.EditorDefinition.Editable.IsEditable();
  392. }
  393. }
  394. }
  395. }
  396. }