DynamicGrid.cs 77 KB

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