DynamicGrid.cs 77 KB

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