DynamicGrid.cs 78 KB

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