DFLayout.cs 22 KB

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