DFLayout.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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. foreach(var variable in variables)
  323. {
  324. var rowHeight = "Auto";
  325. var rowNum = new DFLayoutLabel { Caption = row.ToString(), Row = row, Column = 1 };
  326. var label = new DFLayoutLabel { Caption = variable.Code, Row = row, Column = 2 };
  327. layout.Elements.Add(rowNum);
  328. layout.Elements.Add(label);
  329. var field = GenerateLayoutFieldFromVariable(variable);
  330. if(field != null)
  331. {
  332. field.Row = row;
  333. field.Column = 3;
  334. layout.Elements.Add(field);
  335. rowHeight = GetLayoutFieldDefaultHeight(field);
  336. }
  337. layout.RowHeights.Add(rowHeight);
  338. ++row;
  339. }
  340. return layout;
  341. }
  342. public static DFLayout GenerateAutoMobileLayout(
  343. IList<DigitalFormVariable> variables)
  344. {
  345. var layout = new DFLayout();
  346. layout.ColumnWidths.Add("Auto");
  347. layout.ColumnWidths.Add("*");
  348. var row = 1;
  349. var i = 0;
  350. foreach(var variable in variables)
  351. {
  352. var rowHeight = "Auto";
  353. layout.RowHeights.Add("Auto");
  354. var rowNum = new DFLayoutLabel { Caption = i + 1 + ".", Row = row, Column = 1 };
  355. var label = new DFLayoutLabel { Caption = variable.Code, Row = row, Column = 2 };
  356. layout.Elements.Add(rowNum);
  357. layout.Elements.Add(label);
  358. var field = GenerateLayoutFieldFromVariable(variable);
  359. if(field != null)
  360. {
  361. field.Row = row + 1;
  362. field.Column = 1;
  363. field.ColumnSpan = 2;
  364. layout.Elements.Add(field);
  365. rowHeight = GetLayoutFieldDefaultHeight(field);
  366. }
  367. layout.RowHeights.Add(rowHeight);
  368. row += 2;
  369. ++i;
  370. }
  371. return layout;
  372. }
  373. public static DFLayout GenerateAutoLayout(DFLayoutType type, IList<DigitalFormVariable> variables)
  374. {
  375. return type switch
  376. {
  377. DFLayoutType.Mobile => GenerateAutoDesktopLayout(variables),
  378. _ => GenerateAutoDesktopLayout(variables),
  379. };
  380. }
  381. public static DFLayoutField? GenerateLayoutFieldFromEditor(BaseEditor editor)
  382. {
  383. // TODO: Finish
  384. switch (editor)
  385. {
  386. case CheckBoxEditor _:
  387. var newField = new DFLayoutBooleanField();
  388. newField.Properties.Type = DesignBooleanFieldType.Checkbox;
  389. return newField;
  390. case CheckListEditor _:
  391. // TODO: At this point, it seems CheckListEditor is unused.
  392. throw new NotImplementedException();
  393. case UniqueCodeEditor _:
  394. case CodeEditor _:
  395. return new DFLayoutCodeField();
  396. /* Not implemented because we don't like it.
  397. case PopupEditor v:*/
  398. case CodePopupEditor codePopupEditor:
  399. // TODO: Let's look at this later. For now, using a lookup.
  400. var newLookupFieldPopup = new DFLayoutLookupField();
  401. newLookupFieldPopup.Properties.LookupType = codePopupEditor.Type.EntityName();
  402. return newLookupFieldPopup;
  403. case ColorEditor _:
  404. return new DFLayoutColorField();
  405. case CurrencyEditor _:
  406. // TODO: Make this a specialised editor
  407. return new DFLayoutDoubleField();
  408. case DateEditor _:
  409. return new DFLayoutDateField();
  410. case DateTimeEditor _:
  411. return new DFLayoutDateTimeField();
  412. case DoubleEditor _:
  413. return new DFLayoutDoubleField();
  414. case DurationEditor _:
  415. return new DFLayoutTimeField();
  416. case EmbeddedImageEditor _:
  417. return new DFLayoutEmbeddedImage();
  418. case FileNameEditor _:
  419. case FolderEditor _:
  420. // Unimplemented because these editors only apply to properties for server engine configuration; it
  421. // doesn't make sense to store filenames in the database, and hence no entity will ever try to be saved
  422. // with a property with these editors.
  423. throw new NotImplementedException("This has intentionally been left unimplemented.");
  424. case IntegerEditor _:
  425. return new DFLayoutIntegerField();
  426. case ComboLookupEditor _:
  427. case EnumLookupEditor _:
  428. var newComboLookupField = new DFLayoutOptionField();
  429. var comboValuesTable = (editor as StaticLookupEditor)!.Values("Key");
  430. newComboLookupField.Properties.Options = string.Join(",", comboValuesTable.ExtractValues<string>("Key"));
  431. return newComboLookupField;
  432. case LookupEditor lookupEditor:
  433. var newLookupField = new DFLayoutLookupField();
  434. newLookupField.Properties.LookupType = lookupEditor.Type.EntityName();
  435. return newLookupField;
  436. case ImageDocumentEditor _:
  437. case MiscellaneousDocumentEditor _:
  438. case VectorDocumentEditor _:
  439. case PDFDocumentEditor _:
  440. var newDocField = new DFLayoutDocumentField();
  441. newDocField.Properties.FileMask = (editor as BaseDocumentEditor)!.FileMask;
  442. return newDocField;
  443. case NotesEditor _:
  444. return new DFLayoutNotesField();
  445. case NullEditor _:
  446. return null;
  447. case PasswordEditor _:
  448. return new DFLayoutPasswordField();
  449. case PINEditor _:
  450. var newPINField = new DFLayoutPINField();
  451. newPINField.Properties.Length = ClientFactory.PINLength;
  452. return newPINField;
  453. // TODO: Implement JSON editors and RichText editors.
  454. case JsonEditor _:
  455. case MemoEditor _:
  456. case RichTextEditor _:
  457. case ButtonEditor _:
  458. case ScriptEditor _:
  459. return new DFLayoutTextField();
  460. case TextBoxEditor _:
  461. return new DFLayoutStringField();
  462. case TimestampEditor _:
  463. return new DFLayoutTimeStampField();
  464. case TimeOfDayEditor _:
  465. return new DFLayoutTimeField();
  466. case URLEditor _:
  467. return new DFLayoutURLField();
  468. }
  469. return null;
  470. }
  471. public static DFLayout GenerateEntityLayout(Type entityType)
  472. {
  473. var layout = new DFLayout();
  474. layout.ColumnWidths.Add("Auto");
  475. layout.ColumnWidths.Add("*");
  476. var properties = DatabaseSchema.Properties(entityType);
  477. var Row = 1;
  478. foreach (var property in properties)
  479. {
  480. var editor = EditorUtils.GetPropertyEditor(entityType, property);
  481. if (editor != null && !(editor is NullEditor) && editor.Editable != Editable.Hidden)
  482. {
  483. var field = GenerateLayoutFieldFromEditor(editor);
  484. if (field != null)
  485. {
  486. var label = new DFLayoutLabel { Caption = editor.Caption };
  487. label.Row = Row;
  488. label.Column = 1;
  489. field.Row = Row;
  490. field.Column = 2;
  491. field.Name = property.Name;
  492. layout.Elements.Add(label);
  493. layout.Elements.Add(field);
  494. layout.RowHeights.Add("Auto");
  495. Row++;
  496. }
  497. }
  498. }
  499. return layout;
  500. }
  501. public static DFLayout GenerateEntityLayout<T>()
  502. {
  503. return GenerateEntityLayout(typeof(T));
  504. }
  505. #endregion
  506. }
  507. }