DynamicGrid.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Linq.Expressions;
  9. using System.Runtime.CompilerServices;
  10. using System.Threading.Tasks;
  11. using System.Windows;
  12. using System.Windows.Controls;
  13. using System.Windows.Data;
  14. using System.Windows.Input;
  15. using System.Windows.Media;
  16. using System.Windows.Media.Animation;
  17. using System.Windows.Media.Imaging;
  18. using InABox.Clients;
  19. using InABox.Core;
  20. using InABox.Wpf;
  21. using InABox.WPF;
  22. using Syncfusion.Data;
  23. using Syncfusion.UI.Xaml.Grid;
  24. using Syncfusion.UI.Xaml.Grid.Helpers;
  25. using static InABox.DynamicGrid.IDynamicGrid;
  26. using Color = System.Drawing.Color;
  27. using Columns = InABox.Core.Columns;
  28. using Image = System.Windows.Controls.Image;
  29. using RowColumnIndex = Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex;
  30. using SolidColorBrush = System.Windows.Media.SolidColorBrush;
  31. using String = System.String;
  32. using VerticalAlignment = System.Windows.VerticalAlignment;
  33. using VirtualizingCellsControl = Syncfusion.UI.Xaml.Grid.VirtualizingCellsControl;
  34. using System.Threading;
  35. using System.Diagnostics.CodeAnalysis;
  36. namespace InABox.DynamicGrid;
  37. public abstract class DynamicGrid<T> : BaseDynamicGrid, IDynamicGridUIComponentParent<T>, IDynamicGrid<T>,
  38. IImportDynamicGrid, IExportDynamicGrid, IDuplicateDynamicGrid, IHelpDynamicGrid
  39. where T : BaseObject, new()
  40. {
  41. #region Events
  42. public ValidateEvent<T>? OnValidate { get; set; }
  43. public event OnDefineFilter? OnDefineFilter;
  44. public event OnCreateItem? OnCreateItem;
  45. public event OnAfterCreateItem? OnAfterCreateItem;
  46. public event EditorValueChangedHandler? OnEditorValueChanged;
  47. public event OnAfterEditorValueChanged? OnAfterEditorValueChangedEvent;
  48. private List<(OnCustomiseEditor, OnCustomiseEditor<T>)> _customiseEditorEvents;
  49. event OnCustomiseEditor? IDynamicGrid.OnCustomiseEditor
  50. {
  51. add
  52. {
  53. if (value is null) return;
  54. void dlg(IDynamicEditorForm sender, T[]? items, DynamicGridColumn column, BaseEditor editor)
  55. {
  56. value?.Invoke(sender, items, column, editor);
  57. }
  58. _customiseEditorEvents ??= new();
  59. _customiseEditorEvents.Add((value, dlg));
  60. OnCustomiseEditor += dlg;
  61. }
  62. remove
  63. {
  64. var (_, dlg) = _customiseEditorEvents.FirstOrDefault(x => x.Item1 == value);
  65. if(dlg is not null)
  66. {
  67. OnCustomiseEditor -= dlg;
  68. }
  69. }
  70. }
  71. public event OnCustomiseEditor<T>? OnCustomiseEditor;
  72. public event EntitySaveEvent? OnBeforeSave;
  73. public event EntitySaveEvent? OnAfterSave;
  74. public delegate void EditorLoaded(IDynamicEditorForm editor, T[] items);
  75. public event EditorLoaded? OnEditorLoaded;
  76. public event OnLoadEditorButtons<T>? OnLoadEditorButtons;
  77. #endregion
  78. protected virtual string HelpSlug()
  79. {
  80. return typeof(T).Name.Split('.').Last().SplitCamelCase().Replace(" ", "_");
  81. }
  82. string IHelpDynamicGrid.HelpSlug() => HelpSlug();
  83. protected override bool CanDuplicate => typeof(T).IsAssignableTo(typeof(IDuplicatable));
  84. public DynamicGrid() : base()
  85. {
  86. }
  87. protected sealed override void PreInit()
  88. {
  89. MasterColumns = new DynamicGridColumns();
  90. MasterColumns.ExtractColumns(typeof(T));
  91. HiddenColumns = new HiddenColumnsList();
  92. if (typeof(T).IsAssignableTo(typeof(ISequenceable)))
  93. {
  94. HiddenColumns.Add(x => (x as ISequenceable)!.Sequence);
  95. }
  96. }
  97. protected override void Init()
  98. {
  99. }
  100. #region IDynamicGridUIComponentParent
  101. protected override IDynamicGridUIComponent CreateUIComponent()
  102. {
  103. return new DynamicGridGridUIComponent<T>
  104. {
  105. Parent = this
  106. };
  107. }
  108. T IDynamicGrid<T>.LoadItem(CoreRow row) => LoadItem(row);
  109. void IDynamicGridUIComponentParent<T>.EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  110. => EntityChanged(obj, row, changedColumn, changes);
  111. void IDynamicGridUIComponentParent<T>.UpdateData(T obj, CoreRow row, string changedColumn, Dictionary<CoreColumn, object?> updates)
  112. {
  113. var result = new Dictionary<string, object?>();
  114. foreach (var (col, value) in updates)
  115. {
  116. UpdateRow(row, col.ColumnName, value, refresh: false);
  117. DynamicGridUtils.UpdateEditorValue(new BaseObject[] { obj }, col.ColumnName, value, result);
  118. }
  119. EntityChanged(obj, row, changedColumn, result);
  120. }
  121. #endregion
  122. protected override DynamicGridRowStyleSelector GetRowStyleSelector()
  123. {
  124. return new DynamicGridRowStyleSelector<T, DynamicGridRowStyle>();
  125. }
  126. public DynamicGridColumns MasterColumns { get; protected set; }
  127. public override void OnItemSourceChanged(object value)
  128. {
  129. Data = value as CoreTable;
  130. Refresh(true, true);
  131. }
  132. public class HiddenColumnsList
  133. {
  134. private List<string> Columns { get; set; } = new();
  135. public IEnumerable<string> ColumnNames => Columns;
  136. public void Add(Expression<Func<T, object?>> column) => Add(CoreUtils.GetFullPropertyName(column, "."));
  137. public void Add(IColumn column) => Add(column.Property);
  138. public void Add(string column)
  139. {
  140. if (!Contains(column))
  141. Columns.Add(column);
  142. }
  143. public bool Contains(string column) => Columns.Contains(column);
  144. }
  145. public void AddHiddenColumn(string column) => HiddenColumns.Add(column);
  146. public HiddenColumnsList HiddenColumns { get; private set; }
  147. private static bool IsSequenced => typeof(T).GetInterfaces().Any(x => x.Equals(typeof(ISequenceable)));
  148. #region Options
  149. protected override void DoReconfigure(DynamicGridOptions options)
  150. {
  151. options.ReorderRows = IsSequenced;
  152. }
  153. #endregion
  154. private void EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  155. {
  156. OnAfterEditorValueChanged(null, [obj], new AfterEditorValueChangedArgs(changedColumn, changes), changes);
  157. SaveItem(obj);
  158. foreach (var (key, value) in changes)
  159. {
  160. if (row.Table.GetColumnIndex(key) > -1)
  161. row[key] = value;
  162. }
  163. GetUIComponent().UpdateRow(row);
  164. }
  165. #region Column Handling
  166. /// <summary>
  167. /// Create a set of <see cref="DynamicGridColumns"/> according to the natural default sizes and formats and captions, based on the contents of <paramref name="columns"/>.
  168. /// </summary>
  169. /// <param name="columns"></param>
  170. /// <returns></returns>
  171. protected DynamicGridColumns ExtractColumns(Columns<T> columns)
  172. {
  173. var cols = new DynamicGridColumns();
  174. foreach (var col in columns)
  175. {
  176. var mc = MasterColumns.FirstOrDefault(x => x.ColumnName.Equals(col.Property));
  177. if (mc != null && mc.Editor is not NullEditor && mc.Editor.Visible != Visible.Hidden)
  178. cols.Add(mc);
  179. }
  180. return cols;
  181. }
  182. DynamicGridColumns IDynamicGrid.ExtractColumns(IColumns columns)
  183. {
  184. var cols = new DynamicGridColumns();
  185. foreach (var col in columns)
  186. {
  187. var mc = MasterColumns.FirstOrDefault(x => x.ColumnName.Equals(col.Property));
  188. if (mc != null && mc.Editor is not NullEditor && mc.Editor.Visible != Visible.Hidden)
  189. cols.Add(mc);
  190. }
  191. return cols;
  192. }
  193. public override DynamicGridColumns GenerateColumns()
  194. {
  195. var defaultCols = DefaultColumns.GetDefaultColumns(typeof(T)).Select(x => x.Property).ToArray();
  196. Columns<T> cols;
  197. if(defaultCols.Length == 0)
  198. {
  199. cols = IsDirectEditMode()
  200. ? new Columns<T>(ColumnTypeFlags.IncludeVisible | ColumnTypeFlags.IncludeForeignKeys)
  201. : new Columns<T>(ColumnTypeFlags.IncludeVisible | ColumnTypeFlags.IncludeLinked);
  202. }
  203. else
  204. {
  205. IEnumerable<IProperty> propList;
  206. if (IsDirectEditMode())
  207. {
  208. propList = defaultCols
  209. .Where(x => x.Parent is null || !x.HasParentEntityLink() || (x.IsForeignKey() && !x.Parent.HasParentEntityLink()));
  210. }
  211. else
  212. {
  213. // Ignore foreign keys.
  214. propList = defaultCols.Where(x => !x.IsForeignKey());
  215. }
  216. cols = Columns.None<T>().AddRange(propList.Select(x => new Column<T>(x)));
  217. }
  218. var columns = ExtractColumns(cols);
  219. OnGenerateColumns?.Invoke(this, new GenerateColumnsEventArgs(columns));
  220. return columns;
  221. }
  222. public event GenerateColumnsEvent? OnGenerateColumns;
  223. public event SaveColumnsEvent? OnSaveColumns;
  224. public event GetAvailableColumnsEvent? GetAvailableColumns;
  225. protected override void SaveColumns(DynamicGridColumns columns)
  226. {
  227. OnSaveColumns?.Invoke(this, new(columns));
  228. }
  229. #endregion
  230. #region Refresh / Reload
  231. protected abstract void Reload(
  232. Filters<T> criteria, Columns<T> columns, ref SortOrder<T>? sort,
  233. CancellationToken token, Action<CoreTable?, Exception?> action);
  234. public Filter<T>? DefineFilter()
  235. {
  236. if (OnDefineFilter is null)
  237. return null;
  238. var result = OnDefineFilter.Invoke(typeof(T)) as Filter<T>;
  239. return result;
  240. }
  241. public IEnumerable<TType> ExtractValues<TType>(Expression<Func<T, TType>> column, Selection selection)
  242. {
  243. var result = selection == Selection.None
  244. ? Enumerable.Empty<TType>()
  245. : selection == Selection.Selected
  246. ? SelectedRows.Select(r => r.Get(column))
  247. : Data.ExtractValues(column);
  248. return result;
  249. }
  250. protected sealed override void ReloadData(CancellationToken token, Action<CoreTable?, Exception?> action)
  251. {
  252. _lookupcache.Clear();
  253. var criteria = new Filters<T>();
  254. var filter = DefineFilter();
  255. if (filter != null)
  256. criteria.Add(filter);
  257. var columns = DataColumns();
  258. var sort = LookupFactory.DefineSort<T>();
  259. if (sort == null && IsSequenced)
  260. sort = new SortOrder<T>("Sequence");
  261. Reload(criteria, columns, ref sort, token, action);
  262. }
  263. public Columns<T> DataColumns()
  264. {
  265. var columns = Columns.None<T>();
  266. foreach (var column in VisibleColumns)
  267. columns.Add(column.ColumnName);
  268. foreach (var column in HiddenColumns.ColumnNames)
  269. columns.Add(new Column<T>(column));
  270. if (!Options.ReadOnly)
  271. {
  272. foreach (var column in LookupFactory.RequiredColumns<T>())
  273. {
  274. columns.Add(column);
  275. }
  276. }
  277. return columns;
  278. }
  279. public void UpdateRow(CoreRow row, T obj, bool invalidateRow = true)
  280. {
  281. ObjectToRow(obj, row);
  282. if (_recordmap.TryGetValue(row, out var _value))
  283. ObjectToRow(obj, _value);
  284. if (invalidateRow)
  285. InvalidateRow(row);
  286. }
  287. public void UpdateRows(CoreRow[] rows, T[] objs, bool invalidateRows = true)
  288. {
  289. for(var i = 0; i < objs.Length; ++i)
  290. {
  291. UpdateRow(rows[i], objs[i], invalidateRow: invalidateRows);
  292. }
  293. }
  294. public void AddRow(T data)
  295. {
  296. if (MasterData is null) return;
  297. MasterData.LoadRow(data);
  298. Refresh(false, false);
  299. }
  300. #endregion
  301. #region Item Manipulation
  302. #region Load/Save/Delete
  303. public virtual T[] LoadItems(IList<CoreRow> rows)
  304. {
  305. return rows.ToArray(LoadItem);
  306. }
  307. public abstract T LoadItem(CoreRow row);
  308. public abstract void SaveItem(T item);
  309. public virtual void SaveItems(IEnumerable<T> items)
  310. {
  311. foreach (var item in items)
  312. SaveItem(item);
  313. }
  314. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  315. {
  316. return true;
  317. }
  318. public abstract void DeleteItems(params CoreRow[] rows);
  319. protected override bool CanDeleteRows(params CoreRow[] rows) => CanDeleteItems(rows);
  320. public override void DeleteRows(params CoreRow[] rows) => DeleteItems(rows);
  321. #endregion
  322. #region Edit
  323. protected override void NewRow()
  324. {
  325. CreateItems(null);
  326. }
  327. protected void CreateItems(Func<IEnumerable<T>>? create)
  328. {
  329. var newRows = new List<CoreRow>();
  330. var items = create?.Invoke() ?? CoreUtils.One(CreateItem());
  331. foreach (var item in items)
  332. {
  333. if (!AfterCreate(item))
  334. return;
  335. SaveItem(item);
  336. var datarow = Data.NewRow();
  337. ObjectToRow(item, datarow);
  338. Data.Rows.Add(datarow);
  339. newRows.Add(datarow);
  340. var masterrow = MasterData.NewRow();
  341. ObjectToRow(item, masterrow);
  342. MasterData.Rows.Add(masterrow);
  343. _recordmap[datarow] = masterrow;
  344. }
  345. InvalidateGrid();
  346. SelectedRows = newRows.ToArray();
  347. DoChanged();
  348. }
  349. public virtual DynamicEditorPages LoadEditorPages(T item)
  350. {
  351. DynamicEditorPages pages = new DynamicEditorPages();
  352. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  353. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  354. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  355. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  356. pages.RemoveAll(x => !x.Visible);
  357. foreach (var page in pages)
  358. page.Ready = false;
  359. return pages;
  360. }
  361. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  362. {
  363. buttons.Clear();
  364. buttons.Add(
  365. "",
  366. Wpf.Resources.help.AsBitmapImage(),
  367. item,
  368. (f, i) =>
  369. {
  370. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  371. { UseShellExecute = true });
  372. }
  373. );
  374. OnLoadEditorButtons?.Invoke(item, buttons);
  375. }
  376. protected virtual void BeforeLoad(IDynamicEditorForm form, T[] items)
  377. {
  378. form.BeforeLoad();
  379. }
  380. void IDynamicGrid.InitialiseEditorForm(IDynamicEditorForm editor, object[] items, Func<Type, CoreTable>? pageDataHandler, bool preloadPages)
  381. {
  382. InitialiseEditorForm(editor, items.Cast<T>().ToArray(), pageDataHandler, preloadPages);
  383. }
  384. public virtual bool EditItems(object[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  385. {
  386. var values = items.Cast<T>().ToArray();
  387. return EditItems(values, PageDataHandler, PreloadPages);
  388. }
  389. public virtual void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false)
  390. {
  391. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  392. var buttons = new DynamicEditorButtons();
  393. if (items.Length == 1)
  394. LoadEditorButtons(items.First(), buttons);
  395. editor.Setup(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, pageDataHandler, preloadPages);
  396. editor.OnCustomiseColumns = (sender, columns) =>
  397. {
  398. columns.Clear();
  399. columns.AddRange(MasterColumns);
  400. };
  401. editor.OnDefineEditor = (o, c) =>
  402. {
  403. var result = GetEditor(o, c);
  404. if (result != null)
  405. result = result.CloneEditor();
  406. return result;
  407. };
  408. editor.OnFormCustomiseEditor += DoCustomiseEditor;
  409. editor.OnDefineFilter = (type, column) => { return DefineLookupFilter(type, column, items); };
  410. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  411. editor.OnDefineLookups = editor => DefineLookups(editor, items);
  412. editor.OnEditorValueChanged += (s, n, v) => EditorValueChanged(editor, items, n, v);
  413. editor.OnAfterEditorValueChanged += (g, args) => AfterEditorValueChanged(g, items, args);
  414. editor.OnReconfigureEditors = g => DoReconfigureEditors(g, items);
  415. editor.OnCreateEditorControl += OnCreateEditorControl;
  416. editor.OnValidateData += (o, i) => ValidateData(items);
  417. editor.OnSelectPage += SelectPage;
  418. editor.OnSaveItem = (o, e) =>
  419. {
  420. try
  421. {
  422. using var Wait = new WaitCursor();
  423. DoBeforeSave(editor, items);
  424. if (items.Length == 1)
  425. editor.UnloadEditorPages(false);
  426. foreach (var item in items)
  427. SaveItem(item);
  428. if (items.Length == 1)
  429. editor.UnloadEditorPages(true);
  430. DoAfterSave(editor, items);
  431. }
  432. catch (Exception err)
  433. {
  434. MessageBox.Show(err.Message);
  435. e.Cancel = true;
  436. }
  437. };
  438. BeforeLoad(editor, items);
  439. editor.Items = items;
  440. AfterLoad(editor, items);
  441. }
  442. protected virtual void OnCreateEditorControl(string column, BaseEditor editor, IDynamicEditorControl control)
  443. {
  444. }
  445. private void DoCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  446. {
  447. CustomiseEditor(sender, (T[])items, column, editor);
  448. OnCustomiseEditor?.Invoke(sender, (T[])items, column, editor);
  449. }
  450. protected virtual void CustomiseEditor(IDynamicEditorForm form, T[] items, DynamicGridColumn column, BaseEditor editor)
  451. {
  452. CustomiseEditor(column, editor);
  453. }
  454. protected virtual void DoAfterSave(IDynamicEditorForm editor, T[] items)
  455. {
  456. OnAfterSave?.Invoke(editor, items);
  457. }
  458. protected virtual void DoBeforeSave(IDynamicEditorForm editor, T[] items)
  459. {
  460. OnBeforeSave?.Invoke(editor, items);
  461. }
  462. /// <summary>
  463. /// Edit the <paramref name="items"/> with a non-modal editor window, attaching them to the <paramref name="host"/> provided.
  464. /// </summary>
  465. /// <param name="items">List of objects to edit.</param>
  466. /// <param name="callback">A callback for when the items are finished being edited.</param>
  467. public virtual void EditItemsNonModal(ISubPanelHost host, T[] items, Action<T[], bool> callback, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  468. {
  469. if (!DynamicGridUtils.TryEdit(items, out var editLock))
  470. {
  471. if(editLock.Panel is Window window)
  472. {
  473. Task.Delay(100).ContinueWith(task =>
  474. {
  475. window.WindowState = WindowState.Normal;
  476. window.Activate();
  477. }, TaskScheduler.FromCurrentSynchronizationContext());
  478. }
  479. else
  480. {
  481. MessageWindow.ShowMessage("One or more items are already being edited in an open window. You cannot edit the same entity multiple times simultaneously.", "Simultaneous edit.");
  482. }
  483. return;
  484. }
  485. DynamicEditorForm editor;
  486. using (var cursor = new WaitCursor())
  487. {
  488. editor = new DynamicEditorForm();
  489. editor.SetValue(Panel.ZIndexProperty, 999);
  490. editor.Form.DisableOKIfUnchanged = true;
  491. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  492. OnEditorLoaded?.Invoke(editor, items);
  493. }
  494. editLock.Panel = editor;
  495. host.AddSubPanel(editor);
  496. editor.SubPanelClosed += o =>
  497. {
  498. try
  499. {
  500. DynamicGridUtils.FinishEdit(items);
  501. callback(items, editor.Result == true);
  502. }
  503. catch(Exception e)
  504. {
  505. MessageWindow.ShowError("Error occurred while closing editor.", e);
  506. }
  507. };
  508. editor.Show();
  509. }
  510. /// <summary>
  511. /// Edit the <paramref name="items"/> with a modal editor window.
  512. /// </summary>
  513. /// <param name="items">List of objects to edit.</param>
  514. /// <returns><see langword="true"/> if the items were saved.</returns>
  515. public virtual bool EditItems(T[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  516. {
  517. DynamicEditorForm editor;
  518. using (var cursor = new WaitCursor())
  519. {
  520. editor = new DynamicEditorForm()
  521. {
  522. WindowStartupLocation = WindowStartupLocation.CenterScreen
  523. };
  524. editor.SetValue(Panel.ZIndexProperty, 999);
  525. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  526. OnEditorLoaded?.Invoke(editor, items);
  527. }
  528. return editor.ShowDialog() == true;
  529. }
  530. private Dictionary<String, object?> AfterEditorValueChanged(DynamicEditorGrid grid, T[] items, AfterEditorValueChangedArgs args)
  531. {
  532. var changes = new Dictionary<string, object?>();
  533. OnAfterEditorValueChanged(grid, items, args, changes);
  534. OnAfterEditorValueChangedEvent?.Invoke(grid, args);
  535. return changes;
  536. }
  537. protected virtual void OnAfterEditorValueChanged(DynamicEditorGrid? grid, T[] items, AfterEditorValueChangedArgs args, Dictionary<String, object?> changes)
  538. {
  539. }
  540. protected virtual void DoReconfigureEditors(DynamicEditorGrid grid, T[] items)
  541. {
  542. /*if (items.First() is IDimensioned dimensioned)
  543. {
  544. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  545. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  546. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  547. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  548. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  549. }*/
  550. }
  551. private List<string>? ValidateData(T[] items)
  552. {
  553. var errors = new List<string>();
  554. DoValidate(items, errors);
  555. OnValidate?.Invoke(this, items, errors);
  556. return errors.Count != 0 ? errors : null;
  557. }
  558. protected virtual void DoValidate(T[] items, List<string> errors)
  559. {
  560. }
  561. protected virtual void AfterLoad(IDynamicEditorForm editor, T[] items)
  562. {
  563. editor.AfterLoad();
  564. }
  565. protected virtual void SelectPage(object sender, BaseObject[]? items)
  566. {
  567. }
  568. protected virtual Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, T[] items, string name, object value)
  569. {
  570. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  571. if (OnEditorValueChanged != null)
  572. {
  573. var newchanges = OnEditorValueChanged(editor, name, value);
  574. foreach (var key in newchanges.Keys)
  575. result[key] = newchanges[key];
  576. }
  577. return result;
  578. }
  579. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  580. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items, bool async = true)
  581. {
  582. if (sender.EditorDefinition is not ILookupEditor editor)
  583. return;
  584. var colname = sender.ColumnName;
  585. if (async)
  586. {
  587. Task.Run(() =>
  588. {
  589. try
  590. {
  591. var values = editor.Values(colname, items);
  592. Dispatcher.Invoke(
  593. () =>
  594. {
  595. try
  596. {
  597. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  598. sender.LoadLookups(values);
  599. }
  600. catch (Exception e2)
  601. {
  602. Logger.Send(LogType.Information, typeof(T).Name,
  603. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  604. }
  605. }
  606. );
  607. }
  608. catch (Exception e)
  609. {
  610. Logger.Send(LogType.Information, typeof(T).Name,
  611. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  612. }
  613. });
  614. }
  615. else
  616. {
  617. var values = editor.Values(colname, items);
  618. sender.LoadLookups(values);
  619. }
  620. }
  621. /// <summary>
  622. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  623. /// </summary>
  624. /// <param name="item">The object being edited.</param>
  625. /// <param name="column">The column of the editor.</param>
  626. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  627. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  628. {
  629. return column.Editor ?? DatabaseSchema.Property(item.GetType(), column.ColumnName)?.Editor;
  630. }
  631. protected IFilter? DefineLookupFilter(Type type, string column, T[] items)
  632. {
  633. return LookupFactory.DefineLookupFilter(typeof(T), type, column, items);
  634. }
  635. protected virtual void SetEditorValue(object item, string name, object value)
  636. {
  637. try
  638. {
  639. CoreUtils.SetPropertyValue(item, name, value);
  640. }
  641. catch (Exception e)
  642. {
  643. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  644. }
  645. }
  646. protected virtual object? GetEditorValue(object item, string name)
  647. {
  648. return CoreUtils.GetPropertyValue(item, name);
  649. }
  650. protected override bool CanCreateRows() => CanCreateItems();
  651. protected virtual bool CanCreateItems()
  652. {
  653. return true;
  654. }
  655. protected override bool EditRows(CoreRow[]? rows)
  656. {
  657. if(rows is null)
  658. {
  659. if (!CanCreateItems())
  660. return false;
  661. var item = CreateItem();
  662. if (!AfterCreate(item))
  663. return false;
  664. if(Options.NonModalEditorHost is not null)
  665. {
  666. EditItemsNonModal(Options.NonModalEditorHost, [item], (items, result) =>
  667. {
  668. if (result)
  669. {
  670. var row = Data.NewRow();
  671. ObjectToRow(item, row);
  672. Data.Rows.Add(row);
  673. var masterrow = MasterData.NewRow();
  674. ObjectToRow(item, masterrow);
  675. MasterData.Rows.Add(masterrow);
  676. _recordmap[row] = masterrow;
  677. InvalidateGrid();
  678. SelectedRows = [row];
  679. DoChanged();
  680. }
  681. });
  682. return false;
  683. }
  684. else
  685. {
  686. if (EditItems([item]))
  687. {
  688. //_CurrentRow = Data.Rows.Count;
  689. var row = Data.NewRow();
  690. ObjectToRow(item, row);
  691. Data.Rows.Add(row);
  692. var masterrow = MasterData.NewRow();
  693. ObjectToRow(item, masterrow);
  694. MasterData.Rows.Add(masterrow);
  695. _recordmap[row] = masterrow;
  696. InvalidateGrid();
  697. SelectedRows = [row];
  698. DoChanged();
  699. return true;
  700. }
  701. return false;
  702. }
  703. }
  704. else
  705. {
  706. var items = Array.Empty<T>();
  707. using (new WaitCursor())
  708. {
  709. Stopwatch sw = new Stopwatch();
  710. sw.Start();
  711. items = LoadItems(rows);
  712. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  713. sw.Stop();
  714. }
  715. if (items.Length != 0)
  716. {
  717. var snaps = items.ToArray(x => x.TakeSnapshot());
  718. if(Options.NonModalEditorHost is not null)
  719. {
  720. EditItemsNonModal(Options.NonModalEditorHost, items, (items, result) =>
  721. {
  722. if (result)
  723. {
  724. var sel = SelectedRows;
  725. UpdateRows(rows, items, invalidateRows: false);
  726. InvalidateGrid();
  727. SelectedRows = sel;
  728. DoChanged();
  729. }
  730. else
  731. {
  732. foreach(var snap in snaps)
  733. {
  734. snap.ResetObject();
  735. }
  736. }
  737. });
  738. return false;
  739. }
  740. else
  741. {
  742. if (EditItems(items))
  743. {
  744. var sel = SelectedRows;
  745. UpdateRows(rows, items, invalidateRows: false);
  746. InvalidateGrid();
  747. SelectedRows = sel;
  748. DoChanged();
  749. return true;
  750. }
  751. else
  752. {
  753. foreach(var snap in snaps)
  754. {
  755. snap.ResetObject();
  756. }
  757. }
  758. }
  759. return false;
  760. }
  761. return false;
  762. }
  763. }
  764. #endregion
  765. #region Duplicate
  766. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  767. {
  768. return LoadItems(rows);
  769. }
  770. bool IDuplicateDynamicGrid.DoDuplicate(CoreRow[] rows) => DoDuplicate(rows);
  771. protected virtual bool DoDuplicate(CoreRow[] rows)
  772. {
  773. if (rows.Length == 0)
  774. {
  775. MessageBox.Show("Please select at least one record to duplicate!");
  776. return false;
  777. }
  778. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  779. if (!ids.Any())
  780. {
  781. MessageBox.Show("Please select at least one record to duplicate!");
  782. return false;
  783. }*/
  784. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  785. if (duplicator is null)
  786. {
  787. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  788. return false;
  789. }
  790. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  791. return true;
  792. }
  793. #endregion
  794. public virtual T CreateItem()
  795. {
  796. var result = new T();
  797. OnCreateItem?.Invoke(this, result);
  798. return result;
  799. }
  800. public virtual bool AfterCreate(T item)
  801. {
  802. return OnAfterCreateItem?.Invoke(this, item) ?? true;
  803. }
  804. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(IDynamicEditorForm editor, TTargetType item,
  805. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  806. where TTargetType : Entity, new()
  807. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  808. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  809. {
  810. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  811. var page =
  812. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  813. if (page != null && item != null)
  814. {
  815. if (!page.Ready)
  816. page.Load(item, null);
  817. CoreTable table;
  818. if (sourceid == Guid.Empty)
  819. {
  820. table = new CoreTable();
  821. table.LoadColumns(typeof(TSourceForm));
  822. }
  823. else
  824. {
  825. table = new Client<TSourceForm>().Query(
  826. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  827. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  828. );
  829. }
  830. var newforms = new List<TTargetForm>();
  831. foreach (var row in table.Rows)
  832. {
  833. var sourceform = row.ToObject<TSourceForm>();
  834. var targetform = new TTargetForm();
  835. targetform.Form.ID = sourceform.Form.ID;
  836. targetform.Form.Synchronise(sourceform.Form);
  837. newforms.Add(targetform);
  838. }
  839. page.Items.Clear();
  840. page.LoadItems(newforms.ToArray());
  841. }
  842. }
  843. #region ClipBuffer
  844. protected virtual bool BeforeCopy(IList<T> items)
  845. {
  846. return true;
  847. }
  848. protected override void MoveRows(CoreRow[] rows, int index, bool isCopy = false)
  849. {
  850. if (!Options.ReorderRows || !IsSequenced) return;
  851. var items = LoadItems(rows);
  852. if (isCopy)
  853. {
  854. if (!BeforeCopy(items))
  855. {
  856. return;
  857. }
  858. }
  859. var sequence = index < Data.Rows.Count
  860. ? Data.Rows[index].Get<ISequenceable, long>(x => x.Sequence)
  861. : Data.Rows[^1].Get<ISequenceable, long>(x => x.Sequence) + 1;
  862. var postRows = Data.Rows.Where(r => !rows.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  863. var updates = items.Concatenate(LoadItems(postRows.ToArray()));
  864. foreach (var update in updates)
  865. {
  866. ((ISequenceable)update).Sequence = sequence;
  867. sequence++;
  868. }
  869. if (updates.Length != 0)
  870. {
  871. SaveItems(updates);
  872. DoChanged();
  873. Refresh(false, true);
  874. }
  875. }
  876. #endregion
  877. protected virtual void ObjectToRow(T obj, CoreRow row)
  878. {
  879. row.Table.FillRow(row, obj);
  880. }
  881. #region Import / Export
  882. protected virtual CoreTable LoadImportKeys(String[] fields)
  883. {
  884. var result = new CoreTable();
  885. result.LoadColumns(Columns.None<T>().Add(fields));
  886. return result;
  887. }
  888. protected virtual Guid GetImportID()
  889. {
  890. return Guid.Empty;
  891. }
  892. protected virtual bool CustomiseImportItem(T item)
  893. {
  894. if (IsSequenced)
  895. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  896. return true;
  897. }
  898. protected virtual string CustomiseImportFileName(string filename)
  899. {
  900. return filename;
  901. }
  902. void IImportDynamicGrid.DoImport() => DoImport();
  903. protected virtual void DoImport()
  904. {
  905. var list = new DynamicImportList(
  906. typeof(T),
  907. GetImportID()
  908. );
  909. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  910. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  911. list.OnSave += (sender, entity) => SaveItem(entity as T);
  912. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  913. list.ShowDialog();
  914. Refresh(false, true);
  915. }
  916. protected virtual void CustomiseExportColumns(List<string> columnnames)
  917. {
  918. }
  919. protected virtual string CustomiseExportFileName(string filename)
  920. {
  921. return filename;
  922. }
  923. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  924. {
  925. }
  926. protected virtual void ApplyExportFilter(CoreTable table, object data)
  927. {
  928. }
  929. void IExportDynamicGrid.DoExport() => DoExport();
  930. protected virtual void DoExport()
  931. {
  932. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  933. CustomiseExportColumns(columnnames);
  934. var form = new DynamicExportForm(typeof(T), columnnames);
  935. if (form.ShowDialog() != true)
  936. return;
  937. var filters = new Filters<T>();
  938. filters.Add(DefineFilter());
  939. var predicates = GetUIComponent().GetFilterPredicates();
  940. var visiblerows = GetVisibleRows();
  941. CustomiseExportFilters(filters, visiblerows);
  942. var columns = Columns.None<T>().Add(form.Fields);
  943. var otherColumns = form.GetChildFields()
  944. .Select(x => new Tuple<Type, IColumns>(
  945. x.Key,
  946. Columns.None(x.Key).Add(x.Value)))
  947. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  948. var reloadColumns = Columns.None<T>();
  949. foreach (var column in columns)
  950. {
  951. reloadColumns.Add(column);
  952. }
  953. foreach (var column in HiddenColumns.ColumnNames)
  954. {
  955. reloadColumns.Add(column);
  956. }
  957. foreach (var column in LookupFactory.RequiredColumns<T>())
  958. {
  959. columns.Add(column);
  960. }
  961. foreach (var (column, _) in predicates)
  962. {
  963. reloadColumns.Add(column);
  964. }
  965. CoreTable? data = null;
  966. void LoadExport()
  967. {
  968. var newData = new CoreTable();
  969. newData.LoadColumns(columns);
  970. FilterRows(data.Rows, newData, filter: row =>
  971. {
  972. foreach(var (_, predicate) in predicates)
  973. {
  974. if (!predicate(row))
  975. {
  976. return false;
  977. }
  978. }
  979. return true;
  980. });
  981. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  982. list.AddRange(LoadExportTables(filters, otherColumns));
  983. DoExportTables(list);
  984. }
  985. var sort = LookupFactory.DefineSort<T>();
  986. Reload(filters, reloadColumns, ref sort, CancellationToken.None, (table, err) =>
  987. {
  988. if (table is not null)
  989. {
  990. if (table.Offset == 0 || data is null)
  991. {
  992. data = table;
  993. if (!IsPaging)
  994. {
  995. Dispatcher.Invoke(LoadExport);
  996. }
  997. }
  998. else
  999. {
  1000. data.AddPage(table);
  1001. if (!IsPaging)
  1002. {
  1003. Dispatcher.Invoke(LoadExport);
  1004. }
  1005. }
  1006. }
  1007. else if (err is not null)
  1008. {
  1009. Dispatcher.Invoke(() =>
  1010. {
  1011. MessageWindow.ShowError("Error in export.", err);
  1012. });
  1013. }
  1014. });
  1015. }
  1016. /// <summary>
  1017. /// Loads the child tables for an export, based on the filter of the parent table.
  1018. /// </summary>
  1019. /// <remarks>
  1020. /// If not overriden, defaults to creating empty tables with no records.
  1021. /// </remarks>
  1022. /// <param name="filter">Filter for the parent table.</param>
  1023. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  1024. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  1025. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  1026. {
  1027. return tableColumns.Select(x =>
  1028. {
  1029. var table = new CoreTable();
  1030. table.LoadColumns(x.Item2);
  1031. return new Tuple<Type?, CoreTable>(x.Item1, table);
  1032. });
  1033. }
  1034. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  1035. {
  1036. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  1037. ExcelExporter.DoExport(data, filename);
  1038. }
  1039. #endregion
  1040. #endregion
  1041. #region Header Actions
  1042. protected override bool SelectColumns([NotNullWhen(true)] out DynamicGridColumns? columns)
  1043. {
  1044. var schema = new DynamicGridObjectColumnSchema(typeof(T));
  1045. var editor = new DynamicGridColumnsEditor(schema, typeof(T)) { WindowStartupLocation = WindowStartupLocation.CenterScreen };
  1046. editor.DirectEdit = IsDirectEditMode();
  1047. editor.Columns.AddRange(VisibleColumns);
  1048. schema.OnProcessColumns += args =>
  1049. {
  1050. GetAvailableColumns?.Invoke(args);
  1051. };
  1052. if (editor.ShowDialog().Equals(true))
  1053. {
  1054. columns = editor.Columns;
  1055. return true;
  1056. }
  1057. else
  1058. {
  1059. columns = null;
  1060. return false;
  1061. }
  1062. }
  1063. #endregion
  1064. #region Drag + Drop
  1065. protected DragDropEffects DragTable(Type entity, CoreTable table)
  1066. {
  1067. Logger.Send(LogType.Information, "", "DragTable");
  1068. var data = new DataObject();
  1069. data.SetData(DynamicGridUtils.DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  1070. var effect = DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  1071. return effect;
  1072. }
  1073. protected override DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1074. {
  1075. Logger.Send(LogType.Information, "", "OnRowsDragStart");
  1076. var table = new CoreTable();
  1077. table.LoadColumns(Data.Columns);
  1078. table.LoadRows(rows);
  1079. return DragTable(typeof(T), table);
  1080. }
  1081. #endregion
  1082. }
  1083. #region Styling
  1084. public class DynamicGridRowStyle : DynamicGridStyle<VirtualizingCellsControl>
  1085. {
  1086. public DynamicGridRowStyle() : base(null)
  1087. {
  1088. }
  1089. public DynamicGridRowStyle(IDynamicGridStyle source) : base(source)
  1090. {
  1091. }
  1092. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1093. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1094. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1095. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1096. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1097. }
  1098. public class DynamicGridCellStyle : DynamicGridStyle<Control>
  1099. {
  1100. public DynamicGridCellStyle() : base(null)
  1101. {
  1102. }
  1103. public DynamicGridCellStyle(IDynamicGridStyle source) : base(source)
  1104. {
  1105. }
  1106. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1107. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1108. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1109. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1110. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1111. }
  1112. // Used to render boolean columns (the default "false" value shows what appears to be an intermediate state, which is ugly
  1113. // This should show nothing for false, and a tick in a box for true
  1114. public class BoolToImageConverter : AbstractConverter<bool, ImageSource?>
  1115. {
  1116. public ImageSource TrueValue { get; set; }
  1117. public ImageSource? FalseValue { get; set; }
  1118. public BoolToImageConverter()
  1119. {
  1120. TrueValue = Wpf.Resources.Bullet_Tick.AsBitmapImage();
  1121. }
  1122. public override ImageSource? Convert(bool value)
  1123. {
  1124. return value ? TrueValue : FalseValue;
  1125. }
  1126. public override bool Deconvert(ImageSource? value)
  1127. {
  1128. return ImageUtils.IsEqual(value as BitmapImage, TrueValue as BitmapImage);
  1129. }
  1130. }
  1131. public class StringToColorImageConverter : IValueConverter
  1132. {
  1133. private readonly int _height = 50;
  1134. private readonly int _width = 25;
  1135. private readonly Dictionary<string, BitmapImage> cache = new();
  1136. public StringToColorImageConverter(int width, int height)
  1137. {
  1138. _width = width;
  1139. _height = height;
  1140. }
  1141. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1142. {
  1143. var str = value?.ToString();
  1144. if (str is null)
  1145. return null;
  1146. var colorcode = str.TrimStart('#');
  1147. if (!cache.ContainsKey(colorcode))
  1148. {
  1149. var col = ImageUtils.StringToColor(colorcode);
  1150. var bmp = ImageUtils.BitmapFromColor(col, _width, _height, Color.Black);
  1151. cache[colorcode] = bmp.AsBitmapImage();
  1152. }
  1153. var result = cache[colorcode];
  1154. return result;
  1155. }
  1156. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1157. {
  1158. return null;
  1159. }
  1160. }
  1161. public class StringArrayConverter : IValueConverter
  1162. {
  1163. object? IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1164. {
  1165. if (value is string[] strArray)
  1166. {
  1167. return string.Join("\n", strArray);
  1168. }
  1169. Logger.Send(LogType.Error, "", $"Attempt to convert an object which is not a string array: {value}.");
  1170. return null;
  1171. }
  1172. object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1173. {
  1174. return value;
  1175. }
  1176. }
  1177. #endregion
  1178. [Serializable]
  1179. class DynamicGridDragFormat
  1180. {
  1181. private string entity;
  1182. public DataTable Table { get; set; }
  1183. public Type Entity
  1184. {
  1185. get => CoreUtils.GetEntity(entity);
  1186. [MemberNotNull(nameof(entity))]
  1187. set => entity = value.EntityName();
  1188. }
  1189. public DynamicGridDragFormat(DataTable table, Type entity)
  1190. {
  1191. Table = table;
  1192. Entity = entity;
  1193. }
  1194. }