DynamicGrid.cs 76 KB

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