DynamicGrid.cs 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383
  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.LoadRow(masterrow, row);
  1007. Refresh(false, false);
  1008. }
  1009. public void AddRow(T data)
  1010. {
  1011. if (MasterData is null) return;
  1012. var masterrow = MasterData.NewRow();
  1013. MasterData.LoadRow(masterrow, data);
  1014. MasterData.Rows.Add(masterrow);
  1015. Refresh(false, false);
  1016. }
  1017. public void DeleteRow(CoreRow row)
  1018. {
  1019. if (MasterData is null) return;
  1020. var masterrow = _recordmap[row];
  1021. MasterData.Rows.Remove(masterrow);
  1022. Refresh(false, false);
  1023. }
  1024. private void FilterRows(CoreTable from, CoreTable into, Dictionary<CoreRow, CoreRow>? recordMap = null, Func<CoreRow, bool>? filter = null)
  1025. {
  1026. into.Rows.Clear();
  1027. recordMap?.Clear();
  1028. foreach (var row in from.Rows.ToArray())
  1029. if (FilterRecord(row) && filter?.Invoke(row) != false)
  1030. {
  1031. var newrow = into.NewRow();
  1032. for (var i = 0; i < into.Columns.Count; i++)
  1033. {
  1034. var value = i < row.Values.Count ? row.Values[i] : null;
  1035. if (into.Columns[i].DataType.IsNumeric())
  1036. value = into.Columns[i].DataType.IsDefault(value) ? null : value;
  1037. //else if (Data.Columns[i].DataType == typeof(String[]))
  1038. // value = String.Join("\n", value as String[]);
  1039. newrow.Values.Add(value);
  1040. }
  1041. //newrow.Values.AddRange(row.Values);
  1042. //if ((OnFilterRecord == null) || (OnFilterRecord(row)))
  1043. into.Rows.Add(newrow);
  1044. recordMap?.TryAdd(newrow, row);
  1045. }
  1046. }
  1047. private void LoadData()
  1048. {
  1049. ResetClipBuffer();
  1050. if (MasterData is null)
  1051. return;
  1052. FilterRows(MasterData, Data, _recordmap);
  1053. InvalidateGrid();
  1054. //ScrollBar.Value = _CurrentRow <= 0 ? 0 : _CurrentRow;
  1055. SelectedRows = Array.Empty<CoreRow>();
  1056. }
  1057. //IncrementalList<T> _data = null;
  1058. public void InvalidateRow(CoreRow row)
  1059. {
  1060. UIComponent.InvalidateRow(row);
  1061. }
  1062. protected void InvalidateGrid()
  1063. {
  1064. if (RowStyleSelector != null)
  1065. RowStyleSelector.Data = Data;
  1066. UIComponent.RefreshData(Data);
  1067. Loading.BeginAnimation(Label.OpacityProperty, null);
  1068. Loading.Visibility = Visibility.Collapsed;
  1069. }
  1070. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  1071. {
  1072. UIComponent.AddVisualFilter(column, value, filtertype);
  1073. }
  1074. #endregion
  1075. #region Item Manipulation
  1076. #region Load/Save/Delete
  1077. public virtual T[] LoadItems(CoreRow[] rows)
  1078. {
  1079. var result = new List<T>();
  1080. foreach (var row in rows)
  1081. {
  1082. var index = Data.Rows.IndexOf(row);
  1083. result.Add(LoadItem(row));
  1084. }
  1085. return result.ToArray();
  1086. }
  1087. public abstract T LoadItem(CoreRow row);
  1088. public abstract void SaveItem(T item);
  1089. public virtual void SaveItems(T[] items)
  1090. {
  1091. foreach (var item in items)
  1092. SaveItem(item);
  1093. }
  1094. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  1095. {
  1096. return true;
  1097. }
  1098. public abstract void DeleteItems(params CoreRow[] rows);
  1099. protected virtual void DoDelete()
  1100. {
  1101. var rows = SelectedRows.ToArray();
  1102. if (rows.Any())
  1103. if (CanDeleteItems(rows))
  1104. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1105. MessageBoxResult.Yes)
  1106. {
  1107. DeleteItems(rows);
  1108. SelectedRows = Array.Empty<CoreRow>();
  1109. OnChanged?.Invoke(this, EventArgs.Empty);
  1110. Refresh(false, true);
  1111. SelectItems(null);
  1112. }
  1113. }
  1114. private void Delete_Click(object sender, RoutedEventArgs e)
  1115. {
  1116. DoDelete();
  1117. }
  1118. #endregion
  1119. #region Edit
  1120. protected virtual void DoEdit()
  1121. {
  1122. if (!SelectedRows.Any())
  1123. return;
  1124. if (AddEditClick(SelectedRows))
  1125. {
  1126. SelectItems(SelectedRows);
  1127. }
  1128. }
  1129. private void Edit_Click(object sender, RoutedEventArgs e)
  1130. {
  1131. DoEdit();
  1132. }
  1133. protected virtual void DoAdd(bool OpenEditorOnDirectEdit = false)
  1134. {
  1135. //CoreRow row = (SelectedRow > -1) && (SelectedRow < Data.Rows.Count) ? Data.Rows[this.SelectedRow] : null;
  1136. if (IsDirectEditMode() && !OpenEditorOnDirectEdit)
  1137. {
  1138. var item = CreateItem();
  1139. if (!AfterCreate(item))
  1140. return;
  1141. SaveItem(item);
  1142. var datarow = Data.NewRow();
  1143. ObjectToRow(item, datarow);
  1144. Data.Rows.Add(datarow);
  1145. var masterrow = MasterData.NewRow();
  1146. ObjectToRow(item, masterrow);
  1147. MasterData.Rows.Add(masterrow);
  1148. _recordmap[datarow] = masterrow;
  1149. InvalidateGrid();
  1150. SelectedRows = new[] { datarow };
  1151. OnChanged?.Invoke(this, EventArgs.Empty);
  1152. }
  1153. else if (AddEditClick(null))
  1154. {
  1155. Refresh(false, true);
  1156. }
  1157. }
  1158. private void Add_Click(object sender, RoutedEventArgs e)
  1159. {
  1160. if (CanCreateItems())
  1161. DoAdd();
  1162. }
  1163. public virtual DynamicEditorPages LoadEditorPages(T item)
  1164. {
  1165. DynamicEditorPages pages = new DynamicEditorPages();
  1166. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  1167. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  1168. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  1169. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  1170. foreach (var page in pages)
  1171. page.Ready = false;
  1172. return pages;
  1173. }
  1174. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  1175. {
  1176. buttons.Clear();
  1177. buttons.Add(
  1178. "",
  1179. Wpf.Resources.help.AsBitmapImage(),
  1180. item,
  1181. (f, i) =>
  1182. {
  1183. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  1184. { UseShellExecute = true });
  1185. }
  1186. );
  1187. OnLoadEditorButtons?.Invoke(item, buttons);
  1188. }
  1189. protected virtual void BeforeLoad(IDynamicEditorForm form, T[] items)
  1190. {
  1191. form.BeforeLoad();
  1192. }
  1193. void IDynamicGrid.InitialiseEditorForm(IDynamicEditorForm editor, object[] items, Func<Type, CoreTable>? pageDataHandler, bool preloadPages)
  1194. {
  1195. InitialiseEditorForm(editor, items.Cast<T>().ToArray(), pageDataHandler, preloadPages);
  1196. }
  1197. public virtual bool EditItems(object[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1198. {
  1199. var values = items.Cast<T>().ToArray();
  1200. return EditItems(values, PageDataHandler, PreloadPages);
  1201. }
  1202. public virtual void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false)
  1203. {
  1204. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  1205. var buttons = new DynamicEditorButtons();
  1206. if (items.Length == 1)
  1207. LoadEditorButtons(items.First(), buttons);
  1208. editor.Setup(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, pageDataHandler, preloadPages);
  1209. editor.OnCustomiseColumns = (sender, columns) =>
  1210. {
  1211. columns.Clear();
  1212. columns.AddRange(MasterColumns);
  1213. ConfigureColumns(columns);
  1214. };
  1215. editor.OnDefineEditor = (o, c) =>
  1216. {
  1217. var result = GetEditor(o, c);
  1218. if (result != null)
  1219. result = result.CloneEditor();
  1220. return result;
  1221. };
  1222. editor.OnFormCustomiseEditor += DoCustomiseEditor;
  1223. editor.OnDefineFilter = (type, column) => { return DefineLookupFilter(type, column, items); };
  1224. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  1225. editor.OnDefineLookups = editor => DefineLookups(editor, items);
  1226. editor.OnEditorValueChanged += (s, n, v) => EditorValueChanged(editor, items, n, v);
  1227. editor.OnAfterEditorValueChanged += (g, args) => AfterEditorValueChanged(g, items, args);
  1228. editor.OnReconfigureEditors = g => DoReconfigureEditors(g, items);
  1229. editor.OnValidateData += (o, i) => ValidateData(items);
  1230. editor.OnSelectPage += SelectPage;
  1231. editor.OnSaveItem = (o, e) =>
  1232. {
  1233. try
  1234. {
  1235. using var Wait = new WaitCursor();
  1236. DoBeforeSave(editor, items);
  1237. if (items.Length == 1)
  1238. editor.UnloadEditorPages(false);
  1239. foreach (var item in items)
  1240. SaveItem(item);
  1241. if (items.Length == 1)
  1242. editor.UnloadEditorPages(true);
  1243. DoAfterSave(editor, items);
  1244. }
  1245. catch (Exception err)
  1246. {
  1247. MessageBox.Show(err.Message);
  1248. e.Cancel = true;
  1249. }
  1250. };
  1251. BeforeLoad(editor, items);
  1252. editor.Items = items;
  1253. AfterLoad(editor, items);
  1254. }
  1255. private void DoCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  1256. {
  1257. CustomiseEditor((T[])items, column, editor);
  1258. OnCustomiseEditor?.Invoke(sender, (T[])items, column, editor);
  1259. }
  1260. protected virtual void CustomiseEditor(T[] items, DynamicGridColumn column, BaseEditor editor)
  1261. {
  1262. }
  1263. protected virtual void DoAfterSave(IDynamicEditorForm editor, T[] items)
  1264. {
  1265. OnAfterSave?.Invoke(editor, items);
  1266. }
  1267. protected virtual void DoBeforeSave(IDynamicEditorForm editor, T[] items)
  1268. {
  1269. OnBeforeSave?.Invoke(editor, items);
  1270. }
  1271. public virtual bool EditItems(T[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1272. {
  1273. DynamicEditorForm editor;
  1274. using (var cursor = new WaitCursor())
  1275. {
  1276. editor = new DynamicEditorForm();
  1277. editor.SetValue(Panel.ZIndexProperty, 999);
  1278. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  1279. OnEditorLoaded?.Invoke(editor, items);
  1280. }
  1281. return editor.ShowDialog() == true;
  1282. }
  1283. private Dictionary<String, object?> AfterEditorValueChanged(DynamicEditorGrid grid, T[] items, AfterEditorValueChangedArgs args)
  1284. {
  1285. var changes = new Dictionary<string, object?>();
  1286. OnAfterEditorValueChanged(grid, items, args, changes);
  1287. return changes;
  1288. }
  1289. protected virtual void OnAfterEditorValueChanged(DynamicEditorGrid? grid, T[] items, AfterEditorValueChangedArgs args, Dictionary<String, object?> changes)
  1290. {
  1291. }
  1292. protected virtual void DoReconfigureEditors(DynamicEditorGrid grid, T[] items)
  1293. {
  1294. /*if (items.First() is IDimensioned dimensioned)
  1295. {
  1296. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  1297. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  1298. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  1299. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  1300. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  1301. }*/
  1302. }
  1303. private string[]? ValidateData(T[] items)
  1304. {
  1305. var errors = new List<string>();
  1306. DoValidate(items, errors);
  1307. OnValidate?.Invoke(this, items, errors);
  1308. return errors.Any() ? errors.ToArray() : null;
  1309. }
  1310. protected virtual void DoValidate(T[] items, List<string> errors)
  1311. {
  1312. }
  1313. protected virtual void AfterLoad(IDynamicEditorForm editor, T[] items)
  1314. {
  1315. editor.AfterLoad();
  1316. }
  1317. protected virtual void SelectPage(object sender, BaseObject[]? items)
  1318. {
  1319. }
  1320. protected virtual Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, T[] items, string name, object value)
  1321. {
  1322. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  1323. if (OnEditorValueChanged != null)
  1324. {
  1325. var newchanges = OnEditorValueChanged(editor, name, value);
  1326. foreach (var key in newchanges.Keys)
  1327. result[key] = newchanges[key];
  1328. }
  1329. return result;
  1330. }
  1331. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  1332. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items, bool async = true)
  1333. {
  1334. if (sender.EditorDefinition is not ILookupEditor editor)
  1335. return;
  1336. var colname = sender.ColumnName;
  1337. if (async)
  1338. {
  1339. Task.Run(() =>
  1340. {
  1341. try
  1342. {
  1343. var values = editor.Values(typeof(T), colname, items);
  1344. Dispatcher.Invoke(
  1345. () =>
  1346. {
  1347. try
  1348. {
  1349. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  1350. sender.LoadLookups(values);
  1351. }
  1352. catch (Exception e2)
  1353. {
  1354. Logger.Send(LogType.Information, typeof(T).Name,
  1355. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  1356. }
  1357. }
  1358. );
  1359. }
  1360. catch (Exception e)
  1361. {
  1362. Logger.Send(LogType.Information, typeof(T).Name,
  1363. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  1364. }
  1365. });
  1366. }
  1367. else
  1368. {
  1369. var values = editor.Values(typeof(T), colname, items);
  1370. sender.LoadLookups(values);
  1371. }
  1372. }
  1373. /// <summary>
  1374. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  1375. /// </summary>
  1376. /// <param name="item">The object being edited.</param>
  1377. /// <param name="column">The column of the editor.</param>
  1378. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  1379. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  1380. {
  1381. return column.Editor ?? CoreUtils.GetProperty(item.GetType(), column.ColumnName).GetEditor();
  1382. }
  1383. protected IFilter? DefineLookupFilter(Type type, string column, T[] items)
  1384. {
  1385. return LookupFactory.DefineLookupFilter(typeof(T), type, column, items);
  1386. }
  1387. protected virtual void SetEditorValue(object item, string name, object value)
  1388. {
  1389. try
  1390. {
  1391. CoreUtils.SetPropertyValue(item, name, value);
  1392. }
  1393. catch (Exception e)
  1394. {
  1395. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1396. }
  1397. }
  1398. protected virtual object? GetEditorValue(object item, string name)
  1399. {
  1400. return CoreUtils.GetPropertyValue(item, name);
  1401. }
  1402. protected virtual bool CanCreateItems()
  1403. {
  1404. return true;
  1405. }
  1406. private bool AddEditClick(CoreRow[]? rows)
  1407. {
  1408. if (!IsEnabled || bRefreshing)
  1409. return false;
  1410. if (rows == null || !rows.Any())
  1411. {
  1412. if (!CanCreateItems())
  1413. return false;
  1414. var item = CreateItem();
  1415. if (!AfterCreate(item))
  1416. return false;
  1417. // Yea, and this won't work, because we're actually usually showing the description of a linked item,
  1418. // not the id of the link, and we need to set the ID to have it work properly :-(
  1419. //foreach (String key in VisualFilters.Keys)
  1420. // CoreUtils.SetPropertyValue(item, key, VisualFilters[key]);
  1421. if (EditItems(new[] { item }))
  1422. {
  1423. //_CurrentRow = Data.Rows.Count;
  1424. var row = Data.NewRow();
  1425. ObjectToRow(item, row);
  1426. Data.Rows.Add(row);
  1427. InvalidateGrid();
  1428. SelectedRows = new[] { row };
  1429. DoChanged();
  1430. return true;
  1431. }
  1432. return false;
  1433. }
  1434. var items = Array.Empty<T>();
  1435. using (new WaitCursor())
  1436. {
  1437. Stopwatch sw = new Stopwatch();
  1438. sw.Start();
  1439. items = LoadItems(rows);
  1440. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  1441. sw.Stop();
  1442. }
  1443. if (items.Any())
  1444. {
  1445. var sel = SelectedRows;
  1446. if (EditItems(items))
  1447. {
  1448. for (var i = 0; i < items.Length; i++)
  1449. {
  1450. ObjectToRow(items[i], rows[i]);
  1451. ObjectToRow(items[i], _recordmap[rows[i]]);
  1452. }
  1453. InvalidateGrid();
  1454. SelectedRows = sel;
  1455. DoChanged();
  1456. return true;
  1457. }
  1458. return false;
  1459. }
  1460. return false;
  1461. }
  1462. #endregion
  1463. #region Duplicate
  1464. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  1465. {
  1466. return LoadItems(rows);
  1467. }
  1468. private bool DoDuplicate(Button button, CoreRow[] rows)
  1469. {
  1470. if (!rows.Any())
  1471. {
  1472. MessageBox.Show("Please select at least one record to duplicate!");
  1473. return false;
  1474. }
  1475. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  1476. if (!ids.Any())
  1477. {
  1478. MessageBox.Show("Please select at least one record to duplicate!");
  1479. return false;
  1480. }*/
  1481. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  1482. if (duplicator is null)
  1483. {
  1484. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  1485. return false;
  1486. }
  1487. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  1488. return true;
  1489. }
  1490. #endregion
  1491. public virtual T CreateItem()
  1492. {
  1493. var result = new T();
  1494. OnCreateItem?.Invoke(this, result);
  1495. return result;
  1496. }
  1497. public virtual bool AfterCreate(T item)
  1498. {
  1499. return OnAfterCreateItem?.Invoke(this, item) ?? true;
  1500. }
  1501. protected virtual void DoPrint(object sender)
  1502. {
  1503. OnPrintData?.Invoke(sender);
  1504. }
  1505. protected virtual void ShowHelp(string slug)
  1506. {
  1507. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  1508. }
  1509. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(IDynamicEditorForm editor, TTargetType item,
  1510. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  1511. where TTargetType : Entity, new()
  1512. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  1513. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  1514. {
  1515. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  1516. var page =
  1517. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  1518. if (page != null && item != null)
  1519. {
  1520. if (!page.Ready)
  1521. page.Load(item, null);
  1522. CoreTable table;
  1523. if (sourceid == Guid.Empty)
  1524. {
  1525. table = new CoreTable();
  1526. table.LoadColumns(typeof(TSourceForm));
  1527. }
  1528. else
  1529. {
  1530. table = new Client<TSourceForm>().Query(
  1531. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  1532. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  1533. );
  1534. }
  1535. var newforms = new List<TTargetForm>();
  1536. foreach (var row in table.Rows)
  1537. {
  1538. var sourceform = row.ToObject<TSourceForm>();
  1539. var targetform = new TTargetForm();
  1540. targetform.Form.ID = sourceform.Form.ID;
  1541. targetform.Form.Synchronise(sourceform.Form);
  1542. newforms.Add(targetform);
  1543. }
  1544. page.Items.Clear();
  1545. page.LoadItems(newforms.ToArray());
  1546. }
  1547. }
  1548. #region ClipBuffer
  1549. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  1550. protected void ResetClipBuffer()
  1551. {
  1552. ClipBuffer = null;
  1553. }
  1554. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  1555. {
  1556. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  1557. }
  1558. private void CutToClipBuffer()
  1559. {
  1560. SetClipBuffer(ClipAction.Cut, SelectedRows);
  1561. InvalidateGrid();
  1562. }
  1563. private void CopyToClipBuffer()
  1564. {
  1565. SetClipBuffer(ClipAction.Copy, SelectedRows);
  1566. InvalidateGrid();
  1567. }
  1568. private void PasteFromClipBuffer()
  1569. {
  1570. if (ClipBuffer == null)
  1571. return;
  1572. if (!IsSequenced)
  1573. return;
  1574. using (new WaitCursor())
  1575. {
  1576. var updates = ClipBuffer.Item2.Select(x => x.ToObject<T>()).ToList();
  1577. if (BeforePaste(updates, ClipBuffer.Item1))
  1578. {
  1579. var currow = SelectedRows.FirstOrDefault()
  1580. ?? Data.Rows.LastOrDefault();
  1581. var sequence = currow != null ? currow.Get<T, long>(c => ((ISequenceable)c).Sequence) : 0;
  1582. var postrows = Data.Rows.Where(r => !ClipBuffer.Item2.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  1583. updates.AddRange(LoadItems(postrows.ToArray()));
  1584. foreach (var update in updates)
  1585. {
  1586. sequence++;
  1587. ((ISequenceable)update).Sequence = sequence;
  1588. }
  1589. }
  1590. if (updates.Any())
  1591. {
  1592. SaveItems(updates.ToArray());
  1593. Refresh(false, true);
  1594. }
  1595. }
  1596. }
  1597. protected virtual bool BeforePaste(IEnumerable<T> items, ClipAction action)
  1598. {
  1599. return true;
  1600. }
  1601. private void Cut_Click(object sender, RoutedEventArgs e)
  1602. {
  1603. CutToClipBuffer();
  1604. }
  1605. private void Copy_Click(object sender, RoutedEventArgs e)
  1606. {
  1607. CopyToClipBuffer();
  1608. }
  1609. private void Paste_Click(object sender, RoutedEventArgs e)
  1610. {
  1611. PasteFromClipBuffer();
  1612. }
  1613. #endregion
  1614. protected virtual void ObjectToRow(T obj, CoreRow row)
  1615. {
  1616. row.Table.LoadRow(row, obj);
  1617. }
  1618. #region Import / Export
  1619. protected virtual CoreTable LoadImportKeys(String[] fields)
  1620. {
  1621. var result = new CoreTable();
  1622. result.LoadColumns(new Columns<T>(fields));
  1623. return result;
  1624. }
  1625. protected virtual Guid GetImportID()
  1626. {
  1627. return Guid.Empty;
  1628. }
  1629. protected virtual bool CustomiseImportItem(T item)
  1630. {
  1631. if (IsSequenced)
  1632. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  1633. return true;
  1634. }
  1635. protected virtual string CustomiseImportFileName(string filename)
  1636. {
  1637. return filename;
  1638. }
  1639. protected virtual void DoImport()
  1640. {
  1641. var list = new DynamicImportList(
  1642. typeof(T),
  1643. GetImportID()
  1644. );
  1645. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  1646. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  1647. list.OnSave += (sender, entity) => SaveItem(entity as T);
  1648. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  1649. list.ShowDialog();
  1650. Refresh(false, true);
  1651. }
  1652. private void Import_Click(object sender, RoutedEventArgs e)
  1653. {
  1654. DoImport();
  1655. }
  1656. protected virtual void CustomiseExportColumns(List<string> columnnames)
  1657. {
  1658. }
  1659. protected virtual string CustomiseExportFileName(string filename)
  1660. {
  1661. return filename;
  1662. }
  1663. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  1664. {
  1665. }
  1666. protected virtual void ApplyExportFilter(CoreTable table, object data)
  1667. {
  1668. }
  1669. protected virtual void DoExport()
  1670. {
  1671. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  1672. CustomiseExportColumns(columnnames);
  1673. var form = new DynamicExportForm(typeof(T), columnnames);
  1674. if (form.ShowDialog() != true)
  1675. return;
  1676. var filters = new Filters<T>();
  1677. filters.Add(DefineFilter());
  1678. var predicates = UIComponent.GetFilterPredicates();
  1679. var visiblerows = GetVisibleRows();
  1680. CustomiseExportFilters(filters, visiblerows);
  1681. var columns = new Columns<T>(form.Fields);
  1682. var otherColumns = form.GetChildFields()
  1683. .Select(x => new Tuple<Type, IColumns>(
  1684. x.Key,
  1685. (Activator.CreateInstance(typeof(Columns<>).MakeGenericType(x.Key), new object[] { x.Value }) as IColumns)!))
  1686. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  1687. var reloadColumns = new Columns<T>();
  1688. foreach (var column in columns.ColumnNames())
  1689. {
  1690. reloadColumns.Add(column);
  1691. }
  1692. foreach (var column in HiddenColumns.ColumnNames)
  1693. {
  1694. reloadColumns.Add(column);
  1695. }
  1696. foreach (var (column, _) in predicates)
  1697. {
  1698. reloadColumns.Add(column);
  1699. }
  1700. var sort = LookupFactory.DefineSort<T>();
  1701. Reload(filters, reloadColumns, ref sort, (data, err) => Dispatcher.Invoke(() =>
  1702. {
  1703. if (data is not null)
  1704. {
  1705. var newData = new CoreTable();
  1706. foreach (var column in columns.Items)
  1707. newData.Columns.Add(new CoreColumn { ColumnName = column.Property, DataType = column.Type });
  1708. FilterRows(data, newData, filter: row =>
  1709. {
  1710. foreach(var (_, predicate) in predicates)
  1711. {
  1712. if (!predicate(row))
  1713. {
  1714. return false;
  1715. }
  1716. }
  1717. return true;
  1718. });
  1719. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  1720. list.AddRange(LoadExportTables(filters, otherColumns));
  1721. DoExportTables(list);
  1722. }
  1723. else if (err is not null)
  1724. {
  1725. Logger.Send(LogType.Error, "", $"Error in export: {CoreUtils.FormatException(err)}");
  1726. MessageBox.Show(err.Message);
  1727. }
  1728. }));
  1729. }
  1730. private void Export_Click(object sender, RoutedEventArgs e)
  1731. {
  1732. DoExport();
  1733. }
  1734. /// <summary>
  1735. /// Loads the child tables for an export, based on the filter of the parent table.
  1736. /// </summary>
  1737. /// <remarks>
  1738. /// If not overriden, defaults to creating empty tables with no records.
  1739. /// </remarks>
  1740. /// <param name="filter">Filter for the parent table.</param>
  1741. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  1742. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  1743. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  1744. {
  1745. return tableColumns.Select(x =>
  1746. {
  1747. var table = new CoreTable();
  1748. table.LoadColumns(x.Item2);
  1749. return new Tuple<Type?, CoreTable>(x.Item1, table);
  1750. });
  1751. }
  1752. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  1753. {
  1754. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  1755. ExcelExporter.DoExport(data, filename);
  1756. }
  1757. #endregion
  1758. public void ScrollIntoView(CoreRow row)
  1759. {
  1760. UIComponent.ScrollIntoView(row);
  1761. }
  1762. #endregion
  1763. #region Custom Buttons
  1764. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  1765. {
  1766. var button = new Button();
  1767. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  1768. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  1769. button.Height = 30;
  1770. UpdateButton(button, image, text, tooltip);
  1771. return button;
  1772. }
  1773. public void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  1774. {
  1775. var stackPnl = new StackPanel();
  1776. stackPnl.Orientation = Orientation.Horizontal;
  1777. //stackPnl.Margin = new Thickness(2);
  1778. if (image != null)
  1779. {
  1780. var img = new Image();
  1781. img.Source = image;
  1782. img.Margin = new Thickness(2);
  1783. img.ToolTip = tooltip;
  1784. stackPnl.Children.Add(img);
  1785. }
  1786. if (!string.IsNullOrEmpty(text))
  1787. {
  1788. button.MaxWidth = double.MaxValue;
  1789. var lbl = new Label();
  1790. lbl.Content = text;
  1791. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  1792. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  1793. lbl.Margin = new Thickness(2, 0, 5, 0);
  1794. lbl.ToolTip = ToolTip;
  1795. stackPnl.Children.Add(lbl);
  1796. }
  1797. else
  1798. button.MaxWidth = 30;
  1799. button.Content = stackPnl;
  1800. button.ToolTip = tooltip;
  1801. }
  1802. private bool bFirstButtonAdded = true;
  1803. private bool AnyButtonsVisible()
  1804. {
  1805. if (Add.Visibility != Visibility.Collapsed)
  1806. return true;
  1807. if (Edit.Visibility != Visibility.Collapsed)
  1808. return true;
  1809. /*if (MultiEdit.Visibility != Visibility.Collapsed)
  1810. return true;*/
  1811. if (Export.Visibility != Visibility.Collapsed)
  1812. return true;
  1813. return false;
  1814. }
  1815. public Button AddButton(string? caption, BitmapImage? image, string? tooltip, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1816. {
  1817. var button = CreateButton(image, caption, tooltip);
  1818. button.Margin = position == DynamicGridButtonPosition.Right
  1819. ? new Thickness(2, 2, 0, 0)
  1820. : bFirstButtonAdded && AnyButtonsVisible()
  1821. ? new Thickness(0, 2, 0, 0)
  1822. : new Thickness(0, 2, 2, 0);
  1823. button.Padding = !String.IsNullOrWhiteSpace(caption) ? new Thickness(5, 1, 5, 1) : new Thickness(1);
  1824. button.Tag = action;
  1825. button.Click += Button_Click;
  1826. if (position == DynamicGridButtonPosition.Right)
  1827. RightButtonStack.Children.Add(button);
  1828. else
  1829. LeftButtonStack.Children.Add(button);
  1830. bFirstButtonAdded = false;
  1831. return button;
  1832. }
  1833. public Button AddButton(string? caption, BitmapImage? image, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1834. {
  1835. var result = AddButton(caption, image, null, action, position);
  1836. return result;
  1837. }
  1838. private void Button_Click(object sender, RoutedEventArgs e)
  1839. {
  1840. var button = (Button)sender;
  1841. var action = (DynamicGridButtonClickEvent)button.Tag;
  1842. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  1843. if (action.Invoke(button, SelectedRows))
  1844. Refresh(false, true);
  1845. }
  1846. #endregion
  1847. #region Header Actions
  1848. private void SelectColumnsClick()
  1849. {
  1850. var editor = new DynamicGridColumnsEditor(typeof(T));
  1851. editor.DirectEdit = IsDirectEditMode();
  1852. editor.Columns.AddRange(VisibleColumns);
  1853. if (editor.ShowDialog().Equals(true))
  1854. {
  1855. VisibleColumns.Clear();
  1856. VisibleColumns.AddRange(editor.Columns);
  1857. SaveColumns(VisibleColumns);
  1858. //OnSaveColumns?.Invoke(this, editor.Columns);
  1859. Refresh(true, true);
  1860. }
  1861. }
  1862. #endregion
  1863. #region Drag + Drop
  1864. /// <summary>
  1865. /// Handle a number of rows from a different <see cref="DynamicGrid{T}"/> being dragged into this one.
  1866. /// </summary>
  1867. /// <param name="entity">The type of entity that that the rows of <paramref name="table"/> represent.</param>
  1868. /// <param name="table">The data being dragged.</param>
  1869. /// <param name="e"></param>
  1870. protected virtual void OnDragEnd(Type entity, CoreTable table, DragEventArgs e)
  1871. {
  1872. Logger.Send(LogType.Information,"","OnDragEnd");
  1873. }
  1874. /// <summary>
  1875. /// Handle all types of items being dragged onto this grid that aren't handled by <see cref="OnDragEnd(Type, CoreTable, DragEventArgs)"/>,
  1876. /// i.e., data which is not a <see cref="CoreTable"/> from another <see cref="DynamicGrid{T}"/>
  1877. /// </summary>
  1878. /// <remarks>
  1879. /// Can be used to handle files, for example.
  1880. /// </remarks>
  1881. /// <param name="sender"></param>
  1882. /// <param name="e"></param>
  1883. protected virtual void HandleDragDrop(object sender, DragEventArgs e)
  1884. {
  1885. }
  1886. protected virtual void HandleDragOver(object sender, DragEventArgs e)
  1887. {
  1888. }
  1889. protected DragDropEffects DragTable(Type entity, CoreTable table)
  1890. {
  1891. Logger.Send(LogType.Information, "", "DragTable");
  1892. var data = new DataObject();
  1893. data.SetData(DynamicGridUtils.DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  1894. var effect = DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  1895. return effect;
  1896. }
  1897. protected virtual DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1898. {
  1899. Logger.Send(LogType.Information, "", "OnRowsDragStart");
  1900. var table = new CoreTable();
  1901. table.LoadColumns(Data.Columns);
  1902. table.LoadRows(rows);
  1903. return DragTable(typeof(T), table);
  1904. }
  1905. #endregion
  1906. }