DFLayout.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Xml.Linq;
  8. using Expressive;
  9. using InABox.Clients;
  10. namespace InABox.Core
  11. {
  12. public interface IDFRenderer
  13. {
  14. /// <summary>
  15. /// Retrieve the value of a field, for use in expressions.
  16. /// </summary>
  17. /// <param name="field"></param>
  18. /// <returns></returns>
  19. object? GetFieldValue(string field);
  20. /// <summary>
  21. /// Retrieve a piece of additional data for a field.
  22. /// </summary>
  23. /// <param name="fieldName">The field name, which is the variable code.</param>
  24. /// <param name="dataField">The specific field to be retrieved from the variable.</param>
  25. /// <returns>A value, which is specific to the type of <paramref name="fieldName"/> and the specific <paramref name="dataField"/> being
  26. /// retrieved.</returns>
  27. object? GetFieldData(string fieldName, string dataField);
  28. void SetFieldValue(string field, object? value);
  29. /// <summary>
  30. /// Set the background colour for a field.
  31. /// </summary>
  32. void SetFieldColour(string field, Color? colour = null);
  33. }
  34. public class DFLayout
  35. {
  36. public DFLayout()
  37. {
  38. ColumnWidths = new List<string>();
  39. RowHeights = new List<string>();
  40. Elements = new List<DFLayoutControl>();
  41. HiddenElements = new List<DFLayoutControl>();
  42. Expressions = new Dictionary<string, CoreExpression>();
  43. ColourExpressions = new Dictionary<string, CoreExpression>();
  44. VariableReferences = new Dictionary<string, List<Tuple<ReferenceType, string>>>();
  45. }
  46. public List<string> ColumnWidths { get; }
  47. public List<string> RowHeights { get; }
  48. public List<DFLayoutControl> Elements { get; }
  49. public List<DFLayoutControl> HiddenElements { get; }
  50. private enum ReferenceType
  51. {
  52. Value,
  53. Colour
  54. }
  55. private Dictionary<string, CoreExpression> Expressions;
  56. private Dictionary<string, CoreExpression> ColourExpressions;
  57. private Dictionary<string, List<Tuple<ReferenceType, string>>> VariableReferences;
  58. public IDFRenderer? Renderer;
  59. public IEnumerable<DFLayoutControl> GetElements(bool includeHidden = false)
  60. {
  61. foreach (var element in Elements)
  62. {
  63. yield return element;
  64. }
  65. if (includeHidden)
  66. {
  67. foreach (var element in HiddenElements)
  68. {
  69. yield return element;
  70. }
  71. }
  72. }
  73. public string SaveLayout()
  74. {
  75. var sb = new StringBuilder();
  76. foreach (var column in ColumnWidths)
  77. sb.AppendFormat("C {0}\n", column);
  78. foreach (var row in RowHeights)
  79. sb.AppendFormat("R {0}\n", row);
  80. foreach (var element in Elements)
  81. sb.AppendFormat("E {0} {1}\n", element.GetType().EntityName(), element.SaveToString());
  82. var result = sb.ToString();
  83. return result;
  84. }
  85. private static Dictionary<string, Type>? _controls;
  86. /// <returns>A type which is a <see cref="DFLayoutControl"/></returns>
  87. private Type? GetElementType(string typeName)
  88. {
  89. _controls ??= CoreUtils.Entities.Where(x => x.IsClass && !x.IsGenericType && typeof(DFLayoutControl).IsAssignableFrom(x)).ToDictionary(
  90. x => x.EntityName(),
  91. x => x);
  92. return _controls.GetValueOrDefault(typeName);
  93. }
  94. private static bool IsHidden(DFLayoutControl element)
  95. => element is DFLayoutField field && field.GetPropertyValue<bool>("Hidden");
  96. public void LoadLayout(string layout)
  97. {
  98. ColumnWidths.Clear();
  99. RowHeights.Clear();
  100. Elements.Clear();
  101. var lines = layout.Split('\n');
  102. foreach (var line in lines)
  103. if (line.StartsWith("C "))
  104. {
  105. ColumnWidths.Add(line.Substring(2));
  106. }
  107. else if (line.StartsWith("R "))
  108. {
  109. RowHeights.Add(line.Substring(2));
  110. }
  111. else if (line.StartsWith("E ") || line.StartsWith("O "))
  112. {
  113. var typename = line.Split(' ').Skip(1).FirstOrDefault()
  114. ?.Replace("InABox.Core.Design", "InABox.Core.DFLayout")
  115. ?.Replace("DFLayoutChoiceField", "DFLayoutOptionField");
  116. if (!string.IsNullOrWhiteSpace(typename))
  117. {
  118. var type = GetElementType(typename);
  119. if(type != null)
  120. {
  121. var element = (Activator.CreateInstance(type) as DFLayoutControl)!;
  122. var json = string.Join(" ", line.Split(' ').Skip(2));
  123. element.LoadFromString(json);
  124. //Serialization.DeserializeInto(json, element);
  125. if(IsHidden(element))
  126. {
  127. HiddenElements.Add(element);
  128. }
  129. else
  130. {
  131. Elements.Add(element);
  132. }
  133. }
  134. else
  135. {
  136. Logger.Send(LogType.Error, ClientFactory.UserID, $"{typename} is not the name of any concrete DFLayoutControls!");
  137. }
  138. }
  139. }
  140. //else if (line.StartsWith("O "))
  141. //{
  142. // String typename = line.Split(' ').Skip(1).FirstOrDefault()?.Replace("PRSDesktop", "InABox.Core");
  143. // if (!String.IsNullOrWhiteSpace(typename))
  144. // {
  145. // Type type = Type.GetType(typename);
  146. // DesignControl element = Activator.CreateInstance(type) as DesignControl;
  147. // if (element != null)
  148. // {
  149. // String json = String.Join(" ", line.Split(' ').Skip(2));
  150. // element.LoadFromString(json);
  151. // //CoreUtils.DeserializeInto(json, element);
  152. // }
  153. // Elements.Add(element);
  154. // }
  155. //}
  156. // Invalid Line Hmmm..
  157. if (!ColumnWidths.Any())
  158. ColumnWidths.AddRange(new[] { "*", "Auto" });
  159. if (!RowHeights.Any())
  160. RowHeights.AddRange(new[] { "Auto" });
  161. }
  162. private void AddVariableReference(string reference, string fieldName, ReferenceType referenceType)
  163. {
  164. if (reference.Contains('.'))
  165. reference = reference.Split('.')[0];
  166. if(!VariableReferences.TryGetValue(reference, out var refs))
  167. {
  168. refs = new List<Tuple<ReferenceType, string>>();
  169. VariableReferences[reference] = refs;
  170. }
  171. refs.Add(new Tuple<ReferenceType, string>(referenceType, fieldName));
  172. }
  173. private object? GetFieldValue(string field)
  174. {
  175. if (field.Contains('.'))
  176. {
  177. var parts = field.Split('.');
  178. return Renderer?.GetFieldData(parts[0], string.Join('.', parts.Skip(1)));
  179. }
  180. else
  181. {
  182. return Renderer?.GetFieldValue(field);
  183. }
  184. }
  185. private void EvaluateValueExpression(string name)
  186. {
  187. var expression = Expressions[name];
  188. var values = new Dictionary<string, object?>();
  189. foreach (var field in expression.ReferencedVariables)
  190. {
  191. values[field] = GetFieldValue(field);
  192. }
  193. var oldValue = Renderer?.GetFieldValue(name);
  194. try
  195. {
  196. var value = expression?.Evaluate(values);
  197. if(value != oldValue)
  198. {
  199. Renderer?.SetFieldValue(name, value);
  200. }
  201. }
  202. catch (Exception e)
  203. {
  204. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error in Expression field '{name}': {CoreUtils.FormatException(e)}");
  205. }
  206. }
  207. private void EvaluateColourExpression(string name)
  208. {
  209. var expression = ColourExpressions[name];
  210. var values = new Dictionary<string, object?>();
  211. foreach (var field in expression.ReferencedVariables)
  212. {
  213. values[field] = GetFieldValue(field);
  214. }
  215. try
  216. {
  217. var colour = expression?.Evaluate(values);
  218. Renderer?.SetFieldColour(name, DFLayoutUtils.ConvertObjectToColour(colour));
  219. }
  220. catch (Exception e)
  221. {
  222. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error in Expression field '{name}': {CoreUtils.FormatException(e)}");
  223. }
  224. }
  225. private void LoadExpression(string fieldName, string? expressionStr, ReferenceType referenceType)
  226. {
  227. if (string.IsNullOrWhiteSpace(expressionStr))
  228. return;
  229. var expression = new CoreExpression(expressionStr);
  230. foreach (var reference in expression.ReferencedVariables)
  231. {
  232. AddVariableReference(reference, fieldName, referenceType);
  233. }
  234. switch (referenceType)
  235. {
  236. case ReferenceType.Value:
  237. Expressions[fieldName] = expression;
  238. break;
  239. case ReferenceType.Colour:
  240. ColourExpressions[fieldName] = expression;
  241. break;
  242. }
  243. }
  244. public void LoadVariable(DigitalFormVariable variable, DFLayoutField field)
  245. {
  246. var properties = variable.LoadProperties(field);
  247. LoadExpression(field.Name, properties?.Expression, ReferenceType.Value);
  248. LoadExpression(field.Name, properties?.ColourExpression, ReferenceType.Colour);
  249. }
  250. public void LoadVariables(IEnumerable<DigitalFormVariable> variables)
  251. {
  252. foreach (var field in Elements.Where(x => x is DFLayoutField).Cast<DFLayoutField>())
  253. {
  254. var variable = variables.FirstOrDefault(x => string.Equals(x.Code, field.Name));
  255. if (variable != null)
  256. {
  257. LoadVariable(variable, field);
  258. }
  259. }
  260. }
  261. public static DFLayout FromLayoutString(string layoutString)
  262. {
  263. var layout = new DFLayout();
  264. layout.LoadLayout(layoutString);
  265. return layout;
  266. }
  267. #region Expression Fields
  268. public void ChangeField(string fieldName)
  269. {
  270. if (!VariableReferences.TryGetValue(fieldName, out var refs)) return;
  271. foreach(var (refType, refName) in refs)
  272. {
  273. switch (refType)
  274. {
  275. case ReferenceType.Value:
  276. EvaluateValueExpression(refName);
  277. break;
  278. case ReferenceType.Colour:
  279. EvaluateColourExpression(refName);
  280. break;
  281. }
  282. }
  283. }
  284. public void EvaluateExpressions()
  285. {
  286. foreach(var name in Expressions.Keys)
  287. {
  288. EvaluateValueExpression(name);
  289. }
  290. foreach(var name in ColourExpressions.Keys)
  291. {
  292. EvaluateColourExpression(name);
  293. }
  294. }
  295. #endregion
  296. #region Auto-generated Layouts
  297. public static string GetLayoutFieldDefaultHeight(DFLayoutField field)
  298. {
  299. if (field is DFLayoutSignaturePad || field is DFLayoutMultiSignaturePad)
  300. return "200";
  301. return "Auto";
  302. }
  303. public static DFLayoutField? GenerateLayoutFieldFromVariable(DigitalFormVariable variable)
  304. {
  305. DFLayoutField? field = Activator.CreateInstance(variable.FieldType()) as DFLayoutField;
  306. if(field == null)
  307. {
  308. return null;
  309. }
  310. field.Name = variable.Code;
  311. return field;
  312. }
  313. public static DFLayout GenerateAutoDesktopLayout(
  314. IList<DigitalFormVariable> variables)
  315. {
  316. var layout = new DFLayout();
  317. layout.ColumnWidths.Add("Auto");
  318. layout.ColumnWidths.Add("Auto");
  319. layout.ColumnWidths.Add("*");
  320. int row = 1;
  321. var group = "";
  322. foreach(var variable in variables)
  323. {
  324. if (!String.IsNullOrWhiteSpace(variable.Group) && !String.Equals(variable.Group, group))
  325. {
  326. layout.RowHeights.Add("Auto");
  327. var header = new DFLayoutHeader()
  328. { Header = variable.Group, Row = row, Column = 1, ColumnSpan = 3, Collapsed = !String.IsNullOrWhiteSpace(group) };
  329. layout.Elements.Add(header);
  330. group = variable.Group;
  331. row++;
  332. }
  333. var rowHeight = "Auto";
  334. var rowNum = new DFLayoutLabel { Caption = row.ToString(), Row = row, Column = 1 };
  335. var label = new DFLayoutLabel { Caption = variable.Code, Row = row, Column = 2 };
  336. layout.Elements.Add(rowNum);
  337. layout.Elements.Add(label);
  338. var field = GenerateLayoutFieldFromVariable(variable);
  339. if(field != null)
  340. {
  341. field.Row = row;
  342. field.Column = 3;
  343. layout.Elements.Add(field);
  344. rowHeight = GetLayoutFieldDefaultHeight(field);
  345. }
  346. layout.RowHeights.Add(rowHeight);
  347. ++row;
  348. }
  349. return layout;
  350. }
  351. public static DFLayout GenerateAutoMobileLayout(
  352. IList<DigitalFormVariable> variables)
  353. {
  354. var layout = new DFLayout();
  355. layout.ColumnWidths.Add("Auto");
  356. layout.ColumnWidths.Add("*");
  357. var row = 1;
  358. var i = 0;
  359. var group = "";
  360. foreach(var variable in variables)
  361. {
  362. if (!String.IsNullOrWhiteSpace(variable.Group) && !String.Equals(variable.Group, group))
  363. {
  364. layout.RowHeights.Add("Auto");
  365. var header = new DFLayoutHeader()
  366. { Header = variable.Group, Row = row, Column = 1, ColumnSpan = 2, Collapsed = !String.IsNullOrWhiteSpace(group) };
  367. layout.Elements.Add(header);
  368. group = variable.Group;
  369. row++;
  370. }
  371. var rowHeight = "Auto";
  372. layout.RowHeights.Add("Auto");
  373. var rowNum = new DFLayoutLabel { Caption = i + 1 + ".", Row = row, Column = 1 };
  374. var label = new DFLayoutLabel { Caption = variable.Code, Row = row, Column = 2 };
  375. layout.Elements.Add(rowNum);
  376. layout.Elements.Add(label);
  377. var field = GenerateLayoutFieldFromVariable(variable);
  378. if(field != null)
  379. {
  380. field.Row = row + 1;
  381. field.Column = 1;
  382. field.ColumnSpan = 2;
  383. layout.Elements.Add(field);
  384. rowHeight = GetLayoutFieldDefaultHeight(field);
  385. }
  386. layout.RowHeights.Add(rowHeight);
  387. row += 2;
  388. ++i;
  389. }
  390. return layout;
  391. }
  392. public static DFLayout GenerateAutoLayout(DFLayoutType type, IList<DigitalFormVariable> variables)
  393. {
  394. return type switch
  395. {
  396. DFLayoutType.Mobile => GenerateAutoDesktopLayout(variables),
  397. _ => GenerateAutoDesktopLayout(variables),
  398. };
  399. }
  400. public static DFLayoutField? GenerateLayoutFieldFromEditor(BaseEditor editor)
  401. {
  402. // TODO: Finish
  403. switch (editor)
  404. {
  405. case CheckBoxEditor _:
  406. var newField = new DFLayoutBooleanField();
  407. newField.Properties.Type = DesignBooleanFieldType.Checkbox;
  408. return newField;
  409. case CheckListEditor _:
  410. // TODO: At this point, it seems CheckListEditor is unused.
  411. throw new NotImplementedException();
  412. case UniqueCodeEditor _:
  413. case CodeEditor _:
  414. return new DFLayoutCodeField();
  415. /* Not implemented because we don't like it.
  416. case PopupEditor v:*/
  417. case CodePopupEditor codePopupEditor:
  418. // TODO: Let's look at this later. For now, using a lookup.
  419. var newLookupFieldPopup = new DFLayoutLookupField();
  420. newLookupFieldPopup.Properties.LookupType = codePopupEditor.Type.EntityName();
  421. return newLookupFieldPopup;
  422. case ColorEditor _:
  423. return new DFLayoutColorField();
  424. case CurrencyEditor _:
  425. // TODO: Make this a specialised editor
  426. return new DFLayoutDoubleField();
  427. case DateEditor _:
  428. return new DFLayoutDateField();
  429. case DateTimeEditor _:
  430. return new DFLayoutDateTimeField();
  431. case DoubleEditor _:
  432. return new DFLayoutDoubleField();
  433. case DurationEditor _:
  434. return new DFLayoutTimeField();
  435. case EmbeddedImageEditor _:
  436. return new DFLayoutEmbeddedImage();
  437. case FileNameEditor _:
  438. case FolderEditor _:
  439. // Unimplemented because these editors only apply to properties for server engine configuration; it
  440. // doesn't make sense to store filenames in the database, and hence no entity will ever try to be saved
  441. // with a property with these editors.
  442. throw new NotImplementedException("This has intentionally been left unimplemented.");
  443. case IntegerEditor _:
  444. return new DFLayoutIntegerField();
  445. case ComboLookupEditor _:
  446. case EnumLookupEditor _:
  447. var newComboLookupField = new DFLayoutOptionField();
  448. var comboValuesTable = (editor as StaticLookupEditor)!.Values(typeof(object), "Key");
  449. newComboLookupField.Properties.Options = string.Join(",", comboValuesTable.ExtractValues<string>("Key"));
  450. return newComboLookupField;
  451. case LookupEditor lookupEditor:
  452. var newLookupField = new DFLayoutLookupField();
  453. newLookupField.Properties.LookupType = lookupEditor.Type.EntityName();
  454. return newLookupField;
  455. case ImageDocumentEditor _:
  456. case MiscellaneousDocumentEditor _:
  457. case VectorDocumentEditor _:
  458. case PDFDocumentEditor _:
  459. var newDocField = new DFLayoutDocumentField();
  460. newDocField.Properties.FileMask = (editor as BaseDocumentEditor)!.FileMask;
  461. return newDocField;
  462. case NotesEditor _:
  463. return new DFLayoutNotesField();
  464. case NullEditor _:
  465. return null;
  466. case PasswordEditor _:
  467. return new DFLayoutPasswordField();
  468. case PINEditor _:
  469. var newPINField = new DFLayoutPINField();
  470. newPINField.Properties.Length = ClientFactory.PINLength;
  471. return newPINField;
  472. // TODO: Implement JSON editors and RichText editors.
  473. case JsonEditor _:
  474. case MemoEditor _:
  475. case RichTextEditor _:
  476. case ButtonEditor _:
  477. case ScriptEditor _:
  478. return new DFLayoutTextField();
  479. case TextBoxEditor _:
  480. return new DFLayoutStringField();
  481. case TimestampEditor _:
  482. return new DFLayoutTimeStampField();
  483. case TimeOfDayEditor _:
  484. return new DFLayoutTimeField();
  485. case URLEditor _:
  486. return new DFLayoutURLField();
  487. }
  488. return null;
  489. }
  490. public static DFLayout GenerateEntityLayout(Type entityType)
  491. {
  492. var layout = new DFLayout();
  493. layout.ColumnWidths.Add("Auto");
  494. layout.ColumnWidths.Add("*");
  495. var properties = DatabaseSchema.Properties(entityType);
  496. var Row = 1;
  497. foreach (var property in properties)
  498. {
  499. var editor = EditorUtils.GetPropertyEditor(entityType, property);
  500. if (editor != null && !(editor is NullEditor) && editor.Editable.EditorVisible())
  501. {
  502. var field = GenerateLayoutFieldFromEditor(editor);
  503. if (field != null)
  504. {
  505. var label = new DFLayoutLabel { Caption = editor.Caption };
  506. label.Row = Row;
  507. label.Column = 1;
  508. field.Row = Row;
  509. field.Column = 2;
  510. field.Name = property.Name;
  511. layout.Elements.Add(label);
  512. layout.Elements.Add(field);
  513. layout.RowHeights.Add("Auto");
  514. Row++;
  515. }
  516. }
  517. }
  518. return layout;
  519. }
  520. public static DFLayout GenerateEntityLayout<T>()
  521. {
  522. return GenerateEntityLayout(typeof(T));
  523. }
  524. #endregion
  525. }
  526. }