DynamicGrid.cs 77 KB

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