DynamicGrid.cs 75 KB

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