DynamicVariableGrid.cs 15 KB

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