DynamicGrid.cs 75 KB

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