DynamicGrid.cs 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548
  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.Threading.Tasks;
  10. using System.Windows;
  11. using System.Windows.Controls;
  12. using System.Windows.Data;
  13. using System.Windows.Input;
  14. using System.Windows.Media;
  15. using System.Windows.Media.Animation;
  16. using System.Windows.Media.Imaging;
  17. using InABox.Clients;
  18. using InABox.Core;
  19. using InABox.Wpf;
  20. using InABox.WPF;
  21. using Syncfusion.Data;
  22. using Syncfusion.UI.Xaml.Grid;
  23. using Syncfusion.UI.Xaml.Grid.Helpers;
  24. using static InABox.DynamicGrid.IDynamicGrid;
  25. using Color = System.Drawing.Color;
  26. using Columns = InABox.Core.Columns;
  27. using Image = System.Windows.Controls.Image;
  28. using RowColumnIndex = Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex;
  29. using SolidColorBrush = System.Windows.Media.SolidColorBrush;
  30. using String = System.String;
  31. using VerticalAlignment = System.Windows.VerticalAlignment;
  32. using VirtualizingCellsControl = Syncfusion.UI.Xaml.Grid.VirtualizingCellsControl;
  33. using System.Threading;
  34. namespace InABox.DynamicGrid;
  35. public abstract class DynamicGrid : ContentControl
  36. {
  37. public static readonly DependencyProperty UseWaitCursorProperty =
  38. DependencyProperty.Register(nameof(UseWaitCursor), typeof(bool), typeof(DynamicGrid<>));
  39. public bool UseWaitCursor
  40. {
  41. get => (bool)GetValue(UseWaitCursorProperty);
  42. set => SetValue(UseWaitCursorProperty, value);
  43. }
  44. }
  45. public abstract class DynamicGrid<T> : DynamicGrid, IDynamicGridUIComponentParent<T>, IDynamicGrid<T>
  46. where T : BaseObject, new()
  47. {
  48. protected enum ClipAction
  49. {
  50. Cut,
  51. Copy
  52. }
  53. private IDynamicGridUIComponent<T> UIComponent { get; set; }
  54. private UIElement? _header;
  55. private readonly Button Add;
  56. public bool bRefreshing;
  57. bool IDynamicGridUIComponentParent<T>.IsRefreshing => bRefreshing;
  58. private readonly Label ClipboardSpacer;
  59. private readonly Button Copy;
  60. private readonly Label Count;
  61. private readonly Button Cut;
  62. private readonly Border Disabler;
  63. private readonly Button Delete;
  64. private readonly DockPanel Docker;
  65. private readonly DynamicRowMovementColumn? down;
  66. private readonly Button Edit;
  67. private readonly Label EditSpacer;
  68. private readonly Button Export;
  69. private readonly Label ExportSpacer;
  70. private readonly Button DuplicateBtn;
  71. private readonly Button SwitchViewBtn;
  72. private readonly Button Help;
  73. private readonly Button Import;
  74. private readonly Grid Layout;
  75. private readonly Label Loading;
  76. private DoubleAnimation LoadingFader = new DoubleAnimation(1d, 0.2d, new Duration(TimeSpan.FromSeconds(2))) { AutoReverse = true };
  77. //private readonly Button MultiEdit;
  78. private readonly Button Paste;
  79. private readonly Button Print;
  80. private readonly Label PrintSpacer;
  81. private readonly StackPanel LeftButtonStack;
  82. private readonly StackPanel RightButtonStack;
  83. private readonly DynamicRowMovementColumn? up;
  84. protected DynamicGridRowStyleSelector<T> RowStyleSelector;
  85. #region Events
  86. public event IDynamicGrid.ReconfigureEvent? OnReconfigure;
  87. public OnGetDynamicGridRowStyle? OnGetRowStyle { get; set; }
  88. public ValidateEvent<T>? OnValidate { get; set; }
  89. public event OnPrintData? OnPrintData;
  90. public event BeforeRefreshEventHandler? BeforeRefresh;
  91. public event AfterRefreshEventHandler? AfterRefresh;
  92. public event OnDefineFilter? OnDefineFilter;
  93. public event OnCreateItem? OnCreateItem;
  94. public event OnAfterCreateItem? OnAfterCreateItem;
  95. /// <summary>
  96. /// Called when an item is selected in the grid. It is not called if <see cref="IsReady"/> is not <see langword="true"/>.
  97. /// </summary>
  98. /// <remarks>
  99. /// It is unnecessary to use this if within a grid. Instead, override <see cref="SelectItems(CoreRow[]?)"/>.
  100. /// </remarks>
  101. public event SelectItemHandler? OnSelectItem;
  102. public event OnCellDoubleClick? OnCellDoubleClick;
  103. public event EventHandler? OnChanged;
  104. public delegate void BeforeSelectionEvent(CancelEventArgs cancel);
  105. public event BeforeSelectionEvent? OnBeforeSelection;
  106. protected virtual void Changed()
  107. {
  108. }
  109. public virtual void DoChanged()
  110. {
  111. Changed();
  112. OnChanged?.Invoke(this, EventArgs.Empty);
  113. }
  114. public event EditorValueChangedHandler? OnEditorValueChanged;
  115. public event OnCustomiseEditor<T>? OnCustomiseEditor;
  116. public event OnFilterRecord? OnFilterRecord;
  117. public event OnDoubleClick? OnDoubleClick;
  118. public event EntitySaveEvent? OnBeforeSave;
  119. public event EntitySaveEvent? OnAfterSave;
  120. public delegate void EditorLoaded(IDynamicEditorForm editor, T[] items);
  121. public event EditorLoaded OnEditorLoaded;
  122. public event OnLoadEditorButtons<T> OnLoadEditorButtons;
  123. #endregion
  124. protected DynamicGridSettings Settings { get; set; }
  125. public DynamicGrid() : base()
  126. {
  127. UseWaitCursor = true;
  128. Options = new DynamicGridOptions();
  129. Options.OnChanged += () =>
  130. {
  131. _hasLoadedOptions = true;
  132. OptionsChanged();
  133. };
  134. ActionColumns = new DynamicActionColumns();
  135. ColumnGroupings = new DynamicGridColumnGroupings();
  136. RowStyleSelector = GetRowStyleSelector();
  137. RowStyleSelector.GetStyle += (row, style) => GetRowStyle(row, style);
  138. IsReady = false;
  139. Data = new CoreTable();
  140. MasterColumns = new DynamicGridColumns();
  141. MasterColumns.ExtractColumns(typeof(T));
  142. HiddenColumns = new HiddenColumnsList();
  143. foreach (var column in LookupFactory.RequiredColumns<T>().ColumnNames())
  144. {
  145. AddHiddenColumn(column);
  146. }
  147. if (ShowSequenceButtons)
  148. {
  149. up = new DynamicRowMovementColumn(DynamicRowMovement.Up, SwapRows);
  150. ActionColumns.Add(up);
  151. down = new DynamicRowMovementColumn(DynamicRowMovement.Down, SwapRows);
  152. ActionColumns.Add(down);
  153. HiddenColumns.Add(x => (x as ISequenceable)!.Sequence);
  154. }
  155. VisibleColumns = new DynamicGridColumns();
  156. UIComponent = CreateUIComponent();
  157. Loading = new Label();
  158. Loading.Content = "Loading...";
  159. Loading.Foreground = new SolidColorBrush(Colors.White);
  160. Loading.VerticalContentAlignment = VerticalAlignment.Center;
  161. Loading.HorizontalContentAlignment = HorizontalAlignment.Center;
  162. Loading.Visibility = Visibility.Collapsed;
  163. Loading.SetValue(Panel.ZIndexProperty, 999);
  164. Loading.SetValue(Grid.RowProperty, 1);
  165. Loading.FontSize = 14.0F;
  166. LoadingFader.Completed += (sender, args) =>
  167. {
  168. if (Loading.Visibility == Visibility.Visible)
  169. {
  170. //Logger.Send(LogType.Information, this.GetType().EntityName().Split(".").Last(), "Loading Fader Restarting");
  171. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  172. }
  173. };
  174. Help = CreateButton(Wpf.Resources.help.AsBitmapImage(Color.White));
  175. Help.Margin = new Thickness(0, 2, 2, 0);
  176. Help.SetValue(DockPanel.DockProperty, Dock.Right);
  177. Help.Click += (o, e) => ShowHelp(typeof(T).Name.Split('.').Last().SplitCamelCase().Replace(" ", "_"));
  178. Add = CreateButton(Wpf.Resources.add.AsBitmapImage(Color.White));
  179. Add.Margin = new Thickness(0, 2, 2, 0);
  180. Add.Click += Add_Click;
  181. Edit = CreateButton(Wpf.Resources.pencil.AsBitmapImage(Color.White));
  182. Edit.Margin = new Thickness(0, 2, 2, 0);
  183. Edit.Click += Edit_Click;
  184. SwitchViewBtn = CreateButton(Wpf.Resources.alter.AsBitmapImage());
  185. SwitchViewBtn.Margin = new Thickness(0, 2, 2, 0);
  186. SwitchViewBtn.Click += SwitchView_Click;
  187. EditSpacer = new Label { Width = 5 };
  188. Print = CreateButton(Wpf.Resources.print.AsBitmapImage(Color.White));
  189. Print.Margin = new Thickness(0, 2, 2, 0);
  190. Print.Click += (o, e) => DoPrint(o);
  191. PrintSpacer = new Label { Width = 5 };
  192. Cut = CreateButton(Wpf.Resources.cut.AsBitmapImage(Color.White));
  193. Cut.Margin = new Thickness(0, 2, 2, 0);
  194. Cut.Click += Cut_Click;
  195. Copy = CreateButton(Wpf.Resources.copy.AsBitmapImage(Color.White));
  196. Copy.Margin = new Thickness(0, 2, 2, 0);
  197. Copy.Click += Copy_Click;
  198. Paste = CreateButton(Wpf.Resources.paste.AsBitmapImage(Color.White));
  199. Paste.Margin = new Thickness(0, 2, 2, 0);
  200. Paste.Click += Paste_Click;
  201. ClipboardSpacer = new Label { Width = 5 };
  202. Export = CreateButton(Wpf.Resources.doc_xls.AsBitmapImage(Color.White), "Export");
  203. Export.Margin = new Thickness(0, 2, 2, 0);
  204. Export.Click += Export_Click;
  205. Import = CreateButton(Wpf.Resources.doc_xls.AsBitmapImage(Color.White), "Import");
  206. Import.Margin = new Thickness(0, 2, 2, 0);
  207. Import.Click += Import_Click;
  208. ExportSpacer = new Label { Width = 5 };
  209. LeftButtonStack = new StackPanel();
  210. LeftButtonStack.Orientation = Orientation.Horizontal;
  211. LeftButtonStack.SetValue(DockPanel.DockProperty, Dock.Left);
  212. LeftButtonStack.Children.Add(Help);
  213. LeftButtonStack.Children.Add(Add);
  214. LeftButtonStack.Children.Add(Edit);
  215. LeftButtonStack.Children.Add(SwitchViewBtn);
  216. //Stack.Children.Add(MultiEdit);
  217. LeftButtonStack.Children.Add(EditSpacer);
  218. LeftButtonStack.Children.Add(Print);
  219. LeftButtonStack.Children.Add(PrintSpacer);
  220. LeftButtonStack.Children.Add(Cut);
  221. LeftButtonStack.Children.Add(Copy);
  222. LeftButtonStack.Children.Add(Paste);
  223. LeftButtonStack.Children.Add(ClipboardSpacer);
  224. LeftButtonStack.Children.Add(Export);
  225. LeftButtonStack.Children.Add(Import);
  226. LeftButtonStack.Children.Add(ExportSpacer);
  227. RightButtonStack = new StackPanel();
  228. RightButtonStack.Orientation = Orientation.Horizontal;
  229. RightButtonStack.SetValue(DockPanel.DockProperty, Dock.Right);
  230. Delete = CreateButton(Wpf.Resources.delete.AsBitmapImage(Color.White));
  231. Delete.Margin = new Thickness(2, 2, 0, 0);
  232. Delete.SetValue(DockPanel.DockProperty, Dock.Right);
  233. Delete.Click += Delete_Click;
  234. DuplicateBtn = AddButton("Duplicate", Wpf.Resources.paste.AsBitmapImage(Color.White), DoDuplicate);
  235. Count = new Label();
  236. Count.Height = 30;
  237. Count.Margin = new Thickness(0, 2, 0, 0);
  238. Count.VerticalContentAlignment = VerticalAlignment.Center;
  239. Count.HorizontalContentAlignment = HorizontalAlignment.Center;
  240. Count.SetValue(DockPanel.DockProperty, Dock.Left);
  241. Docker = new DockPanel();
  242. Docker.SetValue(Grid.RowProperty, 2);
  243. Docker.SetValue(Grid.ColumnProperty, 0);
  244. Docker.Children.Add(LeftButtonStack);
  245. Docker.Children.Add(Delete);
  246. Docker.Children.Add(RightButtonStack);
  247. Docker.Children.Add(Count);
  248. Layout = new Grid();
  249. Layout.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
  250. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  251. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
  252. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  253. var control = UIComponent.Control;
  254. control.SetValue(Grid.RowProperty, 1);
  255. Layout.Children.Add(control);
  256. Layout.Children.Add(Loading);
  257. Layout.Children.Add(Docker);
  258. Disabler = new Border()
  259. {
  260. BorderBrush = new SolidColorBrush(Colors.Transparent),
  261. Background = new SolidColorBrush(Colors.DimGray) { Opacity = 0.2 },
  262. Visibility = Visibility.Collapsed,
  263. };
  264. Disabler.SetValue(Canvas.ZIndexProperty, 99);
  265. Disabler.SetValue(Grid.RowSpanProperty, 3);
  266. Layout.Children.Add(Disabler);
  267. //Scroll.ApplyTemplate();
  268. Content = Layout;
  269. IsEnabledChanged += (sender, args) =>
  270. {
  271. Disabler.Visibility = Equals(args.NewValue, true)
  272. ? Visibility.Collapsed
  273. : Visibility.Visible;
  274. };
  275. Settings = LoadSettings();
  276. Init();
  277. Reconfigure();
  278. }
  279. #region IDynamicGridUIComponentParent
  280. protected virtual IDynamicGridUIComponent<T> CreateUIComponent()
  281. {
  282. return new DynamicGridGridUIComponent<T>()
  283. {
  284. Parent = this
  285. };
  286. }
  287. bool IDynamicGridUIComponentParent<T>.CanSort()
  288. {
  289. return !ShowSequenceButtons || !Options.EditRows;
  290. }
  291. T IDynamicGrid<T>.LoadItem(CoreRow row) => LoadItem(row);
  292. DynamicGridRowStyleSelector<T> IDynamicGridUIComponentParent<T>.RowStyleSelector => RowStyleSelector;
  293. void IDynamicGridUIComponentParent<T>.BeforeSelection(CancelEventArgs cancel)
  294. {
  295. BeforeSelection(cancel);
  296. }
  297. void IDynamicGridUIComponentParent<T>.SelectItems(CoreRow[] rows)
  298. {
  299. SelectItems(rows);
  300. }
  301. void IDynamicGridUIComponentParent<T>.EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  302. => EntityChanged(obj, row, changedColumn, changes);
  303. void IDynamicGridUIComponentParent<T>.UpdateData(T obj, CoreRow row, string changedColumn, Dictionary<CoreColumn, object?> updates)
  304. {
  305. var result = new Dictionary<string, object?>();
  306. foreach (var (col, value) in updates)
  307. {
  308. UpdateRow(row, col.ColumnName, value, refresh: false);
  309. DynamicGridUtils.UpdateEditorValue(new BaseObject[] { obj }, col.ColumnName, value, result);
  310. }
  311. EntityChanged(obj, row, changedColumn, result);
  312. }
  313. void IDynamicGridUIComponentParent<T>.HandleKey(KeyEventArgs e)
  314. {
  315. if (ShowSequenceButtons)
  316. {
  317. if (e.Key == Key.X && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  318. {
  319. CutToClipBuffer();
  320. }
  321. else if (e.Key == Key.C && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  322. {
  323. CopyToClipBuffer();
  324. }
  325. else if (e.Key == Key.V && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  326. {
  327. PasteFromClipBuffer();
  328. }
  329. else if (e.Key == Key.Escape)
  330. {
  331. ResetClipBuffer();
  332. InvalidateGrid();
  333. }
  334. }
  335. }
  336. void IDynamicGridUIComponentParent<T>.DoubleClickCell(CoreRow? row, DynamicColumnBase? column)
  337. {
  338. var args = new DynamicGridCellClickEventArgs(row, column);
  339. if (OnCellDoubleClick is not null)
  340. {
  341. OnCellDoubleClick?.Invoke(this, args);
  342. if (args.Handled)
  343. return;
  344. }
  345. if (row is not null)
  346. DoDoubleClick(this, args);
  347. }
  348. void IDynamicGridUIComponentParent<T>.ExecuteActionColumn(DynamicActionColumn column, CoreRow[]? rows)
  349. {
  350. var bRefresh = false;
  351. if(rows is null)
  352. {
  353. bRefresh = column.Action?.Invoke(null) ?? false;
  354. }
  355. else
  356. {
  357. foreach (var row in rows)
  358. if (column.Action?.Invoke(row) == true)
  359. bRefresh = true;
  360. }
  361. if (bRefresh)
  362. Dispatcher.BeginInvoke(() => { Refresh(true, true); });
  363. }
  364. void IDynamicGridUIComponentParent<T>.OpenColumnMenu(DynamicColumnBase column)
  365. {
  366. if(column is DynamicMenuColumn menuColumn)
  367. {
  368. menuColumn.Action?.Invoke(SelectedRows.FirstOrDefault());
  369. }
  370. else if(column is DynamicActionColumn actionColumn)
  371. {
  372. var menu = actionColumn?.ContextMenu?.Invoke(SelectedRows);
  373. if (menu != null && menu.Items.Count > 0)
  374. {
  375. menu.IsOpen = true;
  376. }
  377. }
  378. }
  379. void IDynamicGridUIComponentParent<T>.UpdateRecordCount(int count)
  380. {
  381. Count.Content = FormatRecordCount(count);
  382. }
  383. protected virtual string FormatRecordCount(int count) => $"{count} Records";
  384. void IDynamicGridUIComponentParent<T>.LoadColumnsMenu(ContextMenu menu)
  385. {
  386. menu.AddItem("Select Columns", null, SelectColumnsClick);
  387. LoadColumnsMenu(menu);
  388. }
  389. void IDynamicGridUIComponentParent<T>.DragOver(object sender, DragEventArgs e)
  390. {
  391. HandleDragOver(sender, e);
  392. }
  393. void IDynamicGridUIComponentParent<T>.Drop(object sender, DragEventArgs e)
  394. {
  395. if (!Options.DragTarget)
  396. return;
  397. if(DynamicGridUtils.TryGetDropData(e, out var entityType, out var table))
  398. {
  399. OnDragEnd(entityType, table, e);
  400. }
  401. else
  402. {
  403. HandleDragDrop(sender, e);
  404. }
  405. }
  406. void IDynamicGridUIComponentParent<T>.DragStart(object? sender, CoreRow[] rows)
  407. {
  408. Logger.Send(LogType.Information, "", "RowDragDropController_DragStart");
  409. if (!Options.DragSource)
  410. return;
  411. OnRowsDragStart(rows);
  412. }
  413. void IDynamicGridUIComponentParent<T>.UIFilterChanged(object sender) => DoFilterChanged();
  414. protected virtual void DoFilterChanged()
  415. {
  416. }
  417. IEnumerable<string>? IDynamicGridUIComponentParent<T>.GetColumnFilterItems(DynamicColumnBase column) => GetColumnFilterItems(column);
  418. protected virtual IEnumerable<string>? GetColumnFilterItems(DynamicColumnBase column)
  419. {
  420. return null;
  421. }
  422. #endregion
  423. protected virtual DynamicGridRowStyleSelector<T> GetRowStyleSelector()
  424. {
  425. return new DynamicGridRowStyleSelector<T, DynamicGridRowStyle>();
  426. }
  427. protected virtual DynamicGridStyle GetRowStyle(CoreRow row, DynamicGridStyle style)
  428. {
  429. DynamicGridStyle? result = null;
  430. if (ClipBuffer != null)
  431. if (ClipBuffer.Item2.Contains(row))
  432. {
  433. var bgbrush = style.Background as SolidColorBrush;
  434. var bgcolor = bgbrush != null ? bgbrush.Color : Colors.Transparent;
  435. result = new DynamicGridRowStyle(style);
  436. result.Background = ClipBuffer.Item1 == ClipAction.Cut
  437. ? new SolidColorBrush(bgcolor.MixColors(0.5, Colors.Orchid))
  438. : new SolidColorBrush(bgcolor.MixColors(0.5, Colors.LightGreen));
  439. result.Foreground = new SolidColorBrush(Colors.Gray);
  440. result.FontStyle = FontStyles.Italic;
  441. }
  442. result ??= OnGetRowStyle != null ? OnGetRowStyle(row, style) : style;
  443. return result;
  444. }
  445. protected virtual void BeforeSelection(CancelEventArgs cancel)
  446. {
  447. OnBeforeSelection?.Invoke(cancel);
  448. }
  449. public bool IsReady { get; protected set; }
  450. public UIElement? Header
  451. {
  452. get => _header;
  453. set
  454. {
  455. if (_header is not null && Layout.Children.Contains(_header))
  456. Layout.Children.Remove(_header);
  457. _header = value;
  458. if (_header is not null)
  459. {
  460. _header.SetValue(Grid.RowProperty, 0);
  461. _header.SetValue(Grid.ColumnProperty, 0);
  462. _header.SetValue(Grid.ColumnSpanProperty, 2);
  463. Layout.Children.Add(_header);
  464. }
  465. }
  466. }
  467. /// <summary>
  468. /// Represents the data in the grid. This is <see langword="null"/> until <see cref="Refresh(bool, bool)"/> is called.
  469. /// </summary>
  470. public CoreTable? MasterData { get; set; }
  471. public DynamicGridColumns MasterColumns { get; protected set; }
  472. public DynamicGridColumns VisibleColumns { get; protected set; }
  473. public DynamicActionColumns ActionColumns { get; protected set; }
  474. public CoreTable Data { get; set; }
  475. public class HiddenColumnsList
  476. {
  477. private List<string> Columns { get; set; } = new();
  478. public IEnumerable<string> ColumnNames => Columns;
  479. public void Add(Expression<Func<T, object?>> column) => Add(CoreUtils.GetFullPropertyName(column, "."));
  480. public void Add(IColumn column) => Add(column.Property);
  481. public void Add(string column)
  482. {
  483. if (!Contains(column))
  484. Columns.Add(column);
  485. }
  486. public bool Contains(string column) => Columns.Contains(column);
  487. }
  488. public void AddHiddenColumn(string column) => HiddenColumns.Add(column);
  489. public HiddenColumnsList HiddenColumns { get; }
  490. private static bool IsSequenced => typeof(T).GetInterfaces().Any(x => x.Equals(typeof(ISequenceable)));
  491. protected virtual bool ShowSequenceButtons => IsSequenced;
  492. public double RowHeight
  493. {
  494. get => UIComponent.RowHeight;
  495. set => UIComponent.RowHeight = value;
  496. }
  497. public double HeaderHeight
  498. {
  499. get => UIComponent.HeaderRowHeight;
  500. set => UIComponent.HeaderRowHeight = value;
  501. }
  502. #region Options
  503. /// <summary>
  504. /// Initialise things like custom buttons; called once during construction.
  505. /// </summary>
  506. protected abstract void Init();
  507. protected abstract void DoReconfigure(DynamicGridOptions options);
  508. private bool _hasLoadedOptions = false;
  509. protected virtual void OptionsChanged()
  510. {
  511. var reloadColumns = false;
  512. Help.Visibility = Options.ShowHelp ? Visibility.Visible : Visibility.Collapsed;
  513. Add.Visibility = Options.AddRows ? Visibility.Visible : Visibility.Collapsed;
  514. Edit.Visibility = Options.EditRows ? Visibility.Visible : Visibility.Collapsed;
  515. EditSpacer.Visibility = Options.AddRows || Options.EditRows
  516. ? Visibility.Visible
  517. : Visibility.Collapsed;
  518. Print.Visibility = Options.Print ? Visibility.Visible : Visibility.Collapsed;
  519. PrintSpacer.Visibility = Options.Print ? Visibility.Visible : Visibility.Collapsed;
  520. Cut.Visibility = ShowSequenceButtons && Options.EditRows ? Visibility.Visible : Visibility.Collapsed;
  521. Copy.Visibility = ShowSequenceButtons && Options.EditRows ? Visibility.Visible : Visibility.Collapsed;
  522. Paste.Visibility = ShowSequenceButtons && Options.EditRows ? Visibility.Visible : Visibility.Collapsed;
  523. ClipboardSpacer.Visibility = ShowSequenceButtons && Options.EditRows ? Visibility.Visible : Visibility.Collapsed;
  524. Export.Visibility = Options.ExportData ? Visibility.Visible : Visibility.Collapsed;
  525. Import.Visibility = Options.ImportData ? Visibility.Visible : Visibility.Collapsed;
  526. ExportSpacer.Visibility = Options.ExportData || Options.ImportData
  527. ? Visibility.Visible
  528. : Visibility.Collapsed;
  529. SwitchViewBtn.Visibility = Options.DirectEdit
  530. ? Options.HideDirectEditButton
  531. ? Visibility.Collapsed
  532. : Visibility.Visible
  533. : Visibility.Collapsed;
  534. Count.Visibility = Options.RecordCount ? Visibility.Visible : Visibility.Collapsed;
  535. Delete.Visibility = Options.DeleteRows ? Visibility.Visible : Visibility.Collapsed;
  536. if (up != null && down != null)
  537. {
  538. var hasSequence = up.Position == DynamicActionColumnPosition.Start;
  539. var shouldHaveSequence = Options.EditRows;
  540. if(hasSequence != shouldHaveSequence)
  541. {
  542. up.Position = Options.EditRows ? DynamicActionColumnPosition.Start : DynamicActionColumnPosition.Hidden;
  543. down.Position = Options.EditRows ? DynamicActionColumnPosition.Start : DynamicActionColumnPosition.Hidden;
  544. reloadColumns = true;
  545. }
  546. }
  547. if (DuplicateBtn != null)
  548. DuplicateBtn.Visibility = Visibility.Collapsed;
  549. if (UIComponent.OptionsChanged())
  550. {
  551. reloadColumns = true;
  552. }
  553. if(reloadColumns && IsReady)
  554. {
  555. Refresh(true, false);
  556. }
  557. }
  558. public bool IsDirectEditMode()
  559. {
  560. return Options.DirectEdit
  561. && (Settings.ViewMode == DynamicGridSettings.DynamicGridViewMode.DirectEdit
  562. || Settings.ViewMode == DynamicGridSettings.DynamicGridViewMode.Default);
  563. }
  564. private void SwitchView_Click(object sender, RoutedEventArgs e)
  565. {
  566. Settings.ViewMode = Settings.ViewMode switch
  567. {
  568. DynamicGridSettings.DynamicGridViewMode.Default => DynamicGridSettings.DynamicGridViewMode.Normal,
  569. DynamicGridSettings.DynamicGridViewMode.Normal => DynamicGridSettings.DynamicGridViewMode.DirectEdit,
  570. DynamicGridSettings.DynamicGridViewMode.DirectEdit or _ => DynamicGridSettings.DynamicGridViewMode.Normal
  571. };
  572. SaveSettings(Settings);
  573. Reconfigure();
  574. }
  575. public DynamicGridOptions Options { get; }
  576. protected void OnReconfigureEvent(DynamicGridOptions options)
  577. {
  578. OnReconfigure?.Invoke(options);
  579. }
  580. /// <summary>
  581. /// Configure custom buttons and options.
  582. /// </summary>
  583. public void Reconfigure(DynamicGridOptions options)
  584. {
  585. options.BeginUpdate().Clear();
  586. DoReconfigure(options);
  587. OnReconfigureEvent(options);
  588. options.EndUpdate();
  589. if (!_hasLoadedOptions)
  590. {
  591. _hasLoadedOptions = true;
  592. OptionsChanged();
  593. }
  594. }
  595. public void Reconfigure()
  596. {
  597. Reconfigure(Options);
  598. }
  599. public void Reconfigure(ReconfigureEvent onReconfigure)
  600. {
  601. OnReconfigure += onReconfigure;
  602. Reconfigure();
  603. }
  604. #endregion
  605. protected virtual DynamicGridSettings LoadSettings()
  606. {
  607. return new DynamicGridSettings();
  608. }
  609. protected virtual void SaveSettings(DynamicGridSettings settings)
  610. {
  611. }
  612. protected virtual void LoadColumnsMenu(ContextMenu menu)
  613. {
  614. }
  615. protected void UpdateCell(int row, string colname, object? value)
  616. {
  617. var coreRow = Data.Rows[row];
  618. coreRow[colname] = value;
  619. UIComponent.UpdateCell(coreRow, colname, value);
  620. }
  621. protected void UpdateCell(CoreRow row, DynamicColumnBase column)
  622. {
  623. UIComponent.UpdateCell(row, column);
  624. }
  625. private void EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  626. {
  627. OnAfterEditorValueChanged(null, [obj], new AfterEditorValueChangedArgs(changedColumn, changes), changes);
  628. SaveItem(obj);
  629. foreach (var (key, value) in changes)
  630. {
  631. row[key] = value;
  632. }
  633. UIComponent.UpdateRow(row);
  634. }
  635. #region Row Selections
  636. protected CoreRow[] GetVisibleRows()
  637. {
  638. return UIComponent.GetVisibleRows();
  639. }
  640. public CoreRow[] SelectedRows
  641. {
  642. get => UIComponent.SelectedRows;
  643. set => UIComponent.SelectedRows = value;
  644. }
  645. /// <summary>
  646. /// Call the <see cref="OnSelectItem"/> event, and do any updating which needs to occur when items are selected.
  647. /// </summary>
  648. /// <param name="rows"></param>
  649. protected virtual void SelectItems(CoreRow[]? rows)
  650. {
  651. if (IsReady)
  652. OnSelectItem?.Invoke(this, new DynamicGridSelectionEventArgs(rows));
  653. DuplicateBtn.Visibility =
  654. typeof(T).IsAssignableTo(typeof(IDuplicatable)) && rows != null && rows.Length >= 1 ? Visibility.Visible : Visibility.Collapsed;
  655. }
  656. protected virtual void DoDoubleClick(object sender, DynamicGridCellClickEventArgs args)
  657. {
  658. if (IsDirectEditMode())
  659. return;
  660. //SelectItems(SelectedRows);
  661. var e = new HandledEventArgs(false);
  662. OnDoubleClick?.Invoke(sender, e);
  663. if (e.Handled)
  664. return;
  665. if (Options.EditRows)
  666. DoEdit();
  667. }
  668. #endregion
  669. #region Column Handling
  670. #region Column Grouping
  671. public DynamicGridColumnGroupings ColumnGroupings { get; set; }
  672. /// <summary>
  673. /// Create a new column header group, and return it for editing.
  674. /// </summary>
  675. /// <returns></returns>
  676. public DynamicGridColumnGrouping AddColumnGrouping()
  677. {
  678. var group = new DynamicGridColumnGrouping();
  679. ColumnGroupings.Add(group);
  680. return group;
  681. }
  682. /// <summary>
  683. /// Gets the current column header group, and if there is none, create a new one.
  684. /// </summary>
  685. /// <returns></returns>
  686. public DynamicGridColumnGrouping GetColumnGrouping()
  687. {
  688. if(ColumnGroupings.Count == 0)
  689. {
  690. return AddColumnGrouping();
  691. }
  692. return ColumnGroupings[^1];
  693. }
  694. #endregion
  695. protected virtual DynamicGridColumns LoadColumns()
  696. {
  697. return GenerateColumns();
  698. }
  699. /// <summary>
  700. /// 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"/>.
  701. /// </summary>
  702. /// <param name="columns"></param>
  703. /// <returns></returns>
  704. protected DynamicGridColumns ExtractColumns(Columns<T> columns)
  705. {
  706. var cols = new DynamicGridColumns();
  707. foreach (var col in columns)
  708. {
  709. var mc = MasterColumns.FirstOrDefault(x => x.ColumnName.Equals(col.Property));
  710. if (mc != null && mc.Editor is not NullEditor && mc.Editor.Visible != Visible.Hidden)
  711. cols.Add(mc);
  712. }
  713. return cols;
  714. }
  715. /// <summary>
  716. /// Provide a set of columns which is the default for this grid.
  717. /// </summary>
  718. public virtual DynamicGridColumns GenerateColumns()
  719. {
  720. var cols = IsDirectEditMode()
  721. ? new Columns<T>(ColumnTypeFlags.IncludeVisible | ColumnTypeFlags.IncludeForeignKeys)
  722. : new Columns<T>(ColumnTypeFlags.IncludeVisible | ColumnTypeFlags.IncludeLinked);
  723. return ExtractColumns(cols);
  724. }
  725. private bool SwapRows(int row1, int row2)
  726. {
  727. CoreRow[] rows = Data.Rows.Where(x => x.Index.Equals(row1) || x.Index.Equals(row2)).ToArray();
  728. var items = LoadItems(rows);
  729. var first = (items.First() as ISequenceable)!;
  730. var last = (items.Last() as ISequenceable)!;
  731. var iBuf1 = first.Sequence;
  732. var iBuf2 = last.Sequence;
  733. first.Sequence = iBuf2;
  734. last.Sequence = iBuf1;
  735. SaveItems(items);
  736. return true;
  737. }
  738. protected virtual void SaveColumns(DynamicGridColumns columns)
  739. {
  740. }
  741. public int DesiredWidth()
  742. {
  743. return UIComponent.DesiredWidth();
  744. }
  745. /// <summary>
  746. /// Handle to configure column groups.
  747. /// </summary>
  748. /// <remarks>
  749. /// This is called after <see cref="LoadColumns"/>, so by the time this is called, both <see cref="VisibleColumns"/>
  750. /// and <see cref="ActionColumns"/> will be loaded, which means one can reference these in the column groups.
  751. /// <br/>
  752. /// <b>Note:</b> <see cref="ColumnGroupings"/> is cleared before this function is called.
  753. /// </remarks>
  754. protected virtual void ConfigureColumnGroups()
  755. {
  756. }
  757. protected virtual void ConfigureColumns(DynamicGridColumns columns)
  758. {
  759. }
  760. public class ColumnsLoadedEventArgs : EventArgs
  761. {
  762. public DynamicGridColumns VisibleColumns { get; private set; }
  763. public DynamicActionColumns ActionColumns { get; private set; }
  764. public DynamicGridColumnGroupings ColumnGroupings { get; private set; }
  765. public ColumnsLoadedEventArgs(DynamicGridColumns visibleColumns, DynamicActionColumns actionColumns,
  766. DynamicGridColumnGroupings columnGroupings)
  767. {
  768. VisibleColumns = visibleColumns;
  769. ActionColumns = actionColumns;
  770. ColumnGroupings = columnGroupings;
  771. }
  772. }
  773. public delegate void ColumnsLoadedEvent(DynamicGrid sender, ColumnsLoadedEventArgs args);
  774. public event ColumnsLoadedEvent ColumnsLoaded;
  775. private void ReloadColumns()
  776. {
  777. ConfigureColumns(MasterColumns);
  778. VisibleColumns = LoadColumns();
  779. ConfigureColumns(VisibleColumns);
  780. ColumnGroupings.Clear();
  781. ConfigureColumnGroups();
  782. ColumnsLoaded?.Invoke(this,new ColumnsLoadedEventArgs(VisibleColumns, ActionColumns, ColumnGroupings));
  783. UIComponent.RefreshColumns(VisibleColumns, ActionColumns, ColumnGroupings);
  784. }
  785. #endregion
  786. #region Refresh / Reload
  787. protected abstract void Reload(
  788. Filters<T> criteria, Columns<T> columns, ref SortOrder<T>? sort,
  789. CancellationToken token, Action<CoreTable?, Exception?> action);
  790. public Filter<T>? DefineFilter()
  791. {
  792. if (OnDefineFilter is null)
  793. return null;
  794. var result = OnDefineFilter.Invoke(typeof(T)) as Filter<T>;
  795. return result;
  796. }
  797. protected virtual bool FilterRecord(CoreRow row)
  798. {
  799. var bOK = ActionColumns.All(x =>
  800. {
  801. return x.FilterRecord is null
  802. || ((x.SelectedFilters is null || x.SelectedFilters.Length == 0 || x.FilterRecord.Invoke(row, x.SelectedFilters))
  803. && (x.ExcludeFilters is null || x.ExcludeFilters.Length == 0 || !x.FilterRecord.Invoke(row, x.ExcludeFilters)));
  804. });
  805. if (bOK && OnFilterRecord is not null)
  806. bOK = OnFilterRecord(row);
  807. return bOK;
  808. }
  809. public IEnumerable<TType> ExtractValues<TType>(Expression<Func<T, TType>> column, Selection selection)
  810. {
  811. var result = selection == Selection.None
  812. ? Enumerable.Empty<TType>()
  813. : selection == Selection.Selected
  814. ? SelectedRows.Select(r => r.Get(column))
  815. : Data.ExtractValues(column);
  816. return result;
  817. }
  818. private class RowRange(int rowIdx, int size)
  819. {
  820. public int RowIdx { get; set; } = rowIdx;
  821. public int Size { get; set; } = size;
  822. }
  823. private CancellationTokenSource? RefreshCancellationToken;
  824. public virtual void Refresh(bool reloadcolumns, bool reloaddata)
  825. {
  826. if (bRefreshing)
  827. return;
  828. if (!DoBeforeRefresh())
  829. return;
  830. UIComponent.BeforeRefresh();
  831. using var cursor = UseWaitCursor ? new WaitCursor() : null;
  832. Loading.Visibility = Visibility.Visible;
  833. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  834. bRefreshing = true;
  835. if (reloadcolumns)
  836. ReloadColumns();
  837. if (reloaddata)
  838. {
  839. _lookupcache.Clear();
  840. var criteria = new Filters<T>();
  841. var filter = DefineFilter();
  842. if (filter != null)
  843. criteria.Add(filter);
  844. var columns = DataColumns();
  845. var sort = LookupFactory.DefineSort<T>();
  846. if (sort == null && IsSequenced)
  847. sort = new SortOrder<T>("Sequence");
  848. RefreshCancellationToken?.Cancel();
  849. var tokenSource = new CancellationTokenSource();
  850. RefreshCancellationToken = tokenSource;
  851. var token = tokenSource.Token;
  852. Reload(
  853. criteria, columns, ref sort,
  854. token,
  855. (table, exception) =>
  856. {
  857. if(token.IsCancellationRequested) return; // Don't bother even checking exceptions if task was cancelled.
  858. if (exception != null)
  859. {
  860. Dispatcher.Invoke(() =>
  861. {
  862. MessageWindow.ShowError("Sorry! We couldn't load the data.", exception);
  863. });
  864. }
  865. else if (table is not null)
  866. {
  867. if(table.Offset == 0 || MasterData is null)
  868. {
  869. MasterData = table;
  870. Dispatcher.Invoke(() =>
  871. {
  872. try
  873. {
  874. ProcessData(null);
  875. }
  876. catch (Exception e)
  877. {
  878. }
  879. DoAfterRefresh();
  880. bRefreshing = false;
  881. IsReady = true;
  882. });
  883. }
  884. else
  885. {
  886. int idx = MasterData.Rows.Count;
  887. MasterData.AddPage(table);
  888. Dispatcher.Invoke(() =>
  889. {
  890. try
  891. {
  892. ProcessData(new(idx, table.Rows.Count));
  893. }
  894. catch(Exception e)
  895. {
  896. }
  897. });
  898. }
  899. }
  900. }
  901. );
  902. }
  903. else
  904. {
  905. ProcessData(null);
  906. DoAfterRefresh();
  907. bRefreshing = false;
  908. IsReady = true;
  909. }
  910. }
  911. public void Shutdown()
  912. {
  913. RefreshCancellationToken?.Cancel();
  914. }
  915. protected void NotifyBeforeRefresh(BeforeRefreshEventArgs args) => BeforeRefresh?.Invoke(this, args);
  916. protected void NotifyAfterRefresh(AfterRefreshEventArgs args) => AfterRefresh?.Invoke(this, args);
  917. protected bool OnBeforeRefresh()
  918. {
  919. return true;
  920. }
  921. private bool DoBeforeRefresh()
  922. {
  923. var result = OnBeforeRefresh();
  924. if (result)
  925. {
  926. var args = new BeforeRefreshEventArgs() { Cancel = false };
  927. NotifyBeforeRefresh(args);
  928. result = args.Cancel == false;
  929. }
  930. return result;
  931. }
  932. protected virtual void OnAfterRefresh()
  933. {
  934. }
  935. protected void DoAfterRefresh()
  936. {
  937. OnAfterRefresh();
  938. NotifyAfterRefresh(new AfterRefreshEventArgs());
  939. }
  940. public Columns<T> DataColumns()
  941. {
  942. var columns = Columns.None<T>();
  943. foreach (var column in VisibleColumns)
  944. columns.Add(column.ColumnName);
  945. foreach (var column in HiddenColumns.ColumnNames)
  946. columns.Add(new Column<T>(column));
  947. return columns;
  948. }
  949. /// <summary>
  950. /// Process the data from <see cref="MasterData"/> according to <paramref name="range"/>.
  951. /// </summary>
  952. /// <remarks>
  953. /// Set <paramref name="range"/> to <see langword="null"/> if this is the first page of data to be loaded. This will thus update the grid accordingly,
  954. /// clearing all current rows, resetting columns, selection, etc. If the <paramref name="range"/> is provided, this will add to the grid the rows
  955. /// according to the range from <see cref="MasterData"/>.
  956. /// </remarks>
  957. /// <param name="initialLoad"></param>
  958. private void ProcessData(RowRange? range)
  959. {
  960. if(range is null)
  961. {
  962. Data.Columns.Clear();
  963. Data.Setters.Clear();
  964. if (MasterData != null)
  965. foreach (var column in MasterData.Columns)
  966. Data.Columns.Add(column);
  967. }
  968. LoadData(range);
  969. }
  970. protected readonly Dictionary<CoreRow, CoreRow> _recordmap = new();
  971. public void UpdateRow<TRow, TType>(CoreRow row, Expression<Func<TRow, TType>> column, TType value, bool refresh = true)
  972. {
  973. row.Set(column, value);
  974. _recordmap[row].Set(column, value);
  975. if (refresh)
  976. InvalidateRow(row);
  977. }
  978. public void UpdateRow<TType>(CoreRow row, string column, TType value, bool refresh = true)
  979. {
  980. row.Set(column, value);
  981. _recordmap[row].Set(column, value);
  982. if (refresh)
  983. InvalidateRow(row);
  984. }
  985. public void UpdateRow(CoreRow row, T obj)
  986. {
  987. ObjectToRow(obj, row);
  988. ObjectToRow(obj, _recordmap[row]);
  989. }
  990. /// <summary>
  991. /// Update/sync the data in <paramref name="rows"/> with that of <paramref name="objs"/>.
  992. /// </summary>
  993. public void UpdateRows(CoreRow[] rows, T[] objs, bool invalidateRows = true)
  994. {
  995. for(var i = 0; i < objs.Length; ++i)
  996. {
  997. UpdateRow(rows[i], objs[i]);
  998. if (invalidateRows)
  999. {
  1000. InvalidateRow(rows[i]);
  1001. }
  1002. }
  1003. }
  1004. public void AddRow(CoreRow row)
  1005. {
  1006. if (MasterData is null) return;
  1007. var masterrow = MasterData.NewRow();
  1008. MasterData.FillRow(masterrow, row);
  1009. Refresh(false, false);
  1010. }
  1011. public void AddRow(T data)
  1012. {
  1013. if (MasterData is null) return;
  1014. MasterData.LoadRow(data);
  1015. Refresh(false, false);
  1016. }
  1017. public void DeleteRow(CoreRow row)
  1018. {
  1019. if (MasterData is null) return;
  1020. var masterrow = _recordmap[row];
  1021. MasterData.Rows.Remove(masterrow);
  1022. Refresh(false, false);
  1023. }
  1024. /// <summary>
  1025. /// Filter all given rows into <paramref name="into"/>, given that they match <paramref name="filter"/> and <see cref="FilterRecord(CoreRow)"/>.
  1026. /// If <paramref name="recordMap"/> is given, also updates the map from <paramref name="from"/> to <paramref name="into"/>.
  1027. /// </summary>
  1028. private IList<CoreRow> FilterRows(
  1029. IEnumerable<CoreRow> from,
  1030. CoreTable into,
  1031. Dictionary<CoreRow, CoreRow>? recordMap = null,
  1032. Func<CoreRow, bool>? filter = null)
  1033. {
  1034. var newRows = new List<CoreRow>();
  1035. foreach (var row in from)
  1036. if (FilterRecord(row) && filter?.Invoke(row) != false)
  1037. {
  1038. var newrow = into.NewRow();
  1039. for (var i = 0; i < into.Columns.Count; i++)
  1040. {
  1041. var value = i < row.Values.Count ? row.Values[i] : null;
  1042. if (into.Columns[i].DataType.IsNumeric())
  1043. value = into.Columns[i].DataType.IsDefault(value) ? null : value;
  1044. newrow.Values.Add(value);
  1045. }
  1046. newRows.Add(newrow);
  1047. into.Rows.Add(newrow);
  1048. recordMap?.TryAdd(newrow, row);
  1049. }
  1050. return newRows;
  1051. }
  1052. private readonly SemaphoreSlim semaphore = new(1,1);
  1053. private void LoadData(RowRange? range)
  1054. {
  1055. if (MasterData is null)
  1056. return;
  1057. if(range is null)
  1058. {
  1059. ResetClipBuffer();
  1060. Data.Rows.Clear();
  1061. _recordmap.Clear();
  1062. FilterRows(MasterData.Rows, Data, _recordmap);
  1063. InvalidateGrid();
  1064. SelectedRows = Array.Empty<CoreRow>();
  1065. }
  1066. else
  1067. {
  1068. var _newRows = FilterRows(Enumerable.Range(range.RowIdx, range.Size).Select(i => MasterData.Rows[i]), Data, _recordmap);
  1069. UIComponent.AddPage(_newRows);
  1070. /*
  1071. semaphore.Wait();
  1072. try
  1073. {
  1074. // This throws errors when overalpping refreshes cause a mismatch between MasterData and range
  1075. // Using try/finally and a Semaphore as a temporary measure until we can isolate the issue
  1076. var _newRows = FilterRows(Enumerable.Range(range.RowIdx, range.Size).Select(i => MasterData.Rows[i]), Data, _recordmap);
  1077. UIComponent.AddPage(_newRows);
  1078. }
  1079. finally
  1080. {
  1081. semaphore.Release();
  1082. }*/
  1083. }
  1084. }
  1085. //IncrementalList<T> _data = null;
  1086. public void InvalidateRow(CoreRow row)
  1087. {
  1088. UIComponent.InvalidateRow(row);
  1089. }
  1090. protected void InvalidateGrid()
  1091. {
  1092. if (RowStyleSelector != null)
  1093. RowStyleSelector.Data = Data;
  1094. UIComponent.RefreshData(Data);
  1095. Loading.BeginAnimation(Label.OpacityProperty, null);
  1096. Loading.Visibility = Visibility.Collapsed;
  1097. }
  1098. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  1099. {
  1100. UIComponent.AddVisualFilter(column, value, filtertype);
  1101. }
  1102. protected List<Tuple<string, Func<CoreRow, bool>>> GetFilterPredicates()
  1103. {
  1104. return UIComponent.GetFilterPredicates();
  1105. }
  1106. #endregion
  1107. #region Item Manipulation
  1108. #region Load/Save/Delete
  1109. public virtual T[] LoadItems(IList<CoreRow> rows)
  1110. {
  1111. return rows.ToArray(LoadItem);
  1112. }
  1113. public abstract T LoadItem(CoreRow row);
  1114. public abstract void SaveItem(T item);
  1115. public virtual void SaveItems(IEnumerable<T> items)
  1116. {
  1117. foreach (var item in items)
  1118. SaveItem(item);
  1119. }
  1120. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  1121. {
  1122. return true;
  1123. }
  1124. public abstract void DeleteItems(params CoreRow[] rows);
  1125. protected virtual void DoDelete()
  1126. {
  1127. var rows = SelectedRows.ToArray();
  1128. if (rows.Any())
  1129. if (CanDeleteItems(rows))
  1130. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1131. MessageBoxResult.Yes)
  1132. {
  1133. DeleteItems(rows);
  1134. SelectedRows = Array.Empty<CoreRow>();
  1135. OnChanged?.Invoke(this, EventArgs.Empty);
  1136. Refresh(false, true);
  1137. SelectItems(null);
  1138. }
  1139. }
  1140. private void Delete_Click(object sender, RoutedEventArgs e)
  1141. {
  1142. DoDelete();
  1143. }
  1144. #endregion
  1145. #region Edit
  1146. protected virtual void DoEdit()
  1147. {
  1148. if (SelectedRows.Length == 0)
  1149. return;
  1150. if (AddEditClick(SelectedRows))
  1151. {
  1152. SelectItems(SelectedRows);
  1153. }
  1154. }
  1155. private void Edit_Click(object sender, RoutedEventArgs e)
  1156. {
  1157. DoEdit();
  1158. }
  1159. protected virtual void DoAdd(bool openEditorOnDirectEdit = false)
  1160. {
  1161. //CoreRow row = (SelectedRow > -1) && (SelectedRow < Data.Rows.Count) ? Data.Rows[this.SelectedRow] : null;
  1162. if (IsDirectEditMode() && !openEditorOnDirectEdit)
  1163. {
  1164. CreateItems(null);
  1165. }
  1166. else if (AddEditClick(null))
  1167. {
  1168. Refresh(false, true);
  1169. }
  1170. }
  1171. protected void CreateItems(Func<IEnumerable<T>>? create)
  1172. {
  1173. var newRows = new List<CoreRow>();
  1174. var items = create?.Invoke() ?? CoreUtils.One(CreateItem());
  1175. foreach (var item in items)
  1176. {
  1177. if (!AfterCreate(item))
  1178. return;
  1179. SaveItem(item);
  1180. var datarow = Data.NewRow();
  1181. ObjectToRow(item, datarow);
  1182. Data.Rows.Add(datarow);
  1183. newRows.Add(datarow);
  1184. var masterrow = MasterData.NewRow();
  1185. ObjectToRow(item, masterrow);
  1186. MasterData.Rows.Add(masterrow);
  1187. _recordmap[datarow] = masterrow;
  1188. }
  1189. InvalidateGrid();
  1190. SelectedRows = newRows.ToArray();
  1191. OnChanged?.Invoke(this, EventArgs.Empty);
  1192. }
  1193. private void Add_Click(object sender, RoutedEventArgs e)
  1194. {
  1195. if (CanCreateItems())
  1196. DoAdd();
  1197. }
  1198. public virtual DynamicEditorPages LoadEditorPages(T item)
  1199. {
  1200. DynamicEditorPages pages = new DynamicEditorPages();
  1201. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  1202. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  1203. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  1204. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  1205. foreach (var page in pages)
  1206. page.Ready = false;
  1207. return pages;
  1208. }
  1209. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  1210. {
  1211. buttons.Clear();
  1212. buttons.Add(
  1213. "",
  1214. Wpf.Resources.help.AsBitmapImage(),
  1215. item,
  1216. (f, i) =>
  1217. {
  1218. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  1219. { UseShellExecute = true });
  1220. }
  1221. );
  1222. OnLoadEditorButtons?.Invoke(item, buttons);
  1223. }
  1224. protected virtual void BeforeLoad(IDynamicEditorForm form, T[] items)
  1225. {
  1226. form.BeforeLoad();
  1227. }
  1228. void IDynamicGrid.InitialiseEditorForm(IDynamicEditorForm editor, object[] items, Func<Type, CoreTable>? pageDataHandler, bool preloadPages)
  1229. {
  1230. InitialiseEditorForm(editor, items.Cast<T>().ToArray(), pageDataHandler, preloadPages);
  1231. }
  1232. public virtual bool EditItems(object[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1233. {
  1234. var values = items.Cast<T>().ToArray();
  1235. return EditItems(values, PageDataHandler, PreloadPages);
  1236. }
  1237. public virtual void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false)
  1238. {
  1239. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  1240. var buttons = new DynamicEditorButtons();
  1241. if (items.Length == 1)
  1242. LoadEditorButtons(items.First(), buttons);
  1243. editor.Setup(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, pageDataHandler, preloadPages);
  1244. editor.OnCustomiseColumns = (sender, columns) =>
  1245. {
  1246. columns.Clear();
  1247. columns.AddRange(MasterColumns);
  1248. };
  1249. editor.OnDefineEditor = (o, c) =>
  1250. {
  1251. var result = GetEditor(o, c);
  1252. if (result != null)
  1253. result = result.CloneEditor();
  1254. return result;
  1255. };
  1256. editor.OnFormCustomiseEditor += DoCustomiseEditor;
  1257. editor.OnDefineFilter = (type, column) => { return DefineLookupFilter(type, column, items); };
  1258. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  1259. editor.OnDefineLookups = editor => DefineLookups(editor, items);
  1260. editor.OnEditorValueChanged += (s, n, v) => EditorValueChanged(editor, items, n, v);
  1261. editor.OnAfterEditorValueChanged += (g, args) => AfterEditorValueChanged(g, items, args);
  1262. editor.OnReconfigureEditors = g => DoReconfigureEditors(g, items);
  1263. editor.OnValidateData += (o, i) => ValidateData(items);
  1264. editor.OnSelectPage += SelectPage;
  1265. editor.OnSaveItem = (o, e) =>
  1266. {
  1267. try
  1268. {
  1269. using var Wait = new WaitCursor();
  1270. DoBeforeSave(editor, items);
  1271. if (items.Length == 1)
  1272. editor.UnloadEditorPages(false);
  1273. foreach (var item in items)
  1274. SaveItem(item);
  1275. if (items.Length == 1)
  1276. editor.UnloadEditorPages(true);
  1277. DoAfterSave(editor, items);
  1278. }
  1279. catch (Exception err)
  1280. {
  1281. MessageBox.Show(err.Message);
  1282. e.Cancel = true;
  1283. }
  1284. };
  1285. BeforeLoad(editor, items);
  1286. editor.Items = items;
  1287. AfterLoad(editor, items);
  1288. }
  1289. private void DoCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  1290. {
  1291. CustomiseEditor((T[])items, column, editor);
  1292. OnCustomiseEditor?.Invoke(sender, (T[])items, column, editor);
  1293. }
  1294. protected virtual void CustomiseEditor(T[] items, DynamicGridColumn column, BaseEditor editor)
  1295. {
  1296. }
  1297. protected virtual void DoAfterSave(IDynamicEditorForm editor, T[] items)
  1298. {
  1299. OnAfterSave?.Invoke(editor, items);
  1300. }
  1301. protected virtual void DoBeforeSave(IDynamicEditorForm editor, T[] items)
  1302. {
  1303. OnBeforeSave?.Invoke(editor, items);
  1304. }
  1305. public virtual bool EditItems(T[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1306. {
  1307. DynamicEditorForm editor;
  1308. using (var cursor = new WaitCursor())
  1309. {
  1310. editor = new DynamicEditorForm();
  1311. editor.SetValue(Panel.ZIndexProperty, 999);
  1312. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  1313. OnEditorLoaded?.Invoke(editor, items);
  1314. }
  1315. return editor.ShowDialog() == true;
  1316. }
  1317. private Dictionary<String, object?> AfterEditorValueChanged(DynamicEditorGrid grid, T[] items, AfterEditorValueChangedArgs args)
  1318. {
  1319. var changes = new Dictionary<string, object?>();
  1320. OnAfterEditorValueChanged(grid, items, args, changes);
  1321. return changes;
  1322. }
  1323. protected virtual void OnAfterEditorValueChanged(DynamicEditorGrid? grid, T[] items, AfterEditorValueChangedArgs args, Dictionary<String, object?> changes)
  1324. {
  1325. }
  1326. protected virtual void DoReconfigureEditors(DynamicEditorGrid grid, T[] items)
  1327. {
  1328. /*if (items.First() is IDimensioned dimensioned)
  1329. {
  1330. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  1331. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  1332. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  1333. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  1334. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  1335. }*/
  1336. }
  1337. private List<string>? ValidateData(T[] items)
  1338. {
  1339. var errors = new List<string>();
  1340. DoValidate(items, errors);
  1341. OnValidate?.Invoke(this, items, errors);
  1342. return errors.Count != 0 ? errors : null;
  1343. }
  1344. protected virtual void DoValidate(T[] items, List<string> errors)
  1345. {
  1346. }
  1347. protected virtual void AfterLoad(IDynamicEditorForm editor, T[] items)
  1348. {
  1349. editor.AfterLoad();
  1350. }
  1351. protected virtual void SelectPage(object sender, BaseObject[]? items)
  1352. {
  1353. }
  1354. protected virtual Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, T[] items, string name, object value)
  1355. {
  1356. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  1357. if (OnEditorValueChanged != null)
  1358. {
  1359. var newchanges = OnEditorValueChanged(editor, name, value);
  1360. foreach (var key in newchanges.Keys)
  1361. result[key] = newchanges[key];
  1362. }
  1363. return result;
  1364. }
  1365. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  1366. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items, bool async = true)
  1367. {
  1368. if (sender.EditorDefinition is not ILookupEditor editor)
  1369. return;
  1370. var colname = sender.ColumnName;
  1371. if (async)
  1372. {
  1373. Task.Run(() =>
  1374. {
  1375. try
  1376. {
  1377. var values = editor.Values(typeof(T), colname, items);
  1378. Dispatcher.Invoke(
  1379. () =>
  1380. {
  1381. try
  1382. {
  1383. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  1384. sender.LoadLookups(values);
  1385. }
  1386. catch (Exception e2)
  1387. {
  1388. Logger.Send(LogType.Information, typeof(T).Name,
  1389. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  1390. }
  1391. }
  1392. );
  1393. }
  1394. catch (Exception e)
  1395. {
  1396. Logger.Send(LogType.Information, typeof(T).Name,
  1397. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  1398. }
  1399. });
  1400. }
  1401. else
  1402. {
  1403. var values = editor.Values(typeof(T), colname, items);
  1404. sender.LoadLookups(values);
  1405. }
  1406. }
  1407. /// <summary>
  1408. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  1409. /// </summary>
  1410. /// <param name="item">The object being edited.</param>
  1411. /// <param name="column">The column of the editor.</param>
  1412. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  1413. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  1414. {
  1415. return column.Editor ?? CoreUtils.GetProperty(item.GetType(), column.ColumnName).GetEditor();
  1416. }
  1417. protected IFilter? DefineLookupFilter(Type type, string column, T[] items)
  1418. {
  1419. return LookupFactory.DefineLookupFilter(typeof(T), type, column, items);
  1420. }
  1421. protected virtual void SetEditorValue(object item, string name, object value)
  1422. {
  1423. try
  1424. {
  1425. CoreUtils.SetPropertyValue(item, name, value);
  1426. }
  1427. catch (Exception e)
  1428. {
  1429. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1430. }
  1431. }
  1432. protected virtual object? GetEditorValue(object item, string name)
  1433. {
  1434. return CoreUtils.GetPropertyValue(item, name);
  1435. }
  1436. protected virtual bool CanCreateItems()
  1437. {
  1438. return true;
  1439. }
  1440. private bool AddEditClick(CoreRow[]? rows)
  1441. {
  1442. if (!IsEnabled || bRefreshing)
  1443. return false;
  1444. if (rows == null || rows.Length == 0)
  1445. {
  1446. if (!CanCreateItems())
  1447. return false;
  1448. var item = CreateItem();
  1449. if (!AfterCreate(item))
  1450. return false;
  1451. // Yea, and this won't work, because we're actually usually showing the description of a linked item,
  1452. // not the id of the link, and we need to set the ID to have it work properly :-(
  1453. //foreach (String key in VisualFilters.Keys)
  1454. // CoreUtils.SetPropertyValue(item, key, VisualFilters[key]);
  1455. if (EditItems([item]))
  1456. {
  1457. //_CurrentRow = Data.Rows.Count;
  1458. var row = Data.NewRow();
  1459. ObjectToRow(item, row);
  1460. Data.Rows.Add(row);
  1461. InvalidateGrid();
  1462. SelectedRows = [row];
  1463. DoChanged();
  1464. return true;
  1465. }
  1466. return false;
  1467. }
  1468. var items = Array.Empty<T>();
  1469. using (new WaitCursor())
  1470. {
  1471. Stopwatch sw = new Stopwatch();
  1472. sw.Start();
  1473. items = LoadItems(rows);
  1474. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  1475. sw.Stop();
  1476. }
  1477. if (items.Length != 0)
  1478. {
  1479. var snaps = items.ToArray(x => x.TakeSnapshot());
  1480. if (EditItems(items))
  1481. {
  1482. var sel = SelectedRows;
  1483. UpdateRows(rows, items, invalidateRows: false);
  1484. InvalidateGrid();
  1485. SelectedRows = sel;
  1486. DoChanged();
  1487. return true;
  1488. }
  1489. else
  1490. {
  1491. foreach(var snap in snaps)
  1492. {
  1493. snap.ResetObject();
  1494. }
  1495. }
  1496. return false;
  1497. }
  1498. return false;
  1499. }
  1500. #endregion
  1501. #region Duplicate
  1502. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  1503. {
  1504. return LoadItems(rows);
  1505. }
  1506. private bool DoDuplicate(Button button, CoreRow[] rows)
  1507. {
  1508. if (!rows.Any())
  1509. {
  1510. MessageBox.Show("Please select at least one record to duplicate!");
  1511. return false;
  1512. }
  1513. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  1514. if (!ids.Any())
  1515. {
  1516. MessageBox.Show("Please select at least one record to duplicate!");
  1517. return false;
  1518. }*/
  1519. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  1520. if (duplicator is null)
  1521. {
  1522. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  1523. return false;
  1524. }
  1525. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  1526. return true;
  1527. }
  1528. #endregion
  1529. public virtual T CreateItem()
  1530. {
  1531. var result = new T();
  1532. OnCreateItem?.Invoke(this, result);
  1533. return result;
  1534. }
  1535. public virtual bool AfterCreate(T item)
  1536. {
  1537. return OnAfterCreateItem?.Invoke(this, item) ?? true;
  1538. }
  1539. protected virtual void DoPrint(object sender)
  1540. {
  1541. OnPrintData?.Invoke(sender);
  1542. }
  1543. protected virtual void ShowHelp(string slug)
  1544. {
  1545. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  1546. }
  1547. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(IDynamicEditorForm editor, TTargetType item,
  1548. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  1549. where TTargetType : Entity, new()
  1550. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  1551. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  1552. {
  1553. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  1554. var page =
  1555. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  1556. if (page != null && item != null)
  1557. {
  1558. if (!page.Ready)
  1559. page.Load(item, null);
  1560. CoreTable table;
  1561. if (sourceid == Guid.Empty)
  1562. {
  1563. table = new CoreTable();
  1564. table.LoadColumns(typeof(TSourceForm));
  1565. }
  1566. else
  1567. {
  1568. table = new Client<TSourceForm>().Query(
  1569. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  1570. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  1571. );
  1572. }
  1573. var newforms = new List<TTargetForm>();
  1574. foreach (var row in table.Rows)
  1575. {
  1576. var sourceform = row.ToObject<TSourceForm>();
  1577. var targetform = new TTargetForm();
  1578. targetform.Form.ID = sourceform.Form.ID;
  1579. targetform.Form.Synchronise(sourceform.Form);
  1580. newforms.Add(targetform);
  1581. }
  1582. page.Items.Clear();
  1583. page.LoadItems(newforms.ToArray());
  1584. }
  1585. }
  1586. #region ClipBuffer
  1587. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  1588. protected void ResetClipBuffer()
  1589. {
  1590. ClipBuffer = null;
  1591. }
  1592. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  1593. {
  1594. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  1595. }
  1596. private void CutToClipBuffer()
  1597. {
  1598. SetClipBuffer(ClipAction.Cut, SelectedRows);
  1599. InvalidateGrid();
  1600. }
  1601. private void CopyToClipBuffer()
  1602. {
  1603. SetClipBuffer(ClipAction.Copy, SelectedRows);
  1604. InvalidateGrid();
  1605. }
  1606. private void PasteFromClipBuffer()
  1607. {
  1608. if (ClipBuffer == null)
  1609. return;
  1610. if (!ShowSequenceButtons)
  1611. return;
  1612. using (new WaitCursor())
  1613. {
  1614. var updates = ClipBuffer.Item2.Select(x => x.ToObject<T>()).ToList();
  1615. if (BeforePaste(updates, ClipBuffer.Item1))
  1616. {
  1617. var currow = SelectedRows.FirstOrDefault()
  1618. ?? Data.Rows.LastOrDefault();
  1619. var sequence = currow != null ? currow.Get<T, long>(c => ((ISequenceable)c).Sequence) : 0;
  1620. var postrows = Data.Rows.Where(r => !ClipBuffer.Item2.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  1621. updates.AddRange(LoadItems(postrows.ToArray()));
  1622. foreach (var update in updates)
  1623. {
  1624. sequence++;
  1625. ((ISequenceable)update).Sequence = sequence;
  1626. }
  1627. }
  1628. if (updates.Any())
  1629. {
  1630. SaveItems(updates.ToArray());
  1631. Refresh(false, true);
  1632. }
  1633. }
  1634. }
  1635. protected virtual bool BeforePaste(IEnumerable<T> items, ClipAction action)
  1636. {
  1637. return true;
  1638. }
  1639. private void Cut_Click(object sender, RoutedEventArgs e)
  1640. {
  1641. CutToClipBuffer();
  1642. }
  1643. private void Copy_Click(object sender, RoutedEventArgs e)
  1644. {
  1645. CopyToClipBuffer();
  1646. }
  1647. private void Paste_Click(object sender, RoutedEventArgs e)
  1648. {
  1649. PasteFromClipBuffer();
  1650. }
  1651. #endregion
  1652. protected virtual void ObjectToRow(T obj, CoreRow row)
  1653. {
  1654. row.Table.FillRow(row, obj);
  1655. }
  1656. #region Import / Export
  1657. protected virtual CoreTable LoadImportKeys(String[] fields)
  1658. {
  1659. var result = new CoreTable();
  1660. result.LoadColumns(Columns.None<T>().Add(fields));
  1661. return result;
  1662. }
  1663. protected virtual Guid GetImportID()
  1664. {
  1665. return Guid.Empty;
  1666. }
  1667. protected virtual bool CustomiseImportItem(T item)
  1668. {
  1669. if (IsSequenced)
  1670. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  1671. return true;
  1672. }
  1673. protected virtual string CustomiseImportFileName(string filename)
  1674. {
  1675. return filename;
  1676. }
  1677. protected virtual void DoImport()
  1678. {
  1679. var list = new DynamicImportList(
  1680. typeof(T),
  1681. GetImportID()
  1682. );
  1683. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  1684. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  1685. list.OnSave += (sender, entity) => SaveItem(entity as T);
  1686. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  1687. list.ShowDialog();
  1688. Refresh(false, true);
  1689. }
  1690. private void Import_Click(object sender, RoutedEventArgs e)
  1691. {
  1692. DoImport();
  1693. }
  1694. protected virtual void CustomiseExportColumns(List<string> columnnames)
  1695. {
  1696. }
  1697. protected virtual string CustomiseExportFileName(string filename)
  1698. {
  1699. return filename;
  1700. }
  1701. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  1702. {
  1703. }
  1704. protected virtual void ApplyExportFilter(CoreTable table, object data)
  1705. {
  1706. }
  1707. protected virtual void DoExport()
  1708. {
  1709. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  1710. CustomiseExportColumns(columnnames);
  1711. var form = new DynamicExportForm(typeof(T), columnnames);
  1712. if (form.ShowDialog() != true)
  1713. return;
  1714. var filters = new Filters<T>();
  1715. filters.Add(DefineFilter());
  1716. var predicates = UIComponent.GetFilterPredicates();
  1717. var visiblerows = GetVisibleRows();
  1718. CustomiseExportFilters(filters, visiblerows);
  1719. var columns = Columns.None<T>().Add(form.Fields);
  1720. var otherColumns = form.GetChildFields()
  1721. .Select(x => new Tuple<Type, IColumns>(
  1722. x.Key,
  1723. Columns.None(x.Key).Add(x.Value)))
  1724. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  1725. var reloadColumns = Columns.None<T>();
  1726. foreach (var column in columns)
  1727. {
  1728. reloadColumns.Add(column);
  1729. }
  1730. foreach (var column in HiddenColumns.ColumnNames)
  1731. {
  1732. reloadColumns.Add(column);
  1733. }
  1734. foreach (var (column, _) in predicates)
  1735. {
  1736. reloadColumns.Add(column);
  1737. }
  1738. var sort = LookupFactory.DefineSort<T>();
  1739. Reload(filters, reloadColumns, ref sort, CancellationToken.None, (data, err) => Dispatcher.Invoke(() =>
  1740. {
  1741. if (data is not null)
  1742. {
  1743. var newData = new CoreTable();
  1744. newData.LoadColumns(columns);
  1745. FilterRows(data.Rows, newData, filter: row =>
  1746. {
  1747. foreach(var (_, predicate) in predicates)
  1748. {
  1749. if (!predicate(row))
  1750. {
  1751. return false;
  1752. }
  1753. }
  1754. return true;
  1755. });
  1756. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  1757. list.AddRange(LoadExportTables(filters, otherColumns));
  1758. DoExportTables(list);
  1759. }
  1760. else if (err is not null)
  1761. {
  1762. Logger.Send(LogType.Error, "", $"Error in export: {CoreUtils.FormatException(err)}");
  1763. MessageBox.Show(err.Message);
  1764. }
  1765. }));
  1766. }
  1767. private void Export_Click(object sender, RoutedEventArgs e)
  1768. {
  1769. DoExport();
  1770. }
  1771. /// <summary>
  1772. /// Loads the child tables for an export, based on the filter of the parent table.
  1773. /// </summary>
  1774. /// <remarks>
  1775. /// If not overriden, defaults to creating empty tables with no records.
  1776. /// </remarks>
  1777. /// <param name="filter">Filter for the parent table.</param>
  1778. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  1779. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  1780. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  1781. {
  1782. return tableColumns.Select(x =>
  1783. {
  1784. var table = new CoreTable();
  1785. table.LoadColumns(x.Item2);
  1786. return new Tuple<Type?, CoreTable>(x.Item1, table);
  1787. });
  1788. }
  1789. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  1790. {
  1791. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  1792. ExcelExporter.DoExport(data, filename);
  1793. }
  1794. #endregion
  1795. public void ScrollIntoView(CoreRow row)
  1796. {
  1797. UIComponent.ScrollIntoView(row);
  1798. }
  1799. #endregion
  1800. #region Custom Buttons
  1801. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  1802. {
  1803. var button = new Button();
  1804. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  1805. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  1806. button.Height = 30;
  1807. UpdateButton(button, image, text, tooltip);
  1808. return button;
  1809. }
  1810. public void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  1811. {
  1812. var stackPnl = new StackPanel();
  1813. stackPnl.Orientation = Orientation.Horizontal;
  1814. //stackPnl.Margin = new Thickness(2);
  1815. if (image != null)
  1816. {
  1817. var img = new Image();
  1818. img.Source = image;
  1819. img.Margin = new Thickness(2);
  1820. img.ToolTip = tooltip;
  1821. stackPnl.Children.Add(img);
  1822. }
  1823. if (!string.IsNullOrEmpty(text))
  1824. {
  1825. button.MaxWidth = double.MaxValue;
  1826. var lbl = new Label();
  1827. lbl.Content = text;
  1828. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  1829. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  1830. lbl.Margin = new Thickness(2, 0, 5, 0);
  1831. lbl.ToolTip = ToolTip;
  1832. stackPnl.Children.Add(lbl);
  1833. }
  1834. else
  1835. button.MaxWidth = 30;
  1836. button.Content = stackPnl;
  1837. button.ToolTip = tooltip;
  1838. }
  1839. private bool bFirstButtonAdded = true;
  1840. private bool AnyButtonsVisible()
  1841. {
  1842. if (Add.Visibility != Visibility.Collapsed)
  1843. return true;
  1844. if (Edit.Visibility != Visibility.Collapsed)
  1845. return true;
  1846. /*if (MultiEdit.Visibility != Visibility.Collapsed)
  1847. return true;*/
  1848. if (Export.Visibility != Visibility.Collapsed)
  1849. return true;
  1850. return false;
  1851. }
  1852. public Button AddButton(string? caption, BitmapImage? image, string? tooltip, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1853. {
  1854. var button = CreateButton(image, caption, tooltip);
  1855. button.Margin = position == DynamicGridButtonPosition.Right
  1856. ? new Thickness(2, 2, 0, 0)
  1857. : bFirstButtonAdded && AnyButtonsVisible()
  1858. ? new Thickness(0, 2, 0, 0)
  1859. : new Thickness(0, 2, 2, 0);
  1860. button.Padding = !String.IsNullOrWhiteSpace(caption) ? new Thickness(5, 1, 5, 1) : new Thickness(1);
  1861. button.Tag = action;
  1862. button.Click += Button_Click;
  1863. if (position == DynamicGridButtonPosition.Right)
  1864. RightButtonStack.Children.Add(button);
  1865. else
  1866. LeftButtonStack.Children.Add(button);
  1867. bFirstButtonAdded = false;
  1868. return button;
  1869. }
  1870. public Button AddButton(string? caption, BitmapImage? image, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1871. {
  1872. var result = AddButton(caption, image, null, action, position);
  1873. return result;
  1874. }
  1875. private void Button_Click(object sender, RoutedEventArgs e)
  1876. {
  1877. var button = (Button)sender;
  1878. var action = (DynamicGridButtonClickEvent)button.Tag;
  1879. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  1880. if (action.Invoke(button, SelectedRows))
  1881. Refresh(false, true);
  1882. }
  1883. #endregion
  1884. #region Header Actions
  1885. private void SelectColumnsClick()
  1886. {
  1887. var editor = new DynamicGridColumnsEditor(typeof(T));
  1888. editor.DirectEdit = IsDirectEditMode();
  1889. editor.Columns.AddRange(VisibleColumns);
  1890. if (editor.ShowDialog().Equals(true))
  1891. {
  1892. VisibleColumns.Clear();
  1893. VisibleColumns.AddRange(editor.Columns);
  1894. SaveColumns(editor.Columns);
  1895. //OnSaveColumns?.Invoke(this, editor.Columns);
  1896. Refresh(true, true);
  1897. }
  1898. }
  1899. #endregion
  1900. #region Drag + Drop
  1901. /// <summary>
  1902. /// Handle a number of rows from a different <see cref="DynamicGrid{T}"/> being dragged into this one.
  1903. /// </summary>
  1904. /// <param name="entity">The type of entity that that the rows of <paramref name="table"/> represent.</param>
  1905. /// <param name="table">The data being dragged.</param>
  1906. /// <param name="e"></param>
  1907. protected virtual void OnDragEnd(Type entity, CoreTable table, DragEventArgs e)
  1908. {
  1909. Logger.Send(LogType.Information,"","OnDragEnd");
  1910. }
  1911. /// <summary>
  1912. /// Handle all types of items being dragged onto this grid that aren't handled by <see cref="OnDragEnd(Type, CoreTable, DragEventArgs)"/>,
  1913. /// i.e., data which is not a <see cref="CoreTable"/> from another <see cref="DynamicGrid{T}"/>
  1914. /// </summary>
  1915. /// <remarks>
  1916. /// Can be used to handle files, for example.
  1917. /// </remarks>
  1918. /// <param name="sender"></param>
  1919. /// <param name="e"></param>
  1920. protected virtual void HandleDragDrop(object sender, DragEventArgs e)
  1921. {
  1922. }
  1923. protected virtual void HandleDragOver(object sender, DragEventArgs e)
  1924. {
  1925. }
  1926. protected DragDropEffects DragTable(Type entity, CoreTable table)
  1927. {
  1928. Logger.Send(LogType.Information, "", "DragTable");
  1929. var data = new DataObject();
  1930. data.SetData(DynamicGridUtils.DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  1931. var effect = DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  1932. return effect;
  1933. }
  1934. protected virtual DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1935. {
  1936. Logger.Send(LogType.Information, "", "OnRowsDragStart");
  1937. var table = new CoreTable();
  1938. table.LoadColumns(Data.Columns);
  1939. table.LoadRows(rows);
  1940. return DragTable(typeof(T), table);
  1941. }
  1942. #endregion
  1943. }
  1944. #region Styling
  1945. public class DynamicGridRowStyle : DynamicGridStyle<VirtualizingCellsControl>
  1946. {
  1947. public DynamicGridRowStyle() : base(null)
  1948. {
  1949. }
  1950. public DynamicGridRowStyle(IDynamicGridStyle source) : base(source)
  1951. {
  1952. }
  1953. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1954. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1955. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1956. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1957. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1958. }
  1959. public class DynamicGridCellStyle : DynamicGridStyle<Control>
  1960. {
  1961. public DynamicGridCellStyle() : base(null)
  1962. {
  1963. }
  1964. public DynamicGridCellStyle(IDynamicGridStyle source) : base(source)
  1965. {
  1966. }
  1967. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1968. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1969. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1970. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1971. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1972. }
  1973. // Used to render boolean columns (the default "false" value shows what appears to be an intermediate state, which is ugly
  1974. // This should show nothing for false, and a tick in a box for true
  1975. public class BoolToImageConverter : AbstractConverter<bool,ImageSource>
  1976. {
  1977. public ImageSource TrueValue { get; set; }
  1978. public ImageSource FalseValue { get; set; }
  1979. public BoolToImageConverter()
  1980. {
  1981. TrueValue = Wpf.Resources.Bullet_Tick.AsBitmapImage();
  1982. }
  1983. public override ImageSource Convert(bool value)
  1984. {
  1985. return value ? TrueValue : FalseValue;
  1986. }
  1987. public override bool Deconvert(ImageSource value)
  1988. {
  1989. return ImageUtils.IsEqual(value as BitmapImage,TrueValue as BitmapImage);
  1990. }
  1991. }
  1992. public class StringToColorImageConverter : IValueConverter
  1993. {
  1994. private readonly int _height = 50;
  1995. private readonly int _width = 25;
  1996. private readonly Dictionary<string, BitmapImage> cache = new();
  1997. public StringToColorImageConverter(int width, int height)
  1998. {
  1999. _width = width;
  2000. _height = height;
  2001. }
  2002. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  2003. {
  2004. var str = value?.ToString();
  2005. if (str is null)
  2006. return null;
  2007. var colorcode = str.TrimStart('#');
  2008. if (!cache.ContainsKey(colorcode))
  2009. {
  2010. var col = ImageUtils.StringToColor(colorcode);
  2011. var bmp = ImageUtils.BitmapFromColor(col, _width, _height, Color.Black);
  2012. cache[colorcode] = bmp.AsBitmapImage();
  2013. }
  2014. var result = cache[colorcode];
  2015. return result;
  2016. }
  2017. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  2018. {
  2019. return null;
  2020. }
  2021. }
  2022. public class StringArrayConverter : IValueConverter
  2023. {
  2024. object? IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
  2025. {
  2026. if (value is string[] strArray)
  2027. {
  2028. return string.Join("\n", strArray);
  2029. }
  2030. Logger.Send(LogType.Error, "", $"Attempt to convert an object which is not a string array: {value}.");
  2031. return null;
  2032. }
  2033. object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  2034. {
  2035. return value;
  2036. }
  2037. }
  2038. #endregion
  2039. [Serializable]
  2040. class DynamicGridDragFormat
  2041. {
  2042. private string entity;
  2043. public DataTable Table { get; set; }
  2044. public Type Entity { get => CoreUtils.GetEntity(entity); set => entity = value.EntityName(); }
  2045. public DynamicGridDragFormat(DataTable table, Type entity)
  2046. {
  2047. Table = table;
  2048. Entity = entity;
  2049. }
  2050. }