DynamicGrid.cs 89 KB

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