123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047 |
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Markup;
- using System.Windows.Media;
- using System.Windows.Threading;
- using System.Xml;
- using InABox.Clients;
- using InABox.Configuration;
- using InABox.Core;
- using InABox.WPF;
- namespace InABox.DynamicGrid
- {
- /// <summary>
- /// Interaction logic for DynamicEditorGrid.xaml
- /// </summary>
- public delegate void OnUpdateOtherEditorHandler(string columnname, object value);
- public delegate Dictionary<string, object?> EditorValueChangedHandler(object sender, string name, object value);
- //public delegate Dictionary<object, object> EditorGetLookupsHandler(object sender, String column);
- public partial class DynamicEditorGrid : UserControl
- {
- public delegate void EditorCreatedHandler(object sender, double height, double width);
- public delegate Document FindDocumentEvent(string FileName);
- public delegate Document? GetDocumentEvent(Guid id);
- public delegate object GetPropertyValueHandler(object sender, string name);
- public delegate void SaveDocumentEvent(Document document);
- public delegate void SetPropertyValueHandler(object sender, string name, object value);
- // Column Definitions as defined by calling model
- private DynamicGridColumns _columns;
- private string _layoutname = "";
- private bool _loaded;
- private bool bChanging;
- // List of Changed Editor Values (used when redesigning screen)
- private readonly Dictionary<string, object> changes = new();
- private Grid CustomGrid;
- private DynamicTabControl Details;
- private Grid EditorGrid;
- // Active Editor List
- private readonly List<IDynamicEditorControl> editors = new();
- private readonly Dictionary<IDynamicEditorPage, DynamicTabItem> pagemap = new();
- //Dictionary<IDynamicEditorPage, bool> loadedpages = new Dictionary<IDynamicEditorPage, bool>();
- public DynamicEditorGrid()
- {
- InitializeComponent();
- Loaded += DynamicEditorGrid_Loaded;
- }
- //private Dictionary<String, Tuple<FrameworkElement, Object, DynamicGridColumn>> editors = new Dictionary<string, Tuple<FrameworkElement, Object, DynamicGridColumn>>();
- public DynamicEditorPages Pages { get; private set; }
- public bool PreloadPages { get; set; }
- public Type UnderlyingType { get; set; }
- public OnLoadPage OnLoadPage { get; set; }
- public OnSelectPage OnSelectPage { get; set; }
- public OnUnloadPage OnUnloadPage { get; set; }
- //private void UnloadEditorValues()
- //{
- // foreach (string columnname in editors.Keys)
- // {
- // bool changed = (bool)CoreUtils.GetPropertyValue(editors[columnname], "Changed");
- // if (changed)
- // {
- // changes[columnname] = CoreUtils.GetPropertyValue(editors[columnname], "Value");
- // Dictionary<string, object> othervalues = CoreUtils.GetPropertyValue(editors[columnname], "OtherValues") as Dictionary<string, object>;
- // foreach (var field in othervalues.Keys)
- // {
- // List<String> comps = columnname.Split('.').ToList();
- // comps[comps.Count - 1] = field;
- // String actualname = String.Join(".", comps);
- // changes[actualname] = othervalues[field];
- // }
- // }
- // }
- //}
- public bool IsCustomLayout { get; private set; }
- public IDynamicEditorControl FindEditor(string columnname)
- {
- return editors.FirstOrDefault(x => x.ColumnName.Equals(columnname));
- }
- public object GetPropertyValue(string columnname)
- {
- return OnGetPropertyValue?.Invoke(this, columnname);
- }
- public event EditorCreatedHandler OnEditorCreated;
- public event OnCustomiseColumns OnCustomiseColumns;
- public event OnGetEditor OnGetEditor;
- public event OnGridCustomiseEditor OnGridCustomiseEditor;
- public event OnGetEditorSequence OnGetSequence;
- public event GetPropertyValueHandler OnGetPropertyValue;
- public event SetPropertyValueHandler OnSetPropertyValue;
- public event EditorValueChangedHandler OnEditorValueChanged;
- public event OnReconfigureEditors ReconfigureEditors;
- public event OnDefineFilter OnDefineFilter;
- public event OnDefineLookup OnDefineLookups;
- public event OnLookupsDefined OnLookupsDefined;
- private void DynamicEditorGrid_Loaded(object sender, RoutedEventArgs e)
- {
- ConfigureEditors();
- LoadEditorValues();
- AddPages();
- DoReconfigureEditors();
- //MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
- //MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
- //if (Keyboard.PrimaryDevice != null)
- //{
- // if (Keyboard.PrimaryDevice.ActiveSource != null)
- // {
- // var e1 = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.Tab) { RoutedEvent = Keyboard.KeyDownEvent };
- // InputManager.Current.ProcessInput(e1);
- // }
- //}
- editors.FirstOrDefault().SetFocus();
- _loaded = true;
- }
- public event GetDocumentEvent OnGetDocument;
- public event FindDocumentEvent OnFindDocument;
- public event SaveDocumentEvent OnSaveDocument;
- private void LoadLookupColumns(DynamicGridColumn column, Dictionary<string, string> othercolumns)
- {
- othercolumns.Clear();
- var comps = column.ColumnName.Split('.').ToList();
- comps.RemoveAt(comps.Count - 1);
- var prefix = string.Format("{0}.", string.Join(".", comps));
- var cols = _columns.Where(x => !x.ColumnName.Equals(column.ColumnName) && x.ColumnName.StartsWith(prefix));
- foreach (var col in cols)
- othercolumns[col.ColumnName.Replace(prefix, "")] = col.ColumnName;
- }
- private string GetCodeColumn(DynamicGridColumn column)
- {
- var comps = column.ColumnName.Split('.').ToList();
- comps.RemoveAt(comps.Count - 1);
- var prefix = string.Format("{0}.", string.Join(".", comps));
- var cols = _columns.Where(x => !x.ColumnName.Equals(column.ColumnName) && x.ColumnName.StartsWith(prefix));
- foreach (var col in cols)
- {
- var editor = OnGetEditor?.Invoke(col);
- if (editor is CodeEditor || editor is UniqueCodeEditor)
- return col.ColumnName.Split('.').Last();
- }
- return "";
- }
- private void ConfigurePopupEditor(PopupEditorControl popup, DynamicGridColumn column, PopupEditor editor)
- {
- popup.ColumnName = column.ColumnName;
- LoadLookupColumns(column, popup.OtherColumns);
- if (popup.EditorDefinition is DataLookupEditor)
- LoadLookupColumns(column, (popup.EditorDefinition as DataLookupEditor).OtherColumns);
- popup.OnUpdateOtherEditor += Lookup_OnUpdateOtherEditor;
- }
- private void ConfigureCodePopupEditor(CodePopupEditorControl popup, DynamicGridColumn column, CodePopupEditor editor)
- {
- popup.ColumnName = column.ColumnName;
- LoadLookupColumns(column, popup.OtherColumns);
- if (popup.EditorDefinition is DataLookupEditor)
- LoadLookupColumns(column, (popup.EditorDefinition as DataLookupEditor).OtherColumns);
- popup.CodeColumn = !string.IsNullOrEmpty(editor.CodeColumn) ? editor.CodeColumn : GetCodeColumn(column);
- popup.OnDefineFilter += (sender, type) => { return OnDefineFilter?.Invoke(sender, type); };
- popup.OnUpdateOtherEditor += Lookup_OnUpdateOtherEditor;
- }
- private void ConfigureLookupEditor(LookupEditorControl lookup, DynamicGridColumn column, LookupEditor editor)
- {
- if (editor.Width != int.MaxValue)
- lookup.Width = editor.Width;
- lookup.ColumnName = column.ColumnName;
- LoadLookupColumns(column, lookup.OtherColumns);
- if (lookup.EditorDefinition is DataLookupEditor)
- LoadLookupColumns(column, (lookup.EditorDefinition as DataLookupEditor).OtherColumns);
- lookup.OnUpdateOtherEditor += Lookup_OnUpdateOtherEditor;
- lookup.OnDefineLookups += sender => { OnDefineLookups?.Invoke(sender); };
- lookup.OnLookupsDefined += sender => { OnLookupsDefined?.Invoke(sender); };
- }
- private void ConfigureEnumEditor(LookupEditorControl lookup, DynamicGridColumn column, EnumLookupEditor editor)
- {
- if (editor.Width != int.MaxValue)
- lookup.Width = editor.Width;
- lookup.ColumnName = column.ColumnName;
- lookup.OnDefineLookups += sender => { OnDefineLookups?.Invoke(sender); };
- lookup.OnLookupsDefined += sender =>
- {
- //OnLookupsDefined?.Invoke(sender);
- };
- }
- private void ConfigureComboEditor(LookupEditorControl lookup, DynamicGridColumn column, ComboLookupEditor editor)
- {
- if (editor.Width != int.MaxValue)
- lookup.Width = editor.Width;
- lookup.ColumnName = column.ColumnName;
- lookup.OnDefineLookups += sender => { OnDefineLookups?.Invoke(sender); };
- lookup.OnLookupsDefined += sender => { OnLookupsDefined?.Invoke(sender); };
- }
- private void ConfigureCheckListEditor(CheckListBoxEditorControl checks, DynamicGridColumn column, CheckListEditor editor)
- {
- checks.Width = editor.Width;
- checks.ColumnName = column.ColumnName;
- checks.OnDefineLookups += sender => { OnDefineLookups?.Invoke(sender); };
- checks.OnLookupsDefined += sender => { OnLookupsDefined?.Invoke(sender); };
- }
- private void ConfigureDocumentEditor(DocumentEditorControl document, DynamicGridColumn column, BaseDocumentEditor editor)
- {
- document.ColumnName = column.ColumnName;
- LoadLookupColumns(column, document.OtherColumns);
- if (document.EditorDefinition is DataLookupEditor)
- LoadLookupColumns(column, (document.EditorDefinition as DataLookupEditor).OtherColumns);
- document.OnGetDocument += id => { return OnGetDocument?.Invoke(id); };
- document.OnSaveDocument += doc => { OnSaveDocument?.Invoke(doc); };
- document.OnFindDocument += file => { return OnFindDocument?.Invoke(file); };
- document.OnUpdateOtherEditor += Lookup_OnUpdateOtherEditor;
- document.Filter = editor.FileMask;
- }
- private void ConfigurePasswordEditor(PasswordEditorControl passwordEditorControl, DynamicGridColumn column, PasswordEditor passwordEditor)
- {
- passwordEditorControl.ViewButtonVisible = passwordEditor.ViewButtonVisible;
- }
- //private IEnumerable<BaseDynamicEditorControl> FindEditors(FrameworkElement element, DynamicGridColumn column)
- //{
- // if (element == null)
- // return new List<BaseDynamicEditorControl>();
- // if ((element is Border) && ((element as Border).Child is ScrollViewer))
- // return FindEditors(((element as Border).Child as ScrollViewer), column);
- // return element.FindVisualChildren<BaseDynamicEditorControl>().Where(x => x.ColumnName != null && x.ColumnName.Equals(column.ColumnName));
- //}
- private IEnumerable<BaseDynamicEditorControl> FindEditors(DynamicGridColumn column)
- {
- var results = new List<BaseDynamicEditorControl>();
- foreach (DynamicTabItem tab in Details.Items)
- {
- var border = tab.Content as Border;
- if (border != null)
- {
- var scroll = border.Child as ScrollViewer;
- if (scroll != null)
- {
- var grid = scroll.Content as Grid;
- if (grid != null)
- results.AddRange(grid.Children.OfType<BaseDynamicEditorControl>()
- .Where(x => string.Equals(x.ColumnName, column.ColumnName)));
- }
- }
- }
- //results.AddRange(FindEditors(tab.Content as FrameworkElement, column));
- return results;
- }
- private void ConfigureEditors()
- {
- if (editors.Any() && _columns != null)
- foreach (var column in _columns)
- {
- var editorname = column.ColumnName.Replace(".", "_");
- var
- Editors = FindEditors(
- column); //Details.FindVisualChildren<BaseDynamicEditorControl>().Where(x => x.ColumnName != null && x.ColumnName.Equals(column.ColumnName));
- foreach (var Editor in Editors)
- {
- var editor = Editor.EditorDefinition;
- //List<Object> parameters = editor.Parameters != null ? editor.Parameters.ToList() : new List<object>();
- if (Editor is LookupEditorControl)
- {
- if (editor is LookupEditor)
- ConfigureLookupEditor(Editor as LookupEditorControl, column, editor as LookupEditor);
- else if (editor is EnumLookupEditor)
- ConfigureEnumEditor(Editor as LookupEditorControl, column, editor as EnumLookupEditor);
- else if (editor is ComboLookupEditor)
- ConfigureComboEditor(Editor as LookupEditorControl, column, editor as ComboLookupEditor);
- }
- else if (Editor is CheckListBoxEditorControl && editor is CheckListEditor)
- {
- ConfigureCheckListEditor(Editor as CheckListBoxEditorControl, column, editor as CheckListEditor);
- }
- else if (Editor is PopupEditorControl && editor is PopupEditor)
- {
- ConfigurePopupEditor(Editor as PopupEditorControl, column, editor as PopupEditor);
- }
- else if (Editor is CodePopupEditorControl && editor is CodePopupEditor)
- {
- ConfigureCodePopupEditor(Editor as CodePopupEditorControl, column, editor as CodePopupEditor);
- }
- else if (Editor is DocumentEditorControl && editor is BaseDocumentEditor)
- {
- ConfigureDocumentEditor(Editor as DocumentEditorControl, column, editor as BaseDocumentEditor);
- }
- else if (Editor is PasswordEditorControl && editor is PasswordEditor)
- {
- ConfigurePasswordEditor(Editor as PasswordEditorControl, column, editor as PasswordEditor);
- }
- Editor.Configure();
- if (!editors.Any(x => x.ColumnName.Equals(Editor.ColumnName)))
- editors.Add(Editor);
- Editor.Loaded = true;
- }
- }
- }
- private bool LoadLayout(string xaml)
- {
- if (!string.IsNullOrWhiteSpace(xaml))
- try
- {
- IsCustomLayout = true;
- Content = null;
- Details = XamlReader.Parse(xaml) as DynamicTabControl;
- Content = Details;
- Details.ApplyTemplate();
- var iHeight = Details.Height > 0 ? Details.Height : 600;
- var iWidth = Details.Width > 0 ? Details.Width : 800;
- Details.Height = double.NaN;
- Details.Width = double.NaN;
- OnEditorCreated?.Invoke(this, iHeight, iWidth);
- return true;
- }
- catch (Exception e)
- {
- MessageBox.Show(string.Format("Unable to Load XAML!\n\n{0}", e.Message));
- }
- return false;
- }
- private decimal GetSequence(DynamicGridColumn column)
- {
- if (OnGetSequence != null)
- return OnGetSequence.Invoke(column);
- return 999;
- }
- private void CreateLayout()
- {
- //Stopwatch sw = new Stopwatch();
- //sw.Start();
- IsCustomLayout = false;
- Content = null;
- Details = new DynamicTabControl();
- Details.VerticalAlignment = VerticalAlignment.Stretch;
- Details.HorizontalAlignment = HorizontalAlignment.Stretch;
- Details.Name = "Details";
-
- //Logger.Send(LogType.Information, "DEG.CreateLayout", String.Format("Created Tab Control: {0}", sw.ElapsedMilliseconds));
- //sw.Restart();
- var EditorGrids = new Dictionary<string, Grid>();
- CustomGrid = EnsureGrid(EditorGrids, "Custom Fields");
- EditorGrid = EnsureGrid(EditorGrids, "General");
-
- //Logger.Send(LogType.Information, "DEG.CreateLayout", String.Format("Ensured Grids: {0}", sw.ElapsedMilliseconds));
- //sw.Restart();
- Details.SelectionChanged += Details_SelectionChanged;
- Content = Details;
- editors.Clear();
- double fGeneralHeight = 30; // Allow for Tab Header
- //Logger.Send(LogType.Information, "DEG.CreateLayout", String.Format("Sorted Columns: {0}", sw.ElapsedMilliseconds));
- //sw.Restart();
- long total = 0;
- foreach (var column in _columns.OrderBy(x => GetSequence(x)))
- {
- var iProp = DatabaseSchema.Property(UnderlyingType, column.ColumnName);
- var editor = OnGetEditor?.Invoke(column);
- if (editor != null && iProp?.ShouldShowEditor() != true)
- {
- editor.Visible = Visible.Hidden;
- editor.Editable = Editable.Hidden;
- }
- OnGridCustomiseEditor?.Invoke(this, column, editor);
- if (editor != null && editor.Editable != Editable.Hidden)
- {
- var page = string.IsNullOrWhiteSpace(editor.Page) ? iProp is StandardProperty ? "General" : "Custom Fields" : editor.Page;
- var grid = EnsureGrid(EditorGrids, page);
- //List<Object> parameters = editor.Parameters != null ? editor.Parameters.ToList() : new List<object>();
- //bool bParams = true;
- BaseDynamicEditorControl? element = null;
- switch (editor)
- {
- case TextBoxEditor:
- element = new TextBoxEditorControl();
- break;
- case Core.RichTextEditor:
- element = new RichTextEditorControl();
- break;
- case URLEditor:
- element = new URLEditorControl();
- break;
- case CodeEditor:
- case UniqueCodeEditor:
- element = new CodeEditorControl();
- break;
- case CheckBoxEditor:
- element = new CheckBoxEditorControl();
- break;
- case DateTimeEditor:
- element = new DateTimeEditorControl();
- break;
- case DateEditor:
- element = new DateEditorControl { TodayVisible = (editor as DateEditor).TodayVisible };
- break;
- case TimeOfDayEditor:
- element = new TimeOfDayEditorControl { NowButtonVisible = false };
- break;
- case DurationEditor:
- element = new DurationEditorControl();
- break;
- case NotesEditor:
- element = new NotesEditorControl();
- break;
- case PINEditor:
- element = new PINEditorControl();
- break;
- case CheckListEditor:
- element = new CheckListBoxEditorControl();
- break;
- case MemoEditor:
- element = new MemoEditorControl();
- break;
- case JsonEditor:
- element = new JsonEditorControl();
- break;
- case LookupEditor:
- element = ClientFactory.IsSupported(((LookupEditor)editor).Type) ? new LookupEditorControl() : null;
- break;
- case PopupEditor:
- element = ClientFactory.IsSupported(((PopupEditor)editor).Type) ? new PopupEditorControl() : null;
- break;
- case CodePopupEditor:
- element = ClientFactory.IsSupported(((CodePopupEditor)editor).Type) ? new CodePopupEditorControl() : null;
- break;
- case EnumLookupEditor:
- case ComboLookupEditor:
- element = new LookupEditorControl();
- break;
- case EmbeddedImageEditor:
- element = new EmbeddedImageEditorControl
- {
- MaximumHeight = (editor as EmbeddedImageEditor).MaximumHeight,
- MaximumWidth = (editor as EmbeddedImageEditor).MaximumWidth,
- MaximumFileSize = (editor as EmbeddedImageEditor).MaximumFileSize
- };
- break;
- case FileNameEditor:
- element = new FileNameEditorControl
- {
- Filter = (editor as FileNameEditor).FileMask,
- AllowView = (editor as FileNameEditor).AllowView,
- RequireExisting = (editor as FileNameEditor).RequireExisting
- };
- break;
- case FolderEditor:
- element = new FolderEditorControl
- {
- InitialFolder = (editor as FolderEditor).InitialFolder
- };
- break;
- case MiscellaneousDocumentEditor:
- element = new DocumentEditorControl();
- break;
- case ImageDocumentEditor:
- element = new DocumentEditorControl();
- break;
- case VectorDocumentEditor:
- element = new DocumentEditorControl();
- break;
- case PDFDocumentEditor:
- element = new DocumentEditorControl();
- break;
- case PasswordEditor:
- element = new PasswordEditorControl();
- break;
- case CurrencyEditor:
- element = new CurrencyEditorControl();
- break;
- case DoubleEditor:
- element = new DoubleEditorControl();
- break;
- case IntegerEditor:
- element = new IntegerEditorControl();
- break;
- case Core.ScriptEditor:
- element = new ScriptEditorControl
- {
- SyntaxLanguage = (editor as Core.ScriptEditor).SyntaxLanguage
- };
- break;
- case TimestampEditor:
- element = new TimestampEditorControl();
- break;
- case ColorEditor:
- element = new ColorEditorControl();
- break;
- case FilterEditor filter:
- element = new FilterEditorControl { FilterType = filter.Type! };
- break;
- case ExpressionEditor expression:
- element = new ExpressionEditorControl();
- break;
- default:
- element = null;
- break;
- }
- if (element != null)
- {
- element.EditorDefinition = editor; //22
- element.IsEnabled = editor.Editable == Editable.Enabled;
- if (!string.IsNullOrWhiteSpace(editor.ToolTip))
- {
- element.ToolTip = new ToolTip() { Content = editor.ToolTip };
- }
- var label = new Label();
- label.Content = CoreUtils.Neatify(editor.Caption); // 2
- label.Margin = new Thickness(0F, 0F, 0F, 0F);
- label.HorizontalAlignment = HorizontalAlignment.Stretch;
- label.VerticalAlignment = VerticalAlignment.Stretch;
- label.HorizontalContentAlignment = HorizontalAlignment.Left;
- label.VerticalContentAlignment = VerticalAlignment.Center;
- label.SetValue(Grid.RowProperty, grid.RowDefinitions.Count);
- label.SetValue(Grid.ColumnProperty, 0);
- label.Visibility = string.IsNullOrWhiteSpace(editor.Caption) ? Visibility.Collapsed : Visibility.Visible;
- grid.Children.Add(label);
- element.ColumnName = column.ColumnName;
- element.Color = editor is UniqueCodeEditor ? Color.FromArgb(0xFF, 0xF6, 0xC9, 0xE8) : Colors.LightYellow;
- editors.Add(element);
- element.Margin = new Thickness(5F, 2.5F, 5F, 2.5F);
- double iHeight = element.DesiredHeight();
- if (iHeight == int.MaxValue)
- {
- grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
- fGeneralHeight += grid == EditorGrid ? element.MinHeight + 5.0F : 0.0F;
- }
- else
- {
- grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(iHeight + 5.0F) });
- fGeneralHeight += grid == EditorGrid ? iHeight + 5.0F : 0.0F;
- }
- double iWidth = element.DesiredWidth();
- if (iWidth == int.MaxValue)
- {
- element.HorizontalAlignment = HorizontalAlignment.Stretch;
- }
- else
- {
- element.HorizontalAlignment = HorizontalAlignment.Left;
- element.Width = iWidth;
- }
- element.SetValue(Grid.RowProperty, grid.RowDefinitions.Count - 1);
- element.SetValue(Grid.ColumnProperty, 1);
- grid.Children.Add(element);
- }
- }
- }
- //Logger.Send(LogType.Information, "DEG.CreateLayout", String.Format("Created Editors: {0}", sw.ElapsedMilliseconds));
- //sw.Restart();
-
- OnEditorCreated?.Invoke(this, fGeneralHeight, 800);
- var custom = Details.Items[Details.Items.Count - 1] as DynamicTabItem;
- custom.Visibility = CustomGrid.Children.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
-
- //Logger.Send(LogType.Information, "DEG.CreateLayout", String.Format("Finalised: {0}", sw.ElapsedMilliseconds));
- //sw.Stop();
- }
- private Grid EnsureGrid(Dictionary<string, Grid> grids, string caption)
- {
- if (grids.ContainsKey(caption))
- return grids[caption];
- // Create Editor, ScrollViewer and TabItem for Dynamic Editor
- var result = new Grid
- {
- HorizontalAlignment = HorizontalAlignment.Stretch,
- VerticalAlignment = VerticalAlignment.Stretch,
- //Background = new SolidColorBrush(Colors.Blue),
- Margin = new Thickness(0, 2.5, 0, 2.5)
- };
- result.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
- result.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
- var scroll = new ScrollViewer
- {
- HorizontalAlignment = HorizontalAlignment.Stretch,
- VerticalAlignment = VerticalAlignment.Stretch,
- VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
- Padding = new Thickness(2)
- };
- scroll.Content = result;
- var border = new Border
- {
- BorderBrush = new SolidColorBrush(Colors.Gray),
- Background = new SolidColorBrush(Colors.White),
- BorderThickness = new Thickness(0.75)
- };
- border.Child = scroll;
- var tab = new DynamicTabItem();
- tab.Header = caption;
- tab.Content = border;
- if (Details.Items.Count == 0)
- Details.Items.Add(tab);
- else
- Details.Items.Insert(Details.Items.Count - 1, tab);
- grids[caption] = result;
- return result;
- }
- //List<TabItem> configuredpages = new List<TabItem>();
- private void Details_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- if (bChanging || Details?.SelectedItem == null || e.OriginalSource != Details)
- return;
- bChanging = true;
- try
- {
- var tab = Details.SelectedItem as DynamicTabItem;
- var page = tab.Content as IDynamicEditorPage;
- if (page != null)
- {
- if (!page.Ready)
- using (new WaitCursor())
- {
- OnLoadPage?.Invoke(page);
- }
- }
- else
- {
- if (!_loaded || e.RemovedItems.Count == 0 || e.AddedItems.Count == 0 || e.AddedItems?[0] == e.RemovedItems?[0])
- return;
- //if (!configuredpages.Contains(tab))
- //{
- // ConfigureEditors(eds);
- // configuredpages.Add(tab);
- //}
- var eds = editors
- .Where(x => x is BaseDynamicEditorControl &&
- (x as FrameworkElement).Parent == ((tab.Content as Border).Child as ScrollViewer).Content)
- .Select(x => (BaseDynamicEditorControl)x);
- foreach (var ed in eds)
- {
- var editorvalue = ed.GetValue();
- var entityvalue = OnGetPropertyValue?.Invoke(this, ed.ColumnName);
- if (!Equals(editorvalue, entityvalue))
- {
- ed.Loaded = false;
- ed.SetValue(entityvalue);
- ed.Loaded = true;
- }
- }
- }
- OnSelectPage?.Invoke(tab, null);
- }
- finally
- {
- bChanging = false;
- }
- }
- public void UnloadPages(bool saved)
- {
- foreach (var page in Pages)
- if (page.Ready)
- OnUnloadPage?.Invoke(page, saved);
- }
- private void Lookup_OnUpdateOtherEditor(string columnname, object value)
- {
- var editor = editors.FirstOrDefault(x => x.ColumnName.Equals(columnname));
- if (editor != null)
- CoreUtils.SetPropertyValue(editor, "Value", value);
- }
-
- private string FormatXML(string xml)
- {
- var result = "";
- var mStream = new MemoryStream();
- var writer = new XmlTextWriter(mStream, Encoding.Unicode);
- var document = new XmlDocument();
- try
- {
- // Load the XmlDocument with the XML.
- document.LoadXml(xml);
- writer.Formatting = Formatting.Indented;
- // Write the XML into a formatting XmlTextWriter
- document.WriteContentTo(writer);
- writer.Flush();
- mStream.Flush();
- // Have to rewind the MemoryStream in order to read
- // its contents.
- mStream.Position = 0;
- // Read MemoryStream contents into a StreamReader.
- var sReader = new StreamReader(mStream);
- // Extract the text from the StreamReader.
- var formattedXml = sReader.ReadToEnd();
- result = formattedXml;
- }
- catch (XmlException)
- {
- // Handle the exception
- }
- mStream.Close();
- writer.Close();
- return result;
- }
- public void EditLayout()
- {
- ClearPages();
- //UnloadEditorValues();
- var xaml = new GlobalConfiguration<ScreenLayout>(_layoutname).Load().XAML;
- if (string.IsNullOrWhiteSpace(xaml))
- {
- Details.Height = Details.ActualHeight;
- Details.Width = Details.ActualWidth;
- //xaml = XamlWriter.Save(GetParentWindow(Details));
- xaml = XamlWriter.Save(Details);
- }
- xaml = FormatXML(xaml);
- var scripteditor = new ScriptEditor(xaml, SyntaxLanguage.XAML);
- if (scripteditor.ShowDialog() == true)
- {
- var layout = new ScreenLayout { XAML = scripteditor.Script };
- new GlobalConfiguration<ScreenLayout>(_layoutname).Save(layout);
- Content = null;
- if (!LoadLayout(layout.XAML))
- if (!LoadLayout(xaml))
- CreateLayout();
- Details.ApplyTemplate();
- Application.Current.Dispatcher.Invoke(() =>
- {
- ConfigureEditors();
- LoadEditorValues();
- AddPages();
- DoReconfigureEditors();
- }, DispatcherPriority.Render);
- }
- }
- internal void ResetLayout()
- {
- new GlobalConfiguration<ScreenLayout>(_layoutname).Delete();
- ClearPages();
- //UnloadEditorValues();
- CreateLayout();
- LoadEditorValues();
- AddPages();
- DoReconfigureEditors();
- }
- private void LoadEditor(string columnname, object value)
- {
- }
- private void EditorValueChanged(IDynamicEditorControl sender, Dictionary<string, object> values)
- {
- //Logger.Send(LogType.Information, "", string.Format("DynamicEditorGrid.EditorValueChanged({0})", values.Keys.Count));
- var changededitors = new Dictionary<string, object>();
- foreach (var key in values.Keys)
- {
- var changedcolumns = OnEditorValueChanged?.Invoke(this, key, values[key]);
- if (changedcolumns != null)
- foreach (var change in changedcolumns.Keys)
- if (editors.Any(x => x.ColumnName.Equals(change)) && !changededitors.ContainsKey(change) && !change.Equals(sender.ColumnName))
- changededitors[change] = changedcolumns[change];
- }
- if (changededitors.Any())
- LoadEditorValues(changededitors);
- DoReconfigureEditors();
- }
- private void LoadEditorValues(Dictionary<string, object> changededitors = null)
- {
- var columnnames = changededitors != null ? changededitors.Keys.ToArray() : editors.Select(x => x.ColumnName).ToArray();
- foreach (var columnname in columnnames)
- {
- var editor = editors.FirstOrDefault(x => x.ColumnName.Equals(columnname));
- if (editor == null)
- continue;
- var bLoaded = editor.Loaded;
- editor.Loaded = false;
- if (changededitors != null && changededitors.ContainsKey(columnname))
- {
- CoreUtils.SetPropertyValue(editor, "Value", changededitors[columnname]);
- }
- else
- {
- var curvalue = OnGetPropertyValue?.Invoke(this, columnname);
- try
- {
- CoreUtils.SetPropertyValue(editor, "Value", curvalue);
- }
- catch (Exception e)
- {
- MessageBox.Show(string.Format("Unable to set editor value for {0} -> {1}", columnname, curvalue));
- }
- CoreUtils.SetPropertyValue(editor, "Changed", false);
- }
- editor.Loaded = bLoaded;
- editor.OnEditorValueChanged += EditorValueChanged;
- }
- }
- public virtual void DoReconfigureEditors()
- {
- ReconfigureEditors?.Invoke(this);
- }
- public void Load(string layoutname, DynamicEditorPages pages = null)
- {
- _layoutname = layoutname;
- Pages = pages;
- //Stopwatch sw = new Stopwatch();
- //sw.Start();
- _columns = OnCustomiseColumns?.Invoke(this, null);
- //Logger.Send(LogType.Information, "DEG.Load", String.Format("Loaded Columns: {0}", sw.ElapsedMilliseconds));
- //sw.Restart();
-
- var layout = new GlobalConfiguration<ScreenLayout>(_layoutname).Load();
- //Logger.Send(LogType.Information, "DEG.Load", String.Format("Loaded Layout: {0}", sw.ElapsedMilliseconds));
- //sw.Restart();
- if (!LoadLayout(layout.XAML))
- CreateLayout();
-
- //Logger.Send(LogType.Information, "DEG.Load", String.Format("Created Layout: {0}", sw.ElapsedMilliseconds));
- //sw.Restart();
-
- }
- protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
- {
- base.OnRenderSizeChanged(sizeInfo);
- foreach (var columnname in editors.Select(x => x.ColumnName).ToArray())
- {
- var editor = editors.FirstOrDefault(x => x.ColumnName.Equals(columnname));
- editor.Loaded = true;
- }
- }
- public bool Unload()
- {
- ClearPages();
- var bChanged = false;
- foreach (var columnname in changes.Keys)
- {
- OnSetPropertyValue?.Invoke(this, columnname, changes[columnname]);
- bChanged = true;
- }
- return bChanged;
- }
- private void AddPages()
- {
- if (Pages != null)
- using (new WaitCursor())
- {
- foreach (var page in Pages.OrderBy(x => x.Order()).ThenBy(x => x.Caption()))
- {
- var tab = new DynamicTabItem();
- tab.Header = page.Caption();
- tab.Content = page;
- Details.Items.Insert(Details.Items.Count - 1, tab);
- pagemap[page] = tab;
- if (PreloadPages)
- OnLoadPage?.Invoke(page);
- page.EditorGrid = this;
- }
- }
- //if (Details.Items.Count <= 2)
- // ((TabItem)Details.Items[0]).Visibility = Visibility.Collapsed;
- }
- private void ClearPages()
- {
- foreach (var page in pagemap.Keys)
- {
- var tab = pagemap[page];
- tab.Content = null;
- Details.Items.Remove(tab);
- }
- pagemap.Clear();
- //if (_pages != null)
- //{
- // foreach (var page in _pages)
- // {
- // var tab = Details.Items.OfType<TabItem>().FirstOrDefault(x => x.Content.Equals(page));
- // if (tab != null)
- // {
- // tab.Content = null;
- // Details.Items.Remove(tab);
- // }
- // }
- //}
- }
- }
- }
|