DynamicGrid.cs 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512
  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 && column is DynamicGridColumn col)
  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. reloadColumns = reloadColumns || UIComponent.OptionsChanged();
  550. if(reloadColumns && IsReady)
  551. {
  552. Refresh(true, false);
  553. }
  554. }
  555. public bool IsDirectEditMode()
  556. {
  557. return Options.DirectEdit
  558. && (Settings.ViewMode == DynamicGridSettings.DynamicGridViewMode.DirectEdit
  559. || Settings.ViewMode == DynamicGridSettings.DynamicGridViewMode.Default);
  560. }
  561. private void SwitchView_Click(object sender, RoutedEventArgs e)
  562. {
  563. Settings.ViewMode = Settings.ViewMode switch
  564. {
  565. DynamicGridSettings.DynamicGridViewMode.Default => DynamicGridSettings.DynamicGridViewMode.Normal,
  566. DynamicGridSettings.DynamicGridViewMode.Normal => DynamicGridSettings.DynamicGridViewMode.DirectEdit,
  567. DynamicGridSettings.DynamicGridViewMode.DirectEdit or _ => DynamicGridSettings.DynamicGridViewMode.Normal
  568. };
  569. SaveSettings(Settings);
  570. Reconfigure();
  571. }
  572. public DynamicGridOptions Options { get; }
  573. protected void OnReconfigureEvent(DynamicGridOptions options)
  574. {
  575. OnReconfigure?.Invoke(options);
  576. }
  577. /// <summary>
  578. /// Configure custom buttons and options.
  579. /// </summary>
  580. public void Reconfigure(DynamicGridOptions options)
  581. {
  582. options.BeginUpdate().Clear();
  583. DoReconfigure(options);
  584. OnReconfigureEvent(options);
  585. options.EndUpdate();
  586. if (!_hasLoadedOptions)
  587. {
  588. _hasLoadedOptions = true;
  589. OptionsChanged();
  590. }
  591. }
  592. public void Reconfigure()
  593. {
  594. Reconfigure(Options);
  595. }
  596. public void Reconfigure(ReconfigureEvent onReconfigure)
  597. {
  598. OnReconfigure += onReconfigure;
  599. Reconfigure();
  600. }
  601. #endregion
  602. protected virtual DynamicGridSettings LoadSettings()
  603. {
  604. return new DynamicGridSettings();
  605. }
  606. protected virtual void SaveSettings(DynamicGridSettings settings)
  607. {
  608. }
  609. protected virtual void LoadColumnsMenu(ContextMenu menu)
  610. {
  611. }
  612. protected void UpdateCell(int row, string colname, object? value)
  613. {
  614. var coreRow = Data.Rows[row];
  615. coreRow[colname] = value;
  616. UIComponent.UpdateCell(coreRow, colname, value);
  617. }
  618. private void EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  619. {
  620. OnAfterEditorValueChanged(null, [obj], new AfterEditorValueChangedArgs(changedColumn, changes), changes);
  621. SaveItem(obj);
  622. foreach (var (key, value) in changes)
  623. {
  624. row[key] = value;
  625. }
  626. UIComponent.UpdateRow(row);
  627. }
  628. #region Row Selections
  629. protected CoreRow[] GetVisibleRows()
  630. {
  631. return UIComponent.GetVisibleRows();
  632. }
  633. public CoreRow[] SelectedRows
  634. {
  635. get => UIComponent.SelectedRows;
  636. set => UIComponent.SelectedRows = value;
  637. }
  638. /// <summary>
  639. /// Call the <see cref="OnSelectItem"/> event, and do any updating which needs to occur when items are selected.
  640. /// </summary>
  641. /// <param name="rows"></param>
  642. protected virtual void SelectItems(CoreRow[]? rows)
  643. {
  644. if (IsReady)
  645. OnSelectItem?.Invoke(this, new DynamicGridSelectionEventArgs(rows));
  646. DuplicateBtn.Visibility =
  647. typeof(T).IsAssignableTo(typeof(IDuplicatable)) && rows != null && rows.Length >= 1 ? Visibility.Visible : Visibility.Collapsed;
  648. }
  649. protected virtual void DoDoubleClick(object sender, DynamicGridCellClickEventArgs args)
  650. {
  651. if (IsDirectEditMode())
  652. return;
  653. //SelectItems(SelectedRows);
  654. var e = new HandledEventArgs(false);
  655. OnDoubleClick?.Invoke(sender, e);
  656. if (e.Handled)
  657. return;
  658. if (Options.EditRows)
  659. DoEdit();
  660. }
  661. #endregion
  662. #region Column Handling
  663. #region Column Grouping
  664. public DynamicGridColumnGroupings ColumnGroupings { get; set; }
  665. /// <summary>
  666. /// Create a new column header group, and return it for editing.
  667. /// </summary>
  668. /// <returns></returns>
  669. public DynamicGridColumnGrouping AddColumnGrouping()
  670. {
  671. var group = new DynamicGridColumnGrouping();
  672. ColumnGroupings.Add(group);
  673. return group;
  674. }
  675. /// <summary>
  676. /// Gets the current column header group, and if there is none, create a new one.
  677. /// </summary>
  678. /// <returns></returns>
  679. public DynamicGridColumnGrouping GetColumnGrouping()
  680. {
  681. if(ColumnGroupings.Count == 0)
  682. {
  683. return AddColumnGrouping();
  684. }
  685. return ColumnGroupings[^1];
  686. }
  687. #endregion
  688. protected virtual DynamicGridColumns LoadColumns()
  689. {
  690. return GenerateColumns();
  691. }
  692. /// <summary>
  693. /// Provide a set of columns which is the default for this grid.
  694. /// </summary>
  695. public virtual DynamicGridColumns GenerateColumns()
  696. {
  697. var columns = new DynamicGridColumns();
  698. var cols = IsDirectEditMode()
  699. ? new Columns<T>(ColumnTypeFlags.IncludeVisible | ColumnTypeFlags.IncludeForeignKeys)
  700. : new Columns<T>(ColumnTypeFlags.IncludeVisible | ColumnTypeFlags.IncludeLinked);
  701. foreach (var col in cols)
  702. {
  703. var mc = MasterColumns.FirstOrDefault(x => x.ColumnName.Equals(col.Property));
  704. if (mc != null && mc.Editor is not NullEditor && mc.Editor.Visible != Visible.Hidden)
  705. columns.Add(mc);
  706. }
  707. return columns;
  708. }
  709. private bool SwapRows(int row1, int row2)
  710. {
  711. CoreRow[] rows = Data.Rows.Where(x => x.Index.Equals(row1) || x.Index.Equals(row2)).ToArray();
  712. var items = LoadItems(rows);
  713. var first = (items.First() as ISequenceable)!;
  714. var last = (items.Last() as ISequenceable)!;
  715. var iBuf1 = first.Sequence;
  716. var iBuf2 = last.Sequence;
  717. first.Sequence = iBuf2;
  718. last.Sequence = iBuf1;
  719. SaveItems(items);
  720. return true;
  721. }
  722. protected virtual void SaveColumns(DynamicGridColumns columns)
  723. {
  724. }
  725. public int DesiredWidth()
  726. {
  727. return UIComponent.DesiredWidth();
  728. }
  729. /// <summary>
  730. /// Handle to configure column groups.
  731. /// </summary>
  732. /// <remarks>
  733. /// This is called after <see cref="LoadColumns"/>, so by the time this is called, both <see cref="VisibleColumns"/>
  734. /// and <see cref="ActionColumns"/> will be loaded, which means one can reference these in the column groups.
  735. /// <br/>
  736. /// <b>Note:</b> <see cref="ColumnGroupings"/> is cleared before this function is called.
  737. /// </remarks>
  738. protected virtual void ConfigureColumnGroups()
  739. {
  740. }
  741. protected virtual void ConfigureColumns(DynamicGridColumns columns)
  742. {
  743. }
  744. private void ReloadColumns()
  745. {
  746. ConfigureColumns(MasterColumns);
  747. VisibleColumns = LoadColumns();
  748. ConfigureColumns(VisibleColumns);
  749. ColumnGroupings.Clear();
  750. ConfigureColumnGroups();
  751. UIComponent.RefreshColumns(VisibleColumns, ActionColumns, ColumnGroupings);
  752. }
  753. #endregion
  754. #region Refresh / Reload
  755. protected abstract void Reload(
  756. Filters<T> criteria, Columns<T> columns, ref SortOrder<T>? sort,
  757. CancellationToken token, Action<CoreTable?, Exception?> action);
  758. public Filter<T>? DefineFilter()
  759. {
  760. if (OnDefineFilter is null)
  761. return null;
  762. var result = OnDefineFilter.Invoke(typeof(T)) as Filter<T>;
  763. return result;
  764. }
  765. protected virtual bool FilterRecord(CoreRow row)
  766. {
  767. var bOK = ActionColumns.All(x =>
  768. {
  769. return x.FilterRecord is null
  770. || ((x.SelectedFilters is null || x.SelectedFilters.Length == 0 || x.FilterRecord.Invoke(row, x.SelectedFilters))
  771. && (x.ExcludeFilters is null || x.ExcludeFilters.Length == 0 || !x.FilterRecord.Invoke(row, x.ExcludeFilters)));
  772. });
  773. if (bOK && OnFilterRecord is not null)
  774. bOK = OnFilterRecord(row);
  775. return bOK;
  776. }
  777. public IEnumerable<TType> ExtractValues<TType>(Expression<Func<T, TType>> column, Selection selection)
  778. {
  779. var result = selection == Selection.None
  780. ? Enumerable.Empty<TType>()
  781. : selection == Selection.Selected
  782. ? SelectedRows.Select(r => r.Get(column))
  783. : Data.ExtractValues(column);
  784. return result;
  785. }
  786. private class RowRange(int rowIdx, int size)
  787. {
  788. public int RowIdx { get; set; } = rowIdx;
  789. public int Size { get; set; } = size;
  790. }
  791. private CancellationTokenSource? RefreshCancellationToken;
  792. public virtual void Refresh(bool reloadcolumns, bool reloaddata)
  793. {
  794. if (bRefreshing)
  795. return;
  796. if (!DoBeforeRefresh())
  797. return;
  798. UIComponent.BeforeRefresh();
  799. var cursor = UseWaitCursor ? new WaitCursor() : null;
  800. Loading.Visibility = Visibility.Visible;
  801. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  802. bRefreshing = true;
  803. if (reloadcolumns)
  804. ReloadColumns();
  805. if (reloaddata)
  806. {
  807. _lookupcache.Clear();
  808. var criteria = new Filters<T>();
  809. var filter = DefineFilter();
  810. if (filter != null)
  811. criteria.Add(filter);
  812. var columns = DataColumns();
  813. var sort = LookupFactory.DefineSort<T>();
  814. if (sort == null && IsSequenced)
  815. sort = new SortOrder<T>("Sequence");
  816. RefreshCancellationToken?.Cancel();
  817. var tokenSource = new CancellationTokenSource();
  818. RefreshCancellationToken = tokenSource;
  819. var token = tokenSource.Token;
  820. Reload(
  821. criteria, columns, ref sort,
  822. token,
  823. (table, exception) =>
  824. {
  825. if(token.IsCancellationRequested) return; // Don't bother even checking exceptions if task was cancelled.
  826. if (exception != null)
  827. {
  828. Dispatcher.Invoke(() =>
  829. {
  830. MessageWindow.ShowError("Sorry! We couldn't load the data.", exception);
  831. });
  832. }
  833. else if (table is not null)
  834. {
  835. if(table.Offset == 0 || MasterData is null)
  836. {
  837. MasterData = table;
  838. Dispatcher.Invoke(() =>
  839. {
  840. ProcessData(null);
  841. DoAfterRefresh();
  842. bRefreshing = false;
  843. IsReady = true;
  844. });
  845. }
  846. else
  847. {
  848. int idx = MasterData.Rows.Count;
  849. MasterData.AddPage(table);
  850. Dispatcher.Invoke(() =>
  851. {
  852. ProcessData(new(idx, table.Rows.Count));
  853. });
  854. }
  855. }
  856. }
  857. );
  858. }
  859. else
  860. {
  861. ProcessData(null);
  862. DoAfterRefresh();
  863. bRefreshing = false;
  864. IsReady = true;
  865. Loading.BeginAnimation(Label.OpacityProperty, null);
  866. Loading.Visibility = Visibility.Collapsed;
  867. }
  868. if (cursor != null)
  869. {
  870. cursor.Dispose();
  871. cursor = null;
  872. }
  873. }
  874. public void Shutdown()
  875. {
  876. RefreshCancellationToken?.Cancel();
  877. }
  878. protected void NotifyBeforeRefresh(BeforeRefreshEventArgs args) => BeforeRefresh?.Invoke(this, args);
  879. protected void NotifyAfterRefresh(AfterRefreshEventArgs args) => AfterRefresh?.Invoke(this, args);
  880. protected bool OnBeforeRefresh()
  881. {
  882. return true;
  883. }
  884. private bool DoBeforeRefresh()
  885. {
  886. var result = OnBeforeRefresh();
  887. if (result)
  888. {
  889. var args = new BeforeRefreshEventArgs() { Cancel = false };
  890. NotifyBeforeRefresh(args);
  891. result = args.Cancel == false;
  892. }
  893. return result;
  894. }
  895. protected virtual void OnAfterRefresh()
  896. {
  897. }
  898. protected void DoAfterRefresh()
  899. {
  900. OnAfterRefresh();
  901. NotifyAfterRefresh(new AfterRefreshEventArgs());
  902. }
  903. public Columns<T> DataColumns()
  904. {
  905. var columns = Columns.None<T>();
  906. foreach (var column in VisibleColumns)
  907. columns.Add(column.ColumnName);
  908. foreach (var column in HiddenColumns.ColumnNames)
  909. columns.Add(new Column<T>(column));
  910. return columns;
  911. }
  912. /// <summary>
  913. /// Process the data from <see cref="MasterData"/> according to <paramref name="range"/>.
  914. /// </summary>
  915. /// <remarks>
  916. /// 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,
  917. /// clearing all current rows, resetting columns, selection, etc. If the <paramref name="range"/> is provided, this will add to the grid the rows
  918. /// according to the range from <see cref="MasterData"/>.
  919. /// </remarks>
  920. /// <param name="initialLoad"></param>
  921. private void ProcessData(RowRange? range)
  922. {
  923. if(range is null)
  924. {
  925. Data.Columns.Clear();
  926. Data.Setters.Clear();
  927. if (MasterData != null)
  928. foreach (var column in MasterData.Columns)
  929. Data.Columns.Add(column);
  930. }
  931. LoadData(range);
  932. }
  933. protected readonly Dictionary<CoreRow, CoreRow> _recordmap = new();
  934. public void UpdateRow<TRow, TType>(CoreRow row, Expression<Func<TRow, TType>> column, TType value, bool refresh = true)
  935. {
  936. row.Set(column, value);
  937. _recordmap[row].Set(column, value);
  938. if (refresh)
  939. InvalidateRow(row);
  940. }
  941. public void UpdateRow<TType>(CoreRow row, string column, TType value, bool refresh = true)
  942. {
  943. row.Set(column, value);
  944. _recordmap[row].Set(column, value);
  945. if (refresh)
  946. InvalidateRow(row);
  947. }
  948. public void UpdateRow(CoreRow row, T obj)
  949. {
  950. ObjectToRow(obj, row);
  951. ObjectToRow(obj, _recordmap[row]);
  952. }
  953. public void AddRow(CoreRow row)
  954. {
  955. if (MasterData is null) return;
  956. var masterrow = MasterData.NewRow();
  957. MasterData.FillRow(masterrow, row);
  958. Refresh(false, false);
  959. }
  960. public void AddRow(T data)
  961. {
  962. if (MasterData is null) return;
  963. MasterData.LoadRow(data);
  964. Refresh(false, false);
  965. }
  966. public void DeleteRow(CoreRow row)
  967. {
  968. if (MasterData is null) return;
  969. var masterrow = _recordmap[row];
  970. MasterData.Rows.Remove(masterrow);
  971. Refresh(false, false);
  972. }
  973. /// <summary>
  974. /// Filter all given rows into <paramref name="into"/>, given that they match <paramref name="filter"/> and <see cref="FilterRecord(CoreRow)"/>.
  975. /// If <paramref name="recordMap"/> is given, also updates the map from <paramref name="from"/> to <paramref name="into"/>.
  976. /// </summary>
  977. private IList<CoreRow> FilterRows(
  978. IEnumerable<CoreRow> from,
  979. CoreTable into,
  980. Dictionary<CoreRow, CoreRow>? recordMap = null,
  981. Func<CoreRow, bool>? filter = null)
  982. {
  983. var newRows = new List<CoreRow>();
  984. foreach (var row in from)
  985. if (FilterRecord(row) && filter?.Invoke(row) != false)
  986. {
  987. var newrow = into.NewRow();
  988. for (var i = 0; i < into.Columns.Count; i++)
  989. {
  990. var value = i < row.Values.Count ? row.Values[i] : null;
  991. if (into.Columns[i].DataType.IsNumeric())
  992. value = into.Columns[i].DataType.IsDefault(value) ? null : value;
  993. newrow.Values.Add(value);
  994. }
  995. newRows.Add(newrow);
  996. into.Rows.Add(newrow);
  997. recordMap?.TryAdd(newrow, row);
  998. }
  999. return newRows;
  1000. }
  1001. private readonly SemaphoreSlim semaphore = new(1,1);
  1002. private void LoadData(RowRange? range)
  1003. {
  1004. if (MasterData is null)
  1005. return;
  1006. if(range is null)
  1007. {
  1008. ResetClipBuffer();
  1009. Data.Rows.Clear();
  1010. _recordmap.Clear();
  1011. FilterRows(MasterData.Rows, Data, _recordmap);
  1012. InvalidateGrid();
  1013. SelectedRows = Array.Empty<CoreRow>();
  1014. }
  1015. else
  1016. {
  1017. var _newRows = FilterRows(Enumerable.Range(range.RowIdx, range.Size).Select(i => MasterData.Rows[i]), Data, _recordmap);
  1018. UIComponent.AddPage(_newRows);
  1019. /*
  1020. semaphore.Wait();
  1021. try
  1022. {
  1023. // This throws errors when overalpping refreshes cause a mismatch between MasterData and range
  1024. // Using try/finally and a Semaphore as a temporary measure until we can isolate the issue
  1025. var _newRows = FilterRows(Enumerable.Range(range.RowIdx, range.Size).Select(i => MasterData.Rows[i]), Data, _recordmap);
  1026. UIComponent.AddPage(_newRows);
  1027. }
  1028. finally
  1029. {
  1030. semaphore.Release();
  1031. }*/
  1032. }
  1033. }
  1034. //IncrementalList<T> _data = null;
  1035. public void InvalidateRow(CoreRow row)
  1036. {
  1037. UIComponent.InvalidateRow(row);
  1038. }
  1039. protected void InvalidateGrid()
  1040. {
  1041. if (RowStyleSelector != null)
  1042. RowStyleSelector.Data = Data;
  1043. UIComponent.RefreshData(Data);
  1044. Loading.BeginAnimation(Label.OpacityProperty, null);
  1045. Loading.Visibility = Visibility.Collapsed;
  1046. }
  1047. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  1048. {
  1049. UIComponent.AddVisualFilter(column, value, filtertype);
  1050. }
  1051. protected List<Tuple<string, Func<CoreRow, bool>>> GetFilterPredicates()
  1052. {
  1053. return UIComponent.GetFilterPredicates();
  1054. }
  1055. #endregion
  1056. #region Item Manipulation
  1057. #region Load/Save/Delete
  1058. public virtual T[] LoadItems(CoreRow[] rows)
  1059. {
  1060. return rows.ToArray(LoadItem);
  1061. }
  1062. public abstract T LoadItem(CoreRow row);
  1063. public abstract void SaveItem(T item);
  1064. public virtual void SaveItems(T[] items)
  1065. {
  1066. foreach (var item in items)
  1067. SaveItem(item);
  1068. }
  1069. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  1070. {
  1071. return true;
  1072. }
  1073. public abstract void DeleteItems(params CoreRow[] rows);
  1074. protected virtual void DoDelete()
  1075. {
  1076. var rows = SelectedRows.ToArray();
  1077. if (rows.Any())
  1078. if (CanDeleteItems(rows))
  1079. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1080. MessageBoxResult.Yes)
  1081. {
  1082. DeleteItems(rows);
  1083. SelectedRows = Array.Empty<CoreRow>();
  1084. OnChanged?.Invoke(this, EventArgs.Empty);
  1085. Refresh(false, true);
  1086. SelectItems(null);
  1087. }
  1088. }
  1089. private void Delete_Click(object sender, RoutedEventArgs e)
  1090. {
  1091. DoDelete();
  1092. }
  1093. #endregion
  1094. #region Edit
  1095. protected virtual void DoEdit()
  1096. {
  1097. if (SelectedRows.Length == 0)
  1098. return;
  1099. if (AddEditClick(SelectedRows))
  1100. {
  1101. SelectItems(SelectedRows);
  1102. }
  1103. }
  1104. private void Edit_Click(object sender, RoutedEventArgs e)
  1105. {
  1106. DoEdit();
  1107. }
  1108. protected virtual void DoAdd(bool openEditorOnDirectEdit = false)
  1109. {
  1110. //CoreRow row = (SelectedRow > -1) && (SelectedRow < Data.Rows.Count) ? Data.Rows[this.SelectedRow] : null;
  1111. if (IsDirectEditMode() && !openEditorOnDirectEdit)
  1112. {
  1113. CreateItems(null);
  1114. }
  1115. else if (AddEditClick(null))
  1116. {
  1117. Refresh(false, true);
  1118. }
  1119. }
  1120. protected void CreateItems(Func<IEnumerable<T>>? create)
  1121. {
  1122. var newRows = new List<CoreRow>();
  1123. var items = create?.Invoke() ?? CoreUtils.One(CreateItem());
  1124. foreach (var item in items)
  1125. {
  1126. if (!AfterCreate(item))
  1127. return;
  1128. SaveItem(item);
  1129. var datarow = Data.NewRow();
  1130. ObjectToRow(item, datarow);
  1131. Data.Rows.Add(datarow);
  1132. newRows.Add(datarow);
  1133. var masterrow = MasterData.NewRow();
  1134. ObjectToRow(item, masterrow);
  1135. MasterData.Rows.Add(masterrow);
  1136. _recordmap[datarow] = masterrow;
  1137. }
  1138. InvalidateGrid();
  1139. SelectedRows = newRows.ToArray();
  1140. OnChanged?.Invoke(this, EventArgs.Empty);
  1141. }
  1142. private void Add_Click(object sender, RoutedEventArgs e)
  1143. {
  1144. if (CanCreateItems())
  1145. DoAdd();
  1146. }
  1147. public virtual DynamicEditorPages LoadEditorPages(T item)
  1148. {
  1149. DynamicEditorPages pages = new DynamicEditorPages();
  1150. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  1151. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  1152. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  1153. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  1154. foreach (var page in pages)
  1155. page.Ready = false;
  1156. return pages;
  1157. }
  1158. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  1159. {
  1160. buttons.Clear();
  1161. buttons.Add(
  1162. "",
  1163. Wpf.Resources.help.AsBitmapImage(),
  1164. item,
  1165. (f, i) =>
  1166. {
  1167. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  1168. { UseShellExecute = true });
  1169. }
  1170. );
  1171. OnLoadEditorButtons?.Invoke(item, buttons);
  1172. }
  1173. protected virtual void BeforeLoad(IDynamicEditorForm form, T[] items)
  1174. {
  1175. form.BeforeLoad();
  1176. }
  1177. void IDynamicGrid.InitialiseEditorForm(IDynamicEditorForm editor, object[] items, Func<Type, CoreTable>? pageDataHandler, bool preloadPages)
  1178. {
  1179. InitialiseEditorForm(editor, items.Cast<T>().ToArray(), pageDataHandler, preloadPages);
  1180. }
  1181. public virtual bool EditItems(object[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1182. {
  1183. var values = items.Cast<T>().ToArray();
  1184. return EditItems(values, PageDataHandler, PreloadPages);
  1185. }
  1186. public virtual void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false)
  1187. {
  1188. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  1189. var buttons = new DynamicEditorButtons();
  1190. if (items.Length == 1)
  1191. LoadEditorButtons(items.First(), buttons);
  1192. editor.Setup(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, pageDataHandler, preloadPages);
  1193. editor.OnCustomiseColumns = (sender, columns) =>
  1194. {
  1195. columns.Clear();
  1196. columns.AddRange(MasterColumns);
  1197. };
  1198. editor.OnDefineEditor = (o, c) =>
  1199. {
  1200. var result = GetEditor(o, c);
  1201. if (result != null)
  1202. result = result.CloneEditor();
  1203. return result;
  1204. };
  1205. editor.OnFormCustomiseEditor += DoCustomiseEditor;
  1206. editor.OnDefineFilter = (type, column) => { return DefineLookupFilter(type, column, items); };
  1207. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  1208. editor.OnDefineLookups = editor => DefineLookups(editor, items);
  1209. editor.OnEditorValueChanged += (s, n, v) => EditorValueChanged(editor, items, n, v);
  1210. editor.OnAfterEditorValueChanged += (g, args) => AfterEditorValueChanged(g, items, args);
  1211. editor.OnReconfigureEditors = g => DoReconfigureEditors(g, items);
  1212. editor.OnValidateData += (o, i) => ValidateData(items);
  1213. editor.OnSelectPage += SelectPage;
  1214. editor.OnSaveItem = (o, e) =>
  1215. {
  1216. try
  1217. {
  1218. using var Wait = new WaitCursor();
  1219. DoBeforeSave(editor, items);
  1220. if (items.Length == 1)
  1221. editor.UnloadEditorPages(false);
  1222. foreach (var item in items)
  1223. SaveItem(item);
  1224. if (items.Length == 1)
  1225. editor.UnloadEditorPages(true);
  1226. DoAfterSave(editor, items);
  1227. }
  1228. catch (Exception err)
  1229. {
  1230. MessageBox.Show(err.Message);
  1231. e.Cancel = true;
  1232. }
  1233. };
  1234. BeforeLoad(editor, items);
  1235. editor.Items = items;
  1236. AfterLoad(editor, items);
  1237. }
  1238. private void DoCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  1239. {
  1240. CustomiseEditor((T[])items, column, editor);
  1241. OnCustomiseEditor?.Invoke(sender, (T[])items, column, editor);
  1242. }
  1243. protected virtual void CustomiseEditor(T[] items, DynamicGridColumn column, BaseEditor editor)
  1244. {
  1245. }
  1246. protected virtual void DoAfterSave(IDynamicEditorForm editor, T[] items)
  1247. {
  1248. OnAfterSave?.Invoke(editor, items);
  1249. }
  1250. protected virtual void DoBeforeSave(IDynamicEditorForm editor, T[] items)
  1251. {
  1252. OnBeforeSave?.Invoke(editor, items);
  1253. }
  1254. public virtual bool EditItems(T[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1255. {
  1256. DynamicEditorForm editor;
  1257. using (var cursor = new WaitCursor())
  1258. {
  1259. editor = new DynamicEditorForm();
  1260. editor.SetValue(Panel.ZIndexProperty, 999);
  1261. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  1262. OnEditorLoaded?.Invoke(editor, items);
  1263. }
  1264. return editor.ShowDialog() == true;
  1265. }
  1266. private Dictionary<String, object?> AfterEditorValueChanged(DynamicEditorGrid grid, T[] items, AfterEditorValueChangedArgs args)
  1267. {
  1268. var changes = new Dictionary<string, object?>();
  1269. OnAfterEditorValueChanged(grid, items, args, changes);
  1270. return changes;
  1271. }
  1272. protected virtual void OnAfterEditorValueChanged(DynamicEditorGrid? grid, T[] items, AfterEditorValueChangedArgs args, Dictionary<String, object?> changes)
  1273. {
  1274. }
  1275. protected virtual void DoReconfigureEditors(DynamicEditorGrid grid, T[] items)
  1276. {
  1277. /*if (items.First() is IDimensioned dimensioned)
  1278. {
  1279. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  1280. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  1281. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  1282. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  1283. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  1284. }*/
  1285. }
  1286. private List<string>? ValidateData(T[] items)
  1287. {
  1288. var errors = new List<string>();
  1289. DoValidate(items, errors);
  1290. OnValidate?.Invoke(this, items, errors);
  1291. return errors.Count != 0 ? errors : null;
  1292. }
  1293. protected virtual void DoValidate(T[] items, List<string> errors)
  1294. {
  1295. }
  1296. protected virtual void AfterLoad(IDynamicEditorForm editor, T[] items)
  1297. {
  1298. editor.AfterLoad();
  1299. }
  1300. protected virtual void SelectPage(object sender, BaseObject[]? items)
  1301. {
  1302. }
  1303. protected virtual Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, T[] items, string name, object value)
  1304. {
  1305. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  1306. if (OnEditorValueChanged != null)
  1307. {
  1308. var newchanges = OnEditorValueChanged(editor, name, value);
  1309. foreach (var key in newchanges.Keys)
  1310. result[key] = newchanges[key];
  1311. }
  1312. return result;
  1313. }
  1314. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  1315. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items, bool async = true)
  1316. {
  1317. if (sender.EditorDefinition is not ILookupEditor editor)
  1318. return;
  1319. var colname = sender.ColumnName;
  1320. if (async)
  1321. {
  1322. Task.Run(() =>
  1323. {
  1324. try
  1325. {
  1326. var values = editor.Values(typeof(T), colname, items);
  1327. Dispatcher.Invoke(
  1328. () =>
  1329. {
  1330. try
  1331. {
  1332. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  1333. sender.LoadLookups(values);
  1334. }
  1335. catch (Exception e2)
  1336. {
  1337. Logger.Send(LogType.Information, typeof(T).Name,
  1338. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  1339. }
  1340. }
  1341. );
  1342. }
  1343. catch (Exception e)
  1344. {
  1345. Logger.Send(LogType.Information, typeof(T).Name,
  1346. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  1347. }
  1348. });
  1349. }
  1350. else
  1351. {
  1352. var values = editor.Values(typeof(T), colname, items);
  1353. sender.LoadLookups(values);
  1354. }
  1355. }
  1356. /// <summary>
  1357. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  1358. /// </summary>
  1359. /// <param name="item">The object being edited.</param>
  1360. /// <param name="column">The column of the editor.</param>
  1361. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  1362. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  1363. {
  1364. return column.Editor ?? CoreUtils.GetProperty(item.GetType(), column.ColumnName).GetEditor();
  1365. }
  1366. protected IFilter? DefineLookupFilter(Type type, string column, T[] items)
  1367. {
  1368. return LookupFactory.DefineLookupFilter(typeof(T), type, column, items);
  1369. }
  1370. protected virtual void SetEditorValue(object item, string name, object value)
  1371. {
  1372. try
  1373. {
  1374. CoreUtils.SetPropertyValue(item, name, value);
  1375. }
  1376. catch (Exception e)
  1377. {
  1378. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1379. }
  1380. }
  1381. protected virtual object? GetEditorValue(object item, string name)
  1382. {
  1383. return CoreUtils.GetPropertyValue(item, name);
  1384. }
  1385. protected virtual bool CanCreateItems()
  1386. {
  1387. return true;
  1388. }
  1389. private bool AddEditClick(CoreRow[]? rows)
  1390. {
  1391. if (!IsEnabled || bRefreshing)
  1392. return false;
  1393. if (rows == null || rows.Length == 0)
  1394. {
  1395. if (!CanCreateItems())
  1396. return false;
  1397. var item = CreateItem();
  1398. if (!AfterCreate(item))
  1399. return false;
  1400. // Yea, and this won't work, because we're actually usually showing the description of a linked item,
  1401. // not the id of the link, and we need to set the ID to have it work properly :-(
  1402. //foreach (String key in VisualFilters.Keys)
  1403. // CoreUtils.SetPropertyValue(item, key, VisualFilters[key]);
  1404. if (EditItems([item]))
  1405. {
  1406. //_CurrentRow = Data.Rows.Count;
  1407. var row = Data.NewRow();
  1408. ObjectToRow(item, row);
  1409. Data.Rows.Add(row);
  1410. InvalidateGrid();
  1411. SelectedRows = [row];
  1412. DoChanged();
  1413. return true;
  1414. }
  1415. return false;
  1416. }
  1417. var items = Array.Empty<T>();
  1418. using (new WaitCursor())
  1419. {
  1420. Stopwatch sw = new Stopwatch();
  1421. sw.Start();
  1422. items = LoadItems(rows);
  1423. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  1424. sw.Stop();
  1425. }
  1426. if (items.Length != 0)
  1427. {
  1428. var snaps = items.ToArray(x => x.TakeSnapshot());
  1429. if (EditItems(items))
  1430. {
  1431. var sel = SelectedRows;
  1432. for (var i = 0; i < items.Length; i++)
  1433. UpdateRow(rows[i], items[i]);
  1434. InvalidateGrid();
  1435. SelectedRows = sel;
  1436. DoChanged();
  1437. return true;
  1438. }
  1439. else
  1440. {
  1441. foreach(var snap in snaps)
  1442. {
  1443. snap.ResetObject();
  1444. }
  1445. }
  1446. return false;
  1447. }
  1448. return false;
  1449. }
  1450. #endregion
  1451. #region Duplicate
  1452. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  1453. {
  1454. return LoadItems(rows);
  1455. }
  1456. private bool DoDuplicate(Button button, CoreRow[] rows)
  1457. {
  1458. if (!rows.Any())
  1459. {
  1460. MessageBox.Show("Please select at least one record to duplicate!");
  1461. return false;
  1462. }
  1463. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  1464. if (!ids.Any())
  1465. {
  1466. MessageBox.Show("Please select at least one record to duplicate!");
  1467. return false;
  1468. }*/
  1469. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  1470. if (duplicator is null)
  1471. {
  1472. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  1473. return false;
  1474. }
  1475. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  1476. return true;
  1477. }
  1478. #endregion
  1479. public virtual T CreateItem()
  1480. {
  1481. var result = new T();
  1482. OnCreateItem?.Invoke(this, result);
  1483. return result;
  1484. }
  1485. public virtual bool AfterCreate(T item)
  1486. {
  1487. return OnAfterCreateItem?.Invoke(this, item) ?? true;
  1488. }
  1489. protected virtual void DoPrint(object sender)
  1490. {
  1491. OnPrintData?.Invoke(sender);
  1492. }
  1493. protected virtual void ShowHelp(string slug)
  1494. {
  1495. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  1496. }
  1497. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(IDynamicEditorForm editor, TTargetType item,
  1498. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  1499. where TTargetType : Entity, new()
  1500. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  1501. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  1502. {
  1503. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  1504. var page =
  1505. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  1506. if (page != null && item != null)
  1507. {
  1508. if (!page.Ready)
  1509. page.Load(item, null);
  1510. CoreTable table;
  1511. if (sourceid == Guid.Empty)
  1512. {
  1513. table = new CoreTable();
  1514. table.LoadColumns(typeof(TSourceForm));
  1515. }
  1516. else
  1517. {
  1518. table = new Client<TSourceForm>().Query(
  1519. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  1520. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  1521. );
  1522. }
  1523. var newforms = new List<TTargetForm>();
  1524. foreach (var row in table.Rows)
  1525. {
  1526. var sourceform = row.ToObject<TSourceForm>();
  1527. var targetform = new TTargetForm();
  1528. targetform.Form.ID = sourceform.Form.ID;
  1529. targetform.Form.Synchronise(sourceform.Form);
  1530. newforms.Add(targetform);
  1531. }
  1532. page.Items.Clear();
  1533. page.LoadItems(newforms.ToArray());
  1534. }
  1535. }
  1536. #region ClipBuffer
  1537. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  1538. protected void ResetClipBuffer()
  1539. {
  1540. ClipBuffer = null;
  1541. }
  1542. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  1543. {
  1544. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  1545. }
  1546. private void CutToClipBuffer()
  1547. {
  1548. SetClipBuffer(ClipAction.Cut, SelectedRows);
  1549. InvalidateGrid();
  1550. }
  1551. private void CopyToClipBuffer()
  1552. {
  1553. SetClipBuffer(ClipAction.Copy, SelectedRows);
  1554. InvalidateGrid();
  1555. }
  1556. private void PasteFromClipBuffer()
  1557. {
  1558. if (ClipBuffer == null)
  1559. return;
  1560. if (!ShowSequenceButtons)
  1561. return;
  1562. using (new WaitCursor())
  1563. {
  1564. var updates = ClipBuffer.Item2.Select(x => x.ToObject<T>()).ToList();
  1565. if (BeforePaste(updates, ClipBuffer.Item1))
  1566. {
  1567. var currow = SelectedRows.FirstOrDefault()
  1568. ?? Data.Rows.LastOrDefault();
  1569. var sequence = currow != null ? currow.Get<T, long>(c => ((ISequenceable)c).Sequence) : 0;
  1570. var postrows = Data.Rows.Where(r => !ClipBuffer.Item2.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  1571. updates.AddRange(LoadItems(postrows.ToArray()));
  1572. foreach (var update in updates)
  1573. {
  1574. sequence++;
  1575. ((ISequenceable)update).Sequence = sequence;
  1576. }
  1577. }
  1578. if (updates.Any())
  1579. {
  1580. SaveItems(updates.ToArray());
  1581. Refresh(false, true);
  1582. }
  1583. }
  1584. }
  1585. protected virtual bool BeforePaste(IEnumerable<T> items, ClipAction action)
  1586. {
  1587. return true;
  1588. }
  1589. private void Cut_Click(object sender, RoutedEventArgs e)
  1590. {
  1591. CutToClipBuffer();
  1592. }
  1593. private void Copy_Click(object sender, RoutedEventArgs e)
  1594. {
  1595. CopyToClipBuffer();
  1596. }
  1597. private void Paste_Click(object sender, RoutedEventArgs e)
  1598. {
  1599. PasteFromClipBuffer();
  1600. }
  1601. #endregion
  1602. protected virtual void ObjectToRow(T obj, CoreRow row)
  1603. {
  1604. row.Table.FillRow(row, obj);
  1605. }
  1606. #region Import / Export
  1607. protected virtual CoreTable LoadImportKeys(String[] fields)
  1608. {
  1609. var result = new CoreTable();
  1610. result.LoadColumns(Columns.None<T>().Add(fields));
  1611. return result;
  1612. }
  1613. protected virtual Guid GetImportID()
  1614. {
  1615. return Guid.Empty;
  1616. }
  1617. protected virtual bool CustomiseImportItem(T item)
  1618. {
  1619. if (IsSequenced)
  1620. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  1621. return true;
  1622. }
  1623. protected virtual string CustomiseImportFileName(string filename)
  1624. {
  1625. return filename;
  1626. }
  1627. protected virtual void DoImport()
  1628. {
  1629. var list = new DynamicImportList(
  1630. typeof(T),
  1631. GetImportID()
  1632. );
  1633. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  1634. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  1635. list.OnSave += (sender, entity) => SaveItem(entity as T);
  1636. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  1637. list.ShowDialog();
  1638. Refresh(false, true);
  1639. }
  1640. private void Import_Click(object sender, RoutedEventArgs e)
  1641. {
  1642. DoImport();
  1643. }
  1644. protected virtual void CustomiseExportColumns(List<string> columnnames)
  1645. {
  1646. }
  1647. protected virtual string CustomiseExportFileName(string filename)
  1648. {
  1649. return filename;
  1650. }
  1651. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  1652. {
  1653. }
  1654. protected virtual void ApplyExportFilter(CoreTable table, object data)
  1655. {
  1656. }
  1657. protected virtual void DoExport()
  1658. {
  1659. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  1660. CustomiseExportColumns(columnnames);
  1661. var form = new DynamicExportForm(typeof(T), columnnames);
  1662. if (form.ShowDialog() != true)
  1663. return;
  1664. var filters = new Filters<T>();
  1665. filters.Add(DefineFilter());
  1666. var predicates = UIComponent.GetFilterPredicates();
  1667. var visiblerows = GetVisibleRows();
  1668. CustomiseExportFilters(filters, visiblerows);
  1669. var columns = Columns.None<T>().Add(form.Fields);
  1670. var otherColumns = form.GetChildFields()
  1671. .Select(x => new Tuple<Type, IColumns>(
  1672. x.Key,
  1673. Columns.None(x.Key).Add(x.Value)))
  1674. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  1675. var reloadColumns = Columns.None<T>();
  1676. foreach (var column in columns)
  1677. {
  1678. reloadColumns.Add(column);
  1679. }
  1680. foreach (var column in HiddenColumns.ColumnNames)
  1681. {
  1682. reloadColumns.Add(column);
  1683. }
  1684. foreach (var (column, _) in predicates)
  1685. {
  1686. reloadColumns.Add(column);
  1687. }
  1688. var sort = LookupFactory.DefineSort<T>();
  1689. Reload(filters, reloadColumns, ref sort, CancellationToken.None, (data, err) => Dispatcher.Invoke(() =>
  1690. {
  1691. if (data is not null)
  1692. {
  1693. var newData = new CoreTable();
  1694. newData.LoadColumns(columns);
  1695. FilterRows(data.Rows, newData, filter: row =>
  1696. {
  1697. foreach(var (_, predicate) in predicates)
  1698. {
  1699. if (!predicate(row))
  1700. {
  1701. return false;
  1702. }
  1703. }
  1704. return true;
  1705. });
  1706. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  1707. list.AddRange(LoadExportTables(filters, otherColumns));
  1708. DoExportTables(list);
  1709. }
  1710. else if (err is not null)
  1711. {
  1712. Logger.Send(LogType.Error, "", $"Error in export: {CoreUtils.FormatException(err)}");
  1713. MessageBox.Show(err.Message);
  1714. }
  1715. }));
  1716. }
  1717. private void Export_Click(object sender, RoutedEventArgs e)
  1718. {
  1719. DoExport();
  1720. }
  1721. /// <summary>
  1722. /// Loads the child tables for an export, based on the filter of the parent table.
  1723. /// </summary>
  1724. /// <remarks>
  1725. /// If not overriden, defaults to creating empty tables with no records.
  1726. /// </remarks>
  1727. /// <param name="filter">Filter for the parent table.</param>
  1728. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  1729. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  1730. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  1731. {
  1732. return tableColumns.Select(x =>
  1733. {
  1734. var table = new CoreTable();
  1735. table.LoadColumns(x.Item2);
  1736. return new Tuple<Type?, CoreTable>(x.Item1, table);
  1737. });
  1738. }
  1739. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  1740. {
  1741. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  1742. ExcelExporter.DoExport(data, filename);
  1743. }
  1744. #endregion
  1745. public void ScrollIntoView(CoreRow row)
  1746. {
  1747. UIComponent.ScrollIntoView(row);
  1748. }
  1749. #endregion
  1750. #region Custom Buttons
  1751. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  1752. {
  1753. var button = new Button();
  1754. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  1755. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  1756. button.Height = 30;
  1757. UpdateButton(button, image, text, tooltip);
  1758. return button;
  1759. }
  1760. public void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  1761. {
  1762. var stackPnl = new StackPanel();
  1763. stackPnl.Orientation = Orientation.Horizontal;
  1764. //stackPnl.Margin = new Thickness(2);
  1765. if (image != null)
  1766. {
  1767. var img = new Image();
  1768. img.Source = image;
  1769. img.Margin = new Thickness(2);
  1770. img.ToolTip = tooltip;
  1771. stackPnl.Children.Add(img);
  1772. }
  1773. if (!string.IsNullOrEmpty(text))
  1774. {
  1775. button.MaxWidth = double.MaxValue;
  1776. var lbl = new Label();
  1777. lbl.Content = text;
  1778. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  1779. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  1780. lbl.Margin = new Thickness(2, 0, 5, 0);
  1781. lbl.ToolTip = ToolTip;
  1782. stackPnl.Children.Add(lbl);
  1783. }
  1784. else
  1785. button.MaxWidth = 30;
  1786. button.Content = stackPnl;
  1787. button.ToolTip = tooltip;
  1788. }
  1789. private bool bFirstButtonAdded = true;
  1790. private bool AnyButtonsVisible()
  1791. {
  1792. if (Add.Visibility != Visibility.Collapsed)
  1793. return true;
  1794. if (Edit.Visibility != Visibility.Collapsed)
  1795. return true;
  1796. /*if (MultiEdit.Visibility != Visibility.Collapsed)
  1797. return true;*/
  1798. if (Export.Visibility != Visibility.Collapsed)
  1799. return true;
  1800. return false;
  1801. }
  1802. public Button AddButton(string? caption, BitmapImage? image, string? tooltip, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1803. {
  1804. var button = CreateButton(image, caption, tooltip);
  1805. button.Margin = position == DynamicGridButtonPosition.Right
  1806. ? new Thickness(2, 2, 0, 0)
  1807. : bFirstButtonAdded && AnyButtonsVisible()
  1808. ? new Thickness(0, 2, 0, 0)
  1809. : new Thickness(0, 2, 2, 0);
  1810. button.Padding = !String.IsNullOrWhiteSpace(caption) ? new Thickness(5, 1, 5, 1) : new Thickness(1);
  1811. button.Tag = action;
  1812. button.Click += Button_Click;
  1813. if (position == DynamicGridButtonPosition.Right)
  1814. RightButtonStack.Children.Add(button);
  1815. else
  1816. LeftButtonStack.Children.Add(button);
  1817. bFirstButtonAdded = false;
  1818. return button;
  1819. }
  1820. public Button AddButton(string? caption, BitmapImage? image, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1821. {
  1822. var result = AddButton(caption, image, null, action, position);
  1823. return result;
  1824. }
  1825. private void Button_Click(object sender, RoutedEventArgs e)
  1826. {
  1827. var button = (Button)sender;
  1828. var action = (DynamicGridButtonClickEvent)button.Tag;
  1829. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  1830. if (action.Invoke(button, SelectedRows))
  1831. Refresh(false, true);
  1832. }
  1833. #endregion
  1834. #region Header Actions
  1835. private void SelectColumnsClick()
  1836. {
  1837. var editor = new DynamicGridColumnsEditor(typeof(T));
  1838. editor.DirectEdit = IsDirectEditMode();
  1839. editor.Columns.AddRange(VisibleColumns);
  1840. if (editor.ShowDialog().Equals(true))
  1841. {
  1842. VisibleColumns.Clear();
  1843. VisibleColumns.AddRange(editor.Columns);
  1844. SaveColumns(editor.Columns);
  1845. //OnSaveColumns?.Invoke(this, editor.Columns);
  1846. Refresh(true, true);
  1847. }
  1848. }
  1849. #endregion
  1850. #region Drag + Drop
  1851. /// <summary>
  1852. /// Handle a number of rows from a different <see cref="DynamicGrid{T}"/> being dragged into this one.
  1853. /// </summary>
  1854. /// <param name="entity">The type of entity that that the rows of <paramref name="table"/> represent.</param>
  1855. /// <param name="table">The data being dragged.</param>
  1856. /// <param name="e"></param>
  1857. protected virtual void OnDragEnd(Type entity, CoreTable table, DragEventArgs e)
  1858. {
  1859. Logger.Send(LogType.Information,"","OnDragEnd");
  1860. }
  1861. /// <summary>
  1862. /// Handle all types of items being dragged onto this grid that aren't handled by <see cref="OnDragEnd(Type, CoreTable, DragEventArgs)"/>,
  1863. /// i.e., data which is not a <see cref="CoreTable"/> from another <see cref="DynamicGrid{T}"/>
  1864. /// </summary>
  1865. /// <remarks>
  1866. /// Can be used to handle files, for example.
  1867. /// </remarks>
  1868. /// <param name="sender"></param>
  1869. /// <param name="e"></param>
  1870. protected virtual void HandleDragDrop(object sender, DragEventArgs e)
  1871. {
  1872. }
  1873. protected virtual void HandleDragOver(object sender, DragEventArgs e)
  1874. {
  1875. }
  1876. protected DragDropEffects DragTable(Type entity, CoreTable table)
  1877. {
  1878. Logger.Send(LogType.Information, "", "DragTable");
  1879. var data = new DataObject();
  1880. data.SetData(DynamicGridUtils.DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  1881. var effect = DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  1882. return effect;
  1883. }
  1884. protected virtual DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1885. {
  1886. Logger.Send(LogType.Information, "", "OnRowsDragStart");
  1887. var table = new CoreTable();
  1888. table.LoadColumns(Data.Columns);
  1889. table.LoadRows(rows);
  1890. return DragTable(typeof(T), table);
  1891. }
  1892. #endregion
  1893. }
  1894. #region Styling
  1895. public class DynamicGridRowStyle : DynamicGridStyle<VirtualizingCellsControl>
  1896. {
  1897. public DynamicGridRowStyle() : base(null)
  1898. {
  1899. }
  1900. public DynamicGridRowStyle(IDynamicGridStyle source) : base(source)
  1901. {
  1902. }
  1903. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1904. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1905. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1906. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1907. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1908. }
  1909. public class DynamicGridCellStyle : DynamicGridStyle<Control>
  1910. {
  1911. public DynamicGridCellStyle() : base(null)
  1912. {
  1913. }
  1914. public DynamicGridCellStyle(IDynamicGridStyle source) : base(source)
  1915. {
  1916. }
  1917. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1918. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1919. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1920. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1921. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1922. }
  1923. public class GridSelectionControllerExt : GridSelectionController
  1924. {
  1925. public GridSelectionControllerExt(SfDataGrid datagrid)
  1926. : base(datagrid)
  1927. {
  1928. }
  1929. protected override void ProcessSelectedItemChanged(SelectionPropertyChangedHandlerArgs handle)
  1930. {
  1931. base.ProcessSelectedItemChanged(handle);
  1932. if (handle.NewValue != null)
  1933. {
  1934. //this.DataGrid.ScrollInView(this.CurrentCellManager.CurrentRowColumnIndex);
  1935. //int rowIndex = this.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
  1936. var columnIndex = CurrentCellManager.CurrentRowColumnIndex.ColumnIndex;
  1937. var scrollRowIndex = DataGrid.GetVisualContainer().ScrollRows.LastBodyVisibleLineIndex;
  1938. DataGrid.ScrollInView(new RowColumnIndex(scrollRowIndex, columnIndex));
  1939. }
  1940. }
  1941. }
  1942. // Used to render boolean columns (the default "false" value shows what appears to be an intermediate state, which is ugly
  1943. // This should show nothing for false, and a tick in a box for true
  1944. public class BoolToImageConverter : AbstractConverter<bool,ImageSource>
  1945. {
  1946. public ImageSource TrueValue { get; set; }
  1947. public ImageSource FalseValue { get; set; }
  1948. public BoolToImageConverter()
  1949. {
  1950. TrueValue = Wpf.Resources.Bullet_Tick.AsBitmapImage();
  1951. }
  1952. public override ImageSource Convert(bool value)
  1953. {
  1954. return value ? TrueValue : FalseValue;
  1955. }
  1956. public override bool Deconvert(ImageSource value)
  1957. {
  1958. return ImageUtils.IsEqual(value as BitmapImage,TrueValue as BitmapImage);
  1959. }
  1960. }
  1961. public class StringToColorImageConverter : IValueConverter
  1962. {
  1963. private readonly int _height = 50;
  1964. private readonly int _width = 25;
  1965. private readonly Dictionary<string, BitmapImage> cache = new();
  1966. public StringToColorImageConverter(int width, int height)
  1967. {
  1968. _width = width;
  1969. _height = height;
  1970. }
  1971. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1972. {
  1973. var str = value?.ToString();
  1974. if (str is null)
  1975. return null;
  1976. var colorcode = str.TrimStart('#');
  1977. if (!cache.ContainsKey(colorcode))
  1978. {
  1979. var col = ImageUtils.StringToColor(colorcode);
  1980. var bmp = ImageUtils.BitmapFromColor(col, _width, _height, Color.Black);
  1981. cache[colorcode] = bmp.AsBitmapImage();
  1982. }
  1983. var result = cache[colorcode];
  1984. return result;
  1985. }
  1986. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1987. {
  1988. return null;
  1989. }
  1990. }
  1991. public class StringArrayConverter : IValueConverter
  1992. {
  1993. object? IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1994. {
  1995. if (value is string[] strArray)
  1996. {
  1997. return string.Join("\n", strArray);
  1998. }
  1999. Logger.Send(LogType.Error, "", $"Attempt to convert an object which is not a string array: {value}.");
  2000. return null;
  2001. }
  2002. object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  2003. {
  2004. return value;
  2005. }
  2006. }
  2007. #endregion
  2008. [Serializable]
  2009. class DynamicGridDragFormat
  2010. {
  2011. private string entity;
  2012. public DataTable Table { get; set; }
  2013. public Type Entity { get => CoreUtils.GetEntity(entity); set => entity = value.EntityName(); }
  2014. public DynamicGridDragFormat(DataTable table, Type entity)
  2015. {
  2016. Table = table;
  2017. Entity = entity;
  2018. }
  2019. }