DynamicGrid.cs 79 KB

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