DynamicGrid.cs 76 KB

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