From 14a9838be61b8d75e6c50c300f52f124cacc545f Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 9 Mar 2024 11:59:38 +1000 Subject: [PATCH 001/181] Installing base prism package --- AdamController/AdamController.csproj | 1 + AdamController/App.xaml | 13 ++++---- AdamController/App.xaml.cs | 31 +++++++++++++++++-- .../AdamControllerLibrary.csproj | 1 + 4 files changed, 37 insertions(+), 9 deletions(-) diff --git a/AdamController/AdamController.csproj b/AdamController/AdamController.csproj index 6182832..bf29ae5 100644 --- a/AdamController/AdamController.csproj +++ b/AdamController/AdamController.csproj @@ -90,6 +90,7 @@ + diff --git a/AdamController/App.xaml b/AdamController/App.xaml index db91ed2..6d524d9 100644 --- a/AdamController/App.xaml +++ b/AdamController/App.xaml @@ -1,8 +1,8 @@ - + @@ -18,4 +18,5 @@ - + + diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index a99262e..3de9e71 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -9,10 +9,30 @@ using System.Windows; using System.Xml; +#region prism + +using Prism.Ioc; +using Prism.DryIoc; +using Prism.Modularity; + +#endregion + namespace AdamController { - public partial class App : Application + public partial class App : PrismApplication { + + public App() + { + + } + + protected override Window CreateShell() + { + var w = Container.Resolve(); + return w; + } + protected override void OnStartup(StartupEventArgs e) { LoadHighlighting(); @@ -39,11 +59,16 @@ protected override void OnStartup(StartupEventArgs e) WebApi.Client.v1.BaseApi.SetAuthenticationHeader(login, password); - - base.OnStartup(e); } + protected override void RegisterTypes(IContainerRegistry containerRegistry) + { + //containerRegistry.Register(); + // register other needed services here + } + + private static void LoadHighlighting() { try diff --git a/AdamControllerLibrary/AdamControllerLibrary.csproj b/AdamControllerLibrary/AdamControllerLibrary.csproj index c42b2b7..e5898a9 100644 --- a/AdamControllerLibrary/AdamControllerLibrary.csproj +++ b/AdamControllerLibrary/AdamControllerLibrary.csproj @@ -18,6 +18,7 @@ + From b1bd8c49bd406ae91fe65b6fd0ee203afbc1fbf4 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 9 Mar 2024 12:22:44 +1000 Subject: [PATCH 002/181] Implement viewmodel locator --- AdamController/App.xaml.cs | 7 ++-- AdamController/Helpers/WindowShowerHelpers.cs | 34 ++++++++++--------- .../ViewModels/Common/BaseViewModel.cs | 1 - .../HamburgerMenu/HamburgerMenuView.cs | 2 +- ...nWindowView.cs => MainWindowViewModels.cs} | 20 +++++------ .../ViewModels/ScratchControlView.cs | 6 ++-- .../ViewModels/ScriptEditorControlView.cs | 6 ++-- AdamController/Views/MainWindow.xaml | 3 +- 8 files changed, 41 insertions(+), 38 deletions(-) rename AdamController/ViewModels/{MainWindowView.cs => MainWindowViewModels.cs} (97%) diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 3de9e71..6da9bb8 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -14,6 +14,7 @@ using Prism.Ioc; using Prism.DryIoc; using Prism.Modularity; +using MahApps.Metro.Controls; #endregion @@ -29,19 +30,19 @@ public App() protected override Window CreateShell() { - var w = Container.Resolve(); - return w; + var window = Container.Resolve(); + return window; } protected override void OnStartup(StartupEventArgs e) { + LoadHighlighting(); // side menu context, MUST inherit from MainViewModel // HamburgerMenuView : MainWindowView // and MainWindowView MUST inherit from BaseViewModel // MainWindowView : BaseViewModel - new WindowShowerHelpers(new MainWindow(), new HamburgerMenuView()).Show(); _ = FolderHelper.CreateAppDataFolder(); diff --git a/AdamController/Helpers/WindowShowerHelpers.cs b/AdamController/Helpers/WindowShowerHelpers.cs index df71d81..1aafeec 100644 --- a/AdamController/Helpers/WindowShowerHelpers.cs +++ b/AdamController/Helpers/WindowShowerHelpers.cs @@ -7,7 +7,6 @@ namespace AdamController.Helpers { public class WindowShowerHelpers { - private readonly MetroWindow mWindow; private readonly bool mIsModal; public WindowShowerHelpers(MetroWindow window, object dataContext) @@ -15,17 +14,17 @@ public WindowShowerHelpers(MetroWindow window, object dataContext) IWindowParam param = dataContext as IWindowParam ?? new DefaultWindowParam(); mIsModal = param.IsModal; - mWindow = window; - mWindow.DataContext = dataContext; - mWindow.Title = param.WindowTitle; - mWindow.Height = param.Height; - mWindow.Width = param.Width; - mWindow.ResizeMode = param.ResizeMode; - mWindow.WindowStartupLocation = param.WindowStartupLocation; - mWindow.TitleCharacterCasing = param.TitleCharacterCasing; - mWindow.WindowState = param.WindowState; + Window = window; + Window.DataContext = dataContext; + Window.Title = param.WindowTitle; + Window.Height = param.Height; + Window.Width = param.Width; + Window.ResizeMode = param.ResizeMode; + Window.WindowStartupLocation = param.WindowStartupLocation; + Window.TitleCharacterCasing = param.TitleCharacterCasing; + Window.WindowState = param.WindowState; - mWindow.Closed += (sender, e) => param.OnClosed(window); + Window.Closed += (sender, e) => param.OnClosed(window); } public WindowShowerHelpers(UserControl userControl, object dataContext) @@ -48,9 +47,10 @@ public WindowShowerHelpers(UserControl userControl, object dataContext) }; window.Closed += (sender, e) => param.OnClosed(window); - mWindow = window; + Window = window; } + public WindowShowerHelpers(UserControl userControl, params object[] dataContext) { IWindowParam param = dataContext[0] as IWindowParam ?? new DefaultWindowParam(); @@ -70,14 +70,16 @@ public WindowShowerHelpers(UserControl userControl, params object[] dataContext) }; window.Closed += (sender, e) => param.OnClosed(window); - mWindow = window; + Window = window; } + public readonly MetroWindow Window; + #region Show public void Show() { - if (mWindow == null) + if (Window == null) { return; } @@ -86,7 +88,7 @@ public void Show() { try { - _ = mWindow.ShowDialog(); + _ = Window.ShowDialog(); } catch { @@ -98,7 +100,7 @@ public void Show() { try { - mWindow.Show(); + Window.Show(); } catch { diff --git a/AdamController/ViewModels/Common/BaseViewModel.cs b/AdamController/ViewModels/Common/BaseViewModel.cs index 1826dbc..0fdbd3f 100644 --- a/AdamController/ViewModels/Common/BaseViewModel.cs +++ b/AdamController/ViewModels/Common/BaseViewModel.cs @@ -17,7 +17,6 @@ public abstract class BaseViewModel : BindableBase, IWindowParam /// Default window is modal. Ovverride this to false if window main. /// public virtual bool IsModal => true; - public virtual double Height => 1000; public virtual double Width => 1400; diff --git a/AdamController/ViewModels/HamburgerMenu/HamburgerMenuView.cs b/AdamController/ViewModels/HamburgerMenu/HamburgerMenuView.cs index 898d632..da7e1a1 100644 --- a/AdamController/ViewModels/HamburgerMenu/HamburgerMenuView.cs +++ b/AdamController/ViewModels/HamburgerMenu/HamburgerMenuView.cs @@ -5,7 +5,7 @@ namespace AdamController.ViewModels.HamburgerMenu { - public class HamburgerMenuView : MainWindowView + public class HamburgerMenuView : MainWindowViewModels { private ObservableCollection mMenuItems; private ObservableCollection mMenuOptionItems; diff --git a/AdamController/ViewModels/MainWindowView.cs b/AdamController/ViewModels/MainWindowViewModels.cs similarity index 97% rename from AdamController/ViewModels/MainWindowView.cs rename to AdamController/ViewModels/MainWindowViewModels.cs index cfa0e0a..b1d962a 100644 --- a/AdamController/ViewModels/MainWindowView.cs +++ b/AdamController/ViewModels/MainWindowViewModels.cs @@ -17,7 +17,7 @@ namespace AdamController.ViewModels { - public class MainWindowView : BaseViewModel + public class MainWindowViewModels : BindableBase//BaseViewModel { #region Const @@ -31,7 +31,7 @@ public class MainWindowView : BaseViewModel #endregion - public MainWindowView() + public MainWindowViewModels() { ComunicateHelper.OnAdamTcpConnectedEvent += OnTcpConnected; ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; @@ -662,16 +662,16 @@ private void SelectGridColorDependingSelectedTheme(BlocklyTheme theme) #region IWindowParam - public override string WindowTitle => $"Adam IDE {Assembly.GetExecutingAssembly().GetName().Version}"; - public override bool IsModal => false; - public override WindowState WindowState => WindowState.Maximized; + //public override string WindowTitle => $"Adam IDE {Assembly.GetExecutingAssembly().GetName().Version}"; + //public override bool IsModal => false; + //public override WindowState WindowState => WindowState.Maximized; - public override void OnClosed(Window window) - { - ComunicateHelper.DisconnectAllAndDestroy(); + //public override void OnClosed(Window window) + //{ + // ComunicateHelper.DisconnectAllAndDestroy(); - base.OnClosed(window); - } + // base.OnClosed(window); + //} #endregion } diff --git a/AdamController/ViewModels/ScratchControlView.cs b/AdamController/ViewModels/ScratchControlView.cs index ca1bd57..ad0e7eb 100644 --- a/AdamController/ViewModels/ScratchControlView.cs +++ b/AdamController/ViewModels/ScratchControlView.cs @@ -100,7 +100,7 @@ private void PythonExecuteEvent() { PythonScriptExecuteHelper.OnExecuteStartEvent += (message) => { - if (MainWindowView.GetSelectedPageIndex != 0) + if (MainWindowViewModels.GetSelectedPageIndex != 0) return; mIsWarningStackOwerflowAlreadyShow = false; @@ -112,7 +112,7 @@ private void PythonExecuteEvent() PythonScriptExecuteHelper.OnStandartOutputEvent += (message) => { - if (MainWindowView.GetSelectedPageIndex != 0) + if (MainWindowViewModels.GetSelectedPageIndex != 0) return; if(ResultTextEditorLength > 10000) @@ -134,7 +134,7 @@ private void PythonExecuteEvent() PythonScriptExecuteHelper.OnExecuteFinishEvent += (message) => { - if (MainWindowView.GetSelectedPageIndex != 0) + if (MainWindowViewModels.GetSelectedPageIndex != 0) return; FinishExecuteProgram(); diff --git a/AdamController/ViewModels/ScriptEditorControlView.cs b/AdamController/ViewModels/ScriptEditorControlView.cs index 9e4380a..33ac6c3 100644 --- a/AdamController/ViewModels/ScriptEditorControlView.cs +++ b/AdamController/ViewModels/ScriptEditorControlView.cs @@ -31,7 +31,7 @@ private void PythonExecuteEvent() { PythonScriptExecuteHelper.OnExecuteStartEvent += (message) => { - if (MainWindowView.GetSelectedPageIndex != 1) + if (MainWindowViewModels.GetSelectedPageIndex != 1) return; ResultTextEditor = string.Empty; @@ -42,7 +42,7 @@ private void PythonExecuteEvent() PythonScriptExecuteHelper.OnStandartOutputEvent += (message) => { - if (MainWindowView.GetSelectedPageIndex != 1) + if (MainWindowViewModels.GetSelectedPageIndex != 1) return; if (ResultTextEditorLength > 10000) @@ -64,7 +64,7 @@ private void PythonExecuteEvent() PythonScriptExecuteHelper.OnExecuteFinishEvent += (message) => { - if (MainWindowView.GetSelectedPageIndex != 1) + if (MainWindowViewModels.GetSelectedPageIndex != 1) return; IsCodeExecuted = false; diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index 668a0d9..ec98417 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -15,7 +15,8 @@ mc:Ignorable="d" WindowState="Maximized" ShowIconOnTitleBar="True" - + xmlns:prism="http://prismlibrary.com/" + prism:ViewModelLocator.AutoWireViewModel="True" Title="{Binding WindowTitle}"> From a6c8c17558d7d362d45b1c6644d3474ae12fe976 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 9 Mar 2024 12:28:13 +1000 Subject: [PATCH 003/181] Fix naming --- .../ViewModels/HamburgerMenu/HamburgerMenuView.cs | 2 +- .../{MainWindowViewModels.cs => MainWindowViewModel.cs} | 5 ++--- AdamController/ViewModels/ScratchControlView.cs | 6 +++--- AdamController/ViewModels/ScriptEditorControlView.cs | 6 +++--- 4 files changed, 9 insertions(+), 10 deletions(-) rename AdamController/ViewModels/{MainWindowViewModels.cs => MainWindowViewModel.cs} (99%) diff --git a/AdamController/ViewModels/HamburgerMenu/HamburgerMenuView.cs b/AdamController/ViewModels/HamburgerMenu/HamburgerMenuView.cs index da7e1a1..51d9f59 100644 --- a/AdamController/ViewModels/HamburgerMenu/HamburgerMenuView.cs +++ b/AdamController/ViewModels/HamburgerMenu/HamburgerMenuView.cs @@ -5,7 +5,7 @@ namespace AdamController.ViewModels.HamburgerMenu { - public class HamburgerMenuView : MainWindowViewModels + public class HamburgerMenuView : MainWindowViewModel { private ObservableCollection mMenuItems; private ObservableCollection mMenuOptionItems; diff --git a/AdamController/ViewModels/MainWindowViewModels.cs b/AdamController/ViewModels/MainWindowViewModel.cs similarity index 99% rename from AdamController/ViewModels/MainWindowViewModels.cs rename to AdamController/ViewModels/MainWindowViewModel.cs index b1d962a..a0f0f8a 100644 --- a/AdamController/ViewModels/MainWindowViewModels.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -10,14 +10,13 @@ using System; using System.Collections.ObjectModel; using System.Linq; -using System.Reflection; using System.Windows; using System.Windows.Media; using System.Windows.Threading; namespace AdamController.ViewModels { - public class MainWindowViewModels : BindableBase//BaseViewModel + public class MainWindowViewModel : BindableBase//BaseViewModel { #region Const @@ -31,7 +30,7 @@ public class MainWindowViewModels : BindableBase//BaseViewModel #endregion - public MainWindowViewModels() + public MainWindowViewModel() { ComunicateHelper.OnAdamTcpConnectedEvent += OnTcpConnected; ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; diff --git a/AdamController/ViewModels/ScratchControlView.cs b/AdamController/ViewModels/ScratchControlView.cs index ad0e7eb..3ad900a 100644 --- a/AdamController/ViewModels/ScratchControlView.cs +++ b/AdamController/ViewModels/ScratchControlView.cs @@ -100,7 +100,7 @@ private void PythonExecuteEvent() { PythonScriptExecuteHelper.OnExecuteStartEvent += (message) => { - if (MainWindowViewModels.GetSelectedPageIndex != 0) + if (MainWindowViewModel.GetSelectedPageIndex != 0) return; mIsWarningStackOwerflowAlreadyShow = false; @@ -112,7 +112,7 @@ private void PythonExecuteEvent() PythonScriptExecuteHelper.OnStandartOutputEvent += (message) => { - if (MainWindowViewModels.GetSelectedPageIndex != 0) + if (MainWindowViewModel.GetSelectedPageIndex != 0) return; if(ResultTextEditorLength > 10000) @@ -134,7 +134,7 @@ private void PythonExecuteEvent() PythonScriptExecuteHelper.OnExecuteFinishEvent += (message) => { - if (MainWindowViewModels.GetSelectedPageIndex != 0) + if (MainWindowViewModel.GetSelectedPageIndex != 0) return; FinishExecuteProgram(); diff --git a/AdamController/ViewModels/ScriptEditorControlView.cs b/AdamController/ViewModels/ScriptEditorControlView.cs index 33ac6c3..51fa233 100644 --- a/AdamController/ViewModels/ScriptEditorControlView.cs +++ b/AdamController/ViewModels/ScriptEditorControlView.cs @@ -31,7 +31,7 @@ private void PythonExecuteEvent() { PythonScriptExecuteHelper.OnExecuteStartEvent += (message) => { - if (MainWindowViewModels.GetSelectedPageIndex != 1) + if (MainWindowViewModel.GetSelectedPageIndex != 1) return; ResultTextEditor = string.Empty; @@ -42,7 +42,7 @@ private void PythonExecuteEvent() PythonScriptExecuteHelper.OnStandartOutputEvent += (message) => { - if (MainWindowViewModels.GetSelectedPageIndex != 1) + if (MainWindowViewModel.GetSelectedPageIndex != 1) return; if (ResultTextEditorLength > 10000) @@ -64,7 +64,7 @@ private void PythonExecuteEvent() PythonScriptExecuteHelper.OnExecuteFinishEvent += (message) => { - if (MainWindowViewModels.GetSelectedPageIndex != 1) + if (MainWindowViewModel.GetSelectedPageIndex != 1) return; IsCodeExecuted = false; From 6a21acc11f31a7e6e5489e4d2f126ee8f3d5f28a Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 9 Mar 2024 12:40:45 +1000 Subject: [PATCH 004/181] Implemen test service --- AdamController/App.xaml.cs | 4 +--- AdamController/Services/ITestService.cs | 16 ++++++++++++++ .../HamburgerMenu/HamburgerMenuView.cs | 3 ++- .../ViewModels/MainWindowViewModel.cs | 22 ++++++++++++++++++- 4 files changed, 40 insertions(+), 5 deletions(-) create mode 100644 AdamController/Services/ITestService.cs diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 6da9bb8..a8953ee 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -1,6 +1,5 @@ using AdamController.Helpers; using AdamController.Properties; -using AdamController.ViewModels.HamburgerMenu; using AdamController.Views; using ControlzEx.Theming; using ICSharpCode.AvalonEdit.Highlighting; @@ -65,8 +64,7 @@ protected override void OnStartup(StartupEventArgs e) protected override void RegisterTypes(IContainerRegistry containerRegistry) { - //containerRegistry.Register(); - // register other needed services here + containerRegistry.Register(); } diff --git a/AdamController/Services/ITestService.cs b/AdamController/Services/ITestService.cs new file mode 100644 index 0000000..6458604 --- /dev/null +++ b/AdamController/Services/ITestService.cs @@ -0,0 +1,16 @@ +namespace AdamController.Services +{ + public interface ITestService + { + public string GetMessage(); + } + + + public class TestService : ITestService + { + public string GetMessage() + { + return "Is test message"; + } + } +} diff --git a/AdamController/ViewModels/HamburgerMenu/HamburgerMenuView.cs b/AdamController/ViewModels/HamburgerMenu/HamburgerMenuView.cs index 51d9f59..6b4703b 100644 --- a/AdamController/ViewModels/HamburgerMenu/HamburgerMenuView.cs +++ b/AdamController/ViewModels/HamburgerMenu/HamburgerMenuView.cs @@ -1,4 +1,5 @@  +using AdamController.Services; using MahApps.Metro.IconPacks; using System.Collections.ObjectModel; @@ -10,7 +11,7 @@ public class HamburgerMenuView : MainWindowViewModel private ObservableCollection mMenuItems; private ObservableCollection mMenuOptionItems; - public HamburgerMenuView() + public HamburgerMenuView(ITestService testService) : base(testService) { CreateMenuItems(); } diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index a0f0f8a..ab314a9 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -4,12 +4,15 @@ using AdamController.Helpers; using AdamController.Model; using AdamController.Properties; +using AdamController.Services; using AdamController.ViewModels.Common; using AdamController.WebApi.Client.v1; +using LibVLCSharp.Shared; using MahApps.Metro.IconPacks; using System; using System.Collections.ObjectModel; using System.Linq; +using System.Reflection; using System.Windows; using System.Windows.Media; using System.Windows.Threading; @@ -30,8 +33,25 @@ public class MainWindowViewModel : BindableBase//BaseViewModel #endregion - public MainWindowViewModel() + #region Services + + private Services.ITestService mTestService; + + #endregion + + #region Fields + + public string WindowTitle { get; } //=> $"Adam IDE {Assembly.GetExecutingAssembly().GetName().Version}"; + + #endregion + + public MainWindowViewModel(ITestService testService) { + + mTestService = testService; + WindowTitle = mTestService.GetMessage(); + + ComunicateHelper.OnAdamTcpConnectedEvent += OnTcpConnected; ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; ComunicateHelper.OnAdamTcpReconnected += OnTcpReconnected; From ac154552daeb796b2057c2dce7c9532e08dbc3bf Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 9 Mar 2024 12:50:06 +1000 Subject: [PATCH 005/181] Fix naming library project --- AdamController.sln | 2 +- AdamController/AdamController.csproj | 2 +- AdamController/ViewModels/MainWindowViewModel.cs | 3 +-- ...AdamControllerLibrary.csproj => AdamController.Core.csproj} | 0 4 files changed, 3 insertions(+), 4 deletions(-) rename AdamControllerLibrary/{AdamControllerLibrary.csproj => AdamController.Core.csproj} (100%) diff --git a/AdamController.sln b/AdamController.sln index 9c36a7d..465096e 100644 --- a/AdamController.sln +++ b/AdamController.sln @@ -9,7 +9,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamController", "AdamContr {1FCB70D5-1BBC-414D-8DFB-4AEA7D45B1D1} = {1FCB70D5-1BBC-414D-8DFB-4AEA7D45B1D1} EndProjectSection EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamControllerLibrary", "AdamControllerLibrary\AdamControllerLibrary.csproj", "{1FCB70D5-1BBC-414D-8DFB-4AEA7D45B1D1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamController.Core", "AdamControllerLibrary\AdamController.Core.csproj", "{1FCB70D5-1BBC-414D-8DFB-4AEA7D45B1D1}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{0A650D34-3B1C-4EA6-8F8B-F5B6B21025E6}" ProjectSection(SolutionItems) = preProject diff --git a/AdamController/AdamController.csproj b/AdamController/AdamController.csproj index bf29ae5..8283527 100644 --- a/AdamController/AdamController.csproj +++ b/AdamController/AdamController.csproj @@ -59,7 +59,7 @@ - + diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index ab314a9..d470d16 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -41,7 +41,7 @@ public class MainWindowViewModel : BindableBase//BaseViewModel #region Fields - public string WindowTitle { get; } //=> $"Adam IDE {Assembly.GetExecutingAssembly().GetName().Version}"; + public string WindowTitle => $"Adam IDE {Assembly.GetExecutingAssembly().GetName().Version}"; #endregion @@ -49,7 +49,6 @@ public MainWindowViewModel(ITestService testService) { mTestService = testService; - WindowTitle = mTestService.GetMessage(); ComunicateHelper.OnAdamTcpConnectedEvent += OnTcpConnected; diff --git a/AdamControllerLibrary/AdamControllerLibrary.csproj b/AdamControllerLibrary/AdamController.Core.csproj similarity index 100% rename from AdamControllerLibrary/AdamControllerLibrary.csproj rename to AdamControllerLibrary/AdamController.Core.csproj From c9f32db1424911b213fc10a35278c6e99bbb9592 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 9 Mar 2024 13:12:45 +1000 Subject: [PATCH 006/181] implement region view in core --- .../AdamController.Core.csproj | 4 ++ AdamControllerLibrary/DialogNames.cs | 6 ++ .../Extensions/DialogServiceExtension.cs | 12 ++++ .../Mvvm/RegionViewModelBase.cs | 55 +++++++++++++++++++ AdamControllerLibrary/Mvvm/ViewModelBase.cs | 13 +++++ AdamControllerLibrary/RegionNames.cs | 6 ++ AdamControllerLibrary/app.config | 3 - 7 files changed, 96 insertions(+), 3 deletions(-) create mode 100644 AdamControllerLibrary/DialogNames.cs create mode 100644 AdamControllerLibrary/Extensions/DialogServiceExtension.cs create mode 100644 AdamControllerLibrary/Mvvm/RegionViewModelBase.cs create mode 100644 AdamControllerLibrary/Mvvm/ViewModelBase.cs create mode 100644 AdamControllerLibrary/RegionNames.cs delete mode 100644 AdamControllerLibrary/app.config diff --git a/AdamControllerLibrary/AdamController.Core.csproj b/AdamControllerLibrary/AdamController.Core.csproj index e5898a9..94cfe6d 100644 --- a/AdamControllerLibrary/AdamController.Core.csproj +++ b/AdamControllerLibrary/AdamController.Core.csproj @@ -24,4 +24,8 @@ + + + + \ No newline at end of file diff --git a/AdamControllerLibrary/DialogNames.cs b/AdamControllerLibrary/DialogNames.cs new file mode 100644 index 0000000..b936b80 --- /dev/null +++ b/AdamControllerLibrary/DialogNames.cs @@ -0,0 +1,6 @@ +namespace AdamController.Core +{ + public class DialogNames + { + } +} diff --git a/AdamControllerLibrary/Extensions/DialogServiceExtension.cs b/AdamControllerLibrary/Extensions/DialogServiceExtension.cs new file mode 100644 index 0000000..b3a26b2 --- /dev/null +++ b/AdamControllerLibrary/Extensions/DialogServiceExtension.cs @@ -0,0 +1,12 @@ +using Prism.Services.Dialogs; + +namespace AdamController.Core.Extensions +{ + public static class DialogServiceExtension + { + public static void ShowSettingsDialog(this IDialogService dialogService) + { + //dialogService.ShowDialog(nameof(SettingsDialogView)); + } + } +} diff --git a/AdamControllerLibrary/Mvvm/RegionViewModelBase.cs b/AdamControllerLibrary/Mvvm/RegionViewModelBase.cs new file mode 100644 index 0000000..5b0e20b --- /dev/null +++ b/AdamControllerLibrary/Mvvm/RegionViewModelBase.cs @@ -0,0 +1,55 @@ +using Prism.Regions; +using Prism.Services.Dialogs; +using System; + + +namespace AdamController.Core.Mvvm +{ + internal class RegionViewModelBase : ViewModelBase, INavigationAware, IConfirmNavigationRequest + { + + #region private service + + protected IRegionManager RegionManager { get; } + protected IDialogService DialogService { get; } + + #endregion + + #region ~ + + public RegionViewModelBase(IRegionManager regionManager, IDialogService dialogService) + { + RegionManager = regionManager; + DialogService = dialogService; + } + + #endregion + + /// + /// Occurs when the navigation area is called + /// + public void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) + { + continuationCallback?.Invoke(true); + } + + public bool IsNavigationTarget(NavigationContext navigationContext) + { + return true; + } + + /// + /// On close region + /// + public void OnNavigatedFrom(NavigationContext navigationContext) + { + } + + /// + /// On load region + /// + public void OnNavigatedTo(NavigationContext navigationContext) + { + } + } +} diff --git a/AdamControllerLibrary/Mvvm/ViewModelBase.cs b/AdamControllerLibrary/Mvvm/ViewModelBase.cs new file mode 100644 index 0000000..e5b3633 --- /dev/null +++ b/AdamControllerLibrary/Mvvm/ViewModelBase.cs @@ -0,0 +1,13 @@ + + +using Prism.Mvvm; +using Prism.Navigation; + +namespace AdamController.Core.Mvvm +{ + public class ViewModelBase : BindableBase, IDestructible + { + protected ViewModelBase() { } + public void Destroy() { } + } +} diff --git a/AdamControllerLibrary/RegionNames.cs b/AdamControllerLibrary/RegionNames.cs new file mode 100644 index 0000000..9e11a9d --- /dev/null +++ b/AdamControllerLibrary/RegionNames.cs @@ -0,0 +1,6 @@ +namespace AdamController.Core +{ + public class RegionNames + { + } +} diff --git a/AdamControllerLibrary/app.config b/AdamControllerLibrary/app.config deleted file mode 100644 index 99ddf3e..0000000 --- a/AdamControllerLibrary/app.config +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file From da5ddf7a8e4b29fe37b59cf0ab38dd456537ac52 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 9 Mar 2024 19:21:00 +1000 Subject: [PATCH 007/181] Remove oldes files --- AdamController.sln | 5 ----- 1 file changed, 5 deletions(-) diff --git a/AdamController.sln b/AdamController.sln index 465096e..fa7354f 100644 --- a/AdamController.sln +++ b/AdamController.sln @@ -11,11 +11,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamController", "AdamContr EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamController.Core", "AdamControllerLibrary\AdamController.Core.csproj", "{1FCB70D5-1BBC-414D-8DFB-4AEA7D45B1D1}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{0A650D34-3B1C-4EA6-8F8B-F5B6B21025E6}" - ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - EndProjectSection -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamBlocklyLibrary", "AdamBlocklyLibrary\AdamBlocklyLibrary.csproj", "{CCB5A70B-3F85-4D11-B774-365DF8A220F6}" ProjectSection(ProjectDependencies) = postProject {1FCB70D5-1BBC-414D-8DFB-4AEA7D45B1D1} = {1FCB70D5-1BBC-414D-8DFB-4AEA7D45B1D1} From 2308778882bfb15f97756b6b745221c9aec11855 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 9 Mar 2024 19:44:15 +1000 Subject: [PATCH 008/181] Added ContentRegion view --- AdamController.sln | 11 +++++++ .../AdamController.Core.csproj | 3 -- AdamControllerLibrary/Mvvm/ViewModelBase.cs | 4 +-- AdamControllerLibrary/RegionNames.cs | 1 + ...damController.Modules.ContentRegion.csproj | 12 ++++++++ .../ContentRegionModule.cs | 30 +++++++++++++++++++ .../ViewModels/ContentRegionViewModel.cs | 8 +++++ .../Views/ContentRegionView.xaml | 13 ++++++++ .../Views/ContentRegionView.xaml.cs | 12 ++++++++ 9 files changed, 88 insertions(+), 6 deletions(-) create mode 100644 Modules/AdamController.Modules.ContentRegion/AdamController.Modules.ContentRegion.csproj create mode 100644 Modules/AdamController.Modules.ContentRegion/ContentRegionModule.cs create mode 100644 Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs create mode 100644 Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml create mode 100644 Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml.cs diff --git a/AdamController.sln b/AdamController.sln index fa7354f..1d519cc 100644 --- a/AdamController.sln +++ b/AdamController.sln @@ -18,6 +18,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamBlocklyLibrary", "AdamB EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamController.WebApi.Client", "AdamController.WebApi.Client\AdamController.WebApi.Client.csproj", "{157FE150-54A5-4D10-A052-580A5B4895DA}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Modules", "Modules", "{BF38E868-9FEB-4645-9B2B-15AC47844075}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdamController.Modules.ContentRegion", "Modules\AdamController.Modules.ContentRegion\AdamController.Modules.ContentRegion.csproj", "{8EF23718-8FE0-4711-BB00-04411C6B4787}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -40,10 +44,17 @@ Global {157FE150-54A5-4D10-A052-580A5B4895DA}.Debug|Any CPU.Build.0 = Debug|Any CPU {157FE150-54A5-4D10-A052-580A5B4895DA}.Release|Any CPU.ActiveCfg = Release|Any CPU {157FE150-54A5-4D10-A052-580A5B4895DA}.Release|Any CPU.Build.0 = Release|Any CPU + {8EF23718-8FE0-4711-BB00-04411C6B4787}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8EF23718-8FE0-4711-BB00-04411C6B4787}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8EF23718-8FE0-4711-BB00-04411C6B4787}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8EF23718-8FE0-4711-BB00-04411C6B4787}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {8EF23718-8FE0-4711-BB00-04411C6B4787} = {BF38E868-9FEB-4645-9B2B-15AC47844075} + EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {D00A029C-930D-44A8-8257-721FCA9202F6} EndGlobalSection diff --git a/AdamControllerLibrary/AdamController.Core.csproj b/AdamControllerLibrary/AdamController.Core.csproj index 94cfe6d..82f8c9e 100644 --- a/AdamControllerLibrary/AdamController.Core.csproj +++ b/AdamControllerLibrary/AdamController.Core.csproj @@ -2,17 +2,14 @@ net7.0-windows Library - 9.0 false MIT-Modern-Variant bin\x64\Debug\ - 9.0 bin\x64\Release\ - 9.0 diff --git a/AdamControllerLibrary/Mvvm/ViewModelBase.cs b/AdamControllerLibrary/Mvvm/ViewModelBase.cs index e5b3633..cb70a15 100644 --- a/AdamControllerLibrary/Mvvm/ViewModelBase.cs +++ b/AdamControllerLibrary/Mvvm/ViewModelBase.cs @@ -1,6 +1,4 @@ - - -using Prism.Mvvm; +using Prism.Mvvm; using Prism.Navigation; namespace AdamController.Core.Mvvm diff --git a/AdamControllerLibrary/RegionNames.cs b/AdamControllerLibrary/RegionNames.cs index 9e11a9d..d101d5a 100644 --- a/AdamControllerLibrary/RegionNames.cs +++ b/AdamControllerLibrary/RegionNames.cs @@ -2,5 +2,6 @@ { public class RegionNames { + public const string ContentRegion = $"{nameof(ContentRegion)}"; } } diff --git a/Modules/AdamController.Modules.ContentRegion/AdamController.Modules.ContentRegion.csproj b/Modules/AdamController.Modules.ContentRegion/AdamController.Modules.ContentRegion.csproj new file mode 100644 index 0000000..46cd8aa --- /dev/null +++ b/Modules/AdamController.Modules.ContentRegion/AdamController.Modules.ContentRegion.csproj @@ -0,0 +1,12 @@ + + + net7.0-windows7.0 + true + + + + + + + + \ No newline at end of file diff --git a/Modules/AdamController.Modules.ContentRegion/ContentRegionModule.cs b/Modules/AdamController.Modules.ContentRegion/ContentRegionModule.cs new file mode 100644 index 0000000..38f2529 --- /dev/null +++ b/Modules/AdamController.Modules.ContentRegion/ContentRegionModule.cs @@ -0,0 +1,30 @@ +using AdamController.Core; +using AdamController.Modules.ContentRegion.Views; +using Prism.Ioc; +using Prism.Modularity; +using Prism.Regions; + +namespace AdamController.Modules.ContentRegion +{ + public class ContentRegionModule : IModule + { + private readonly IRegionManager mRegionManager; + + public ContentRegionModule(IRegionManager regionManager) + { + mRegionManager = regionManager; + } + + public void OnInitialized(IContainerProvider containerProvider) + { + mRegionManager.RequestNavigate(RegionNames.ContentRegion, nameof(ContentRegionView)); + } + + public void RegisterTypes(IContainerRegistry containerRegistry) + { + containerRegistry.RegisterForNavigation(); + + containerRegistry.RegisterForNavigation(nameof(ContentRegionView)); + } + } +} \ No newline at end of file diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs new file mode 100644 index 0000000..fa73353 --- /dev/null +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs @@ -0,0 +1,8 @@ +using Prism.Mvvm; + +namespace AdamController.Modules.ContentRegion.ViewModels +{ + public class ContentRegionViewModel : BindableBase + { + } +} diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml new file mode 100644 index 0000000..c278a24 --- /dev/null +++ b/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml @@ -0,0 +1,13 @@ + + + + diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml.cs b/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml.cs new file mode 100644 index 0000000..e5974e7 --- /dev/null +++ b/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml.cs @@ -0,0 +1,12 @@ +using System.Windows.Controls; + +namespace AdamController.Modules.ContentRegion.Views +{ + public partial class ContentRegionView : UserControl + { + public ContentRegionView() + { + InitializeComponent(); + } + } +} From 176e3314c62d04f55c8c0c19d5e7590364d5ecd7 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 9 Mar 2024 21:03:27 +1000 Subject: [PATCH 009/181] Added: module view --- AdamController.sln | 7 +++++ AdamController/AdamController.csproj | 2 ++ AdamController/App.xaml.cs | 7 +++++ .../Mvvm/RegionViewModelBase.cs | 2 +- AdamControllerLibrary/RegionNames.cs | 1 + .../ViewModels/ContentRegionViewModel.cs | 9 ++++-- .../Views/ContentRegionView.xaml | 1 - .../AdamController.Modules.MenuRegion.csproj | 12 +++++++ .../MenuRegionModule.cs | 31 +++++++++++++++++++ .../ViewModels/MenuRegionViewModel.cs | 13 ++++++++ .../Views/MenuRegionView.xaml | 13 ++++++++ .../Views/MenuRegionView.xaml.cs | 15 +++++++++ 12 files changed, 109 insertions(+), 4 deletions(-) create mode 100644 Modules/AdamController.Modules.MenuRegion/AdamController.Modules.MenuRegion.csproj create mode 100644 Modules/AdamController.Modules.MenuRegion/MenuRegionModule.cs create mode 100644 Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs create mode 100644 Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml create mode 100644 Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml.cs diff --git a/AdamController.sln b/AdamController.sln index 1d519cc..4a336ba 100644 --- a/AdamController.sln +++ b/AdamController.sln @@ -22,6 +22,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Modules", "Modules", "{BF38 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdamController.Modules.ContentRegion", "Modules\AdamController.Modules.ContentRegion\AdamController.Modules.ContentRegion.csproj", "{8EF23718-8FE0-4711-BB00-04411C6B4787}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdamController.Modules.MenuRegion", "Modules\AdamController.Modules.MenuRegion\AdamController.Modules.MenuRegion.csproj", "{6F12ECFD-3891-40AE-A18D-B3362C6A2946}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -48,12 +50,17 @@ Global {8EF23718-8FE0-4711-BB00-04411C6B4787}.Debug|Any CPU.Build.0 = Debug|Any CPU {8EF23718-8FE0-4711-BB00-04411C6B4787}.Release|Any CPU.ActiveCfg = Release|Any CPU {8EF23718-8FE0-4711-BB00-04411C6B4787}.Release|Any CPU.Build.0 = Release|Any CPU + {6F12ECFD-3891-40AE-A18D-B3362C6A2946}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6F12ECFD-3891-40AE-A18D-B3362C6A2946}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6F12ECFD-3891-40AE-A18D-B3362C6A2946}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6F12ECFD-3891-40AE-A18D-B3362C6A2946}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {8EF23718-8FE0-4711-BB00-04411C6B4787} = {BF38E868-9FEB-4645-9B2B-15AC47844075} + {6F12ECFD-3891-40AE-A18D-B3362C6A2946} = {BF38E868-9FEB-4645-9B2B-15AC47844075} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {D00A029C-930D-44A8-8257-721FCA9202F6} diff --git a/AdamController/AdamController.csproj b/AdamController/AdamController.csproj index 8283527..0ab1820 100644 --- a/AdamController/AdamController.csproj +++ b/AdamController/AdamController.csproj @@ -60,6 +60,8 @@ + + diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index a8953ee..dd4a89e 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -14,6 +14,8 @@ using Prism.DryIoc; using Prism.Modularity; using MahApps.Metro.Controls; +using AdamController.Modules.MenuRegion; +using AdamController.Modules.ContentRegion; #endregion @@ -67,6 +69,11 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) containerRegistry.Register(); } + protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) + { + moduleCatalog.AddModule(); + moduleCatalog.AddModule(); + } private static void LoadHighlighting() { diff --git a/AdamControllerLibrary/Mvvm/RegionViewModelBase.cs b/AdamControllerLibrary/Mvvm/RegionViewModelBase.cs index 5b0e20b..9dc4e2a 100644 --- a/AdamControllerLibrary/Mvvm/RegionViewModelBase.cs +++ b/AdamControllerLibrary/Mvvm/RegionViewModelBase.cs @@ -5,7 +5,7 @@ namespace AdamController.Core.Mvvm { - internal class RegionViewModelBase : ViewModelBase, INavigationAware, IConfirmNavigationRequest + public class RegionViewModelBase : ViewModelBase, INavigationAware, IConfirmNavigationRequest { #region private service diff --git a/AdamControllerLibrary/RegionNames.cs b/AdamControllerLibrary/RegionNames.cs index d101d5a..05cebbb 100644 --- a/AdamControllerLibrary/RegionNames.cs +++ b/AdamControllerLibrary/RegionNames.cs @@ -3,5 +3,6 @@ public class RegionNames { public const string ContentRegion = $"{nameof(ContentRegion)}"; + public const string MenuRegion = $"{nameof(MenuRegion)}"; } } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs index fa73353..e021263 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs @@ -1,8 +1,13 @@ -using Prism.Mvvm; +using AdamController.Core.Mvvm; +using Prism.Regions; +using Prism.Services.Dialogs; namespace AdamController.Modules.ContentRegion.ViewModels { - public class ContentRegionViewModel : BindableBase + public class ContentRegionViewModel : RegionViewModelBase { + public ContentRegionViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) + { + } } } diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml index c278a24..e3801e4 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml @@ -5,7 +5,6 @@ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" - d:DesignHeight="300" d:DesignWidth="300" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" > diff --git a/Modules/AdamController.Modules.MenuRegion/AdamController.Modules.MenuRegion.csproj b/Modules/AdamController.Modules.MenuRegion/AdamController.Modules.MenuRegion.csproj new file mode 100644 index 0000000..46cd8aa --- /dev/null +++ b/Modules/AdamController.Modules.MenuRegion/AdamController.Modules.MenuRegion.csproj @@ -0,0 +1,12 @@ + + + net7.0-windows7.0 + true + + + + + + + + \ No newline at end of file diff --git a/Modules/AdamController.Modules.MenuRegion/MenuRegionModule.cs b/Modules/AdamController.Modules.MenuRegion/MenuRegionModule.cs new file mode 100644 index 0000000..0af80e1 --- /dev/null +++ b/Modules/AdamController.Modules.MenuRegion/MenuRegionModule.cs @@ -0,0 +1,31 @@ +using AdamController.Core; +using AdamController.Modules.MenuRegion.Views; +using Prism.Ioc; +using Prism.Modularity; +using Prism.Regions; + +namespace AdamController.Modules.MenuRegion +{ + public class MenuRegionModule : IModule + { + private readonly IRegionManager mRegionManager; + + public MenuRegionModule(IRegionManager regionManager) + { + mRegionManager = regionManager; + } + + + public void OnInitialized(IContainerProvider containerProvider) + { + mRegionManager.RequestNavigate(RegionNames.MenuRegion, nameof(MenuRegionView)); + } + + public void RegisterTypes(IContainerRegistry containerRegistry) + { + containerRegistry.RegisterForNavigation(); + + containerRegistry.RegisterForNavigation(nameof(MenuRegionView)); + } + } +} \ No newline at end of file diff --git a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs new file mode 100644 index 0000000..9abc66e --- /dev/null +++ b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs @@ -0,0 +1,13 @@ +using AdamController.Core.Mvvm; +using Prism.Regions; +using Prism.Services.Dialogs; + +namespace AdamController.Modules.MenuRegion.ViewModels +{ + public class MenuRegionViewModel : RegionViewModelBase + { + public MenuRegionViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) + { + } + } +} diff --git a/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml b/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml new file mode 100644 index 0000000..3b7b01f --- /dev/null +++ b/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml @@ -0,0 +1,13 @@ + + + + diff --git a/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml.cs b/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml.cs new file mode 100644 index 0000000..0581765 --- /dev/null +++ b/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml.cs @@ -0,0 +1,15 @@ +using System.Windows.Controls; + +namespace AdamController.Modules.MenuRegion.Views +{ + /// + /// Interaction logic for ViewA.xaml + /// + public partial class MenuRegionView : UserControl + { + public MenuRegionView() + { + InitializeComponent(); + } + } +} From 48105b01b5295cadf1b15c40dd7fcf1fbc831dc6 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 9 Mar 2024 21:08:45 +1000 Subject: [PATCH 010/181] Movin menu xaml to region module --- AdamController/Views/MainMenu.xaml | 54 ----------------- AdamController/Views/MainMenu.xaml.cs | 5 +- .../Views/MenuRegionView.xaml | 60 ++++++++++++++++++- 3 files changed, 60 insertions(+), 59 deletions(-) diff --git a/AdamController/Views/MainMenu.xaml b/AdamController/Views/MainMenu.xaml index 2a14d8d..d06e528 100644 --- a/AdamController/Views/MainMenu.xaml +++ b/AdamController/Views/MainMenu.xaml @@ -7,60 +7,6 @@ d:DataContext="{d:DesignInstance Type=viewmodels:MainMenuView}" mc:Ignorable="d"> - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + @@ -822,8 +835,8 @@ Width="80" VerticalAlignment="Center" HorizontalAlignment="Right" - Command="{Binding CloseWindowCommand}" - CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" + Command="{Binding CloseDialogCommand}" + CommandParameter="true" Style="{DynamicResource MahApps.Styles.Button}" HorizontalContentAlignment="Center"/> @@ -833,4 +846,4 @@ - + diff --git a/AdamController.Core/Dialog.Views/SettingsView.xaml.cs b/AdamController.Core/Dialog.Views/SettingsView.xaml.cs new file mode 100644 index 0000000..f7370cc --- /dev/null +++ b/AdamController.Core/Dialog.Views/SettingsView.xaml.cs @@ -0,0 +1,12 @@ +using System.Windows.Controls; + +namespace AdamController.Core.Dialog.Views +{ + public partial class SettingsView : UserControl + { + public SettingsView() + { + InitializeComponent(); + } + } +} diff --git a/AdamController.Core/Dialog.Views/SettingsWindow.xaml.cs b/AdamController.Core/Dialog.Views/SettingsWindow.xaml.cs deleted file mode 100644 index 29caf4a..0000000 --- a/AdamController.Core/Dialog.Views/SettingsWindow.xaml.cs +++ /dev/null @@ -1,12 +0,0 @@ -using MahApps.Metro.Controls; - -namespace AdamController.Core.Dialog.Views -{ - public partial class SettingsWindow : MetroWindow - { - public SettingsWindow() - { - InitializeComponent(); - } - } -} diff --git a/AdamController.Core/DialogNames.cs b/AdamController.Core/DialogNames.cs index b936b80..468627e 100644 --- a/AdamController.Core/DialogNames.cs +++ b/AdamController.Core/DialogNames.cs @@ -1,6 +1,9 @@ -namespace AdamController.Core +using AdamController.Core.Dialog.Views; + +namespace AdamController.Core { public class DialogNames { + public const string SettingsDialog = nameof(SettingsView); } } diff --git a/AdamController.Core/Extensions/DialogServiceExtension.cs b/AdamController.Core/Extensions/DialogServiceExtension.cs index b3a26b2..71f72b3 100644 --- a/AdamController.Core/Extensions/DialogServiceExtension.cs +++ b/AdamController.Core/Extensions/DialogServiceExtension.cs @@ -1,4 +1,5 @@ -using Prism.Services.Dialogs; +using AdamController.Core.Dialog.Views; +using Prism.Services.Dialogs; namespace AdamController.Core.Extensions { @@ -6,7 +7,7 @@ public static class DialogServiceExtension { public static void ShowSettingsDialog(this IDialogService dialogService) { - //dialogService.ShowDialog(nameof(SettingsDialogView)); + dialogService.ShowDialog(nameof(SettingsView)); } } } diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index b4f0212..34e06bb 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -21,6 +21,8 @@ using AdamController.Core; using AdamController.Modules.FlayoutsRegion; using AdamController.Modules.HamburgerMenu; +using AdamController.Core.Dialog.Views; +using AdamController.Core.Dialog.ViewModels; #endregion @@ -73,6 +75,8 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) { //here must be ip/port containerRegistry.Register(); + + containerRegistry.RegisterDialog(); } protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) diff --git a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs index e64faca..d5b371c 100644 --- a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs +++ b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs @@ -16,8 +16,6 @@ public class MenuRegionViewModel : RegionViewModelBase public MenuRegionViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) { - CloseAppCommand = new DelegateCommand(Application.Current.Shutdown); - CloseAppCommand = new DelegateCommand(CloseApp); ShowDialogCommand = new DelegateCommand(ShowDialog); ShowRegionCommand = new DelegateCommand(ShowRegion); @@ -30,12 +28,9 @@ private void ShowDialog(string dialogNames) { switch (dialogNames) { - //case DialogNames.SettingsDialog: - // DialogService.ShowSettingsDialog(); - // break; - //case DialogNames.LogDialog: - // DialogService.ShowLogViewerDialog(); - // break; + case DialogNames.SettingsDialog: + DialogService.ShowSettingsDialog(); + break; } } diff --git a/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml b/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml index ae61a84..930ea9a 100644 --- a/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml +++ b/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml @@ -72,8 +72,10 @@ - - + + From 296e8b2d29c747536474b56a9a02221b8d428a6c Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 16 Mar 2024 12:40:35 +1000 Subject: [PATCH 047/181] Fix and enable NetworkView --- .../Behaviors/ActivateBehavior.cs | 1 + .../Dialog.ViewModels/NetworkTestViewModel.cs | 42 ++++--------- .../Dialog.ViewModels/SettingsViewModel.cs | 43 ++------------ .../Dialog.Views/NetworkTestView.xaml | 52 +++++++++------- .../Dialog.Views/SettingsView.xaml | 8 +++ AdamController.Core/DialogNames.cs | 1 + .../Extensions/DialogServiceExtension.cs | 5 ++ .../Mvvm/DialogViewModelBase.cs | 59 +++++++++++++++++++ AdamController/App.xaml.cs | 6 +- .../ViewModels/MenuRegionViewModel.cs | 4 ++ .../Views/MenuRegionView.xaml | 6 +- 11 files changed, 132 insertions(+), 95 deletions(-) create mode 100644 AdamController.Core/Mvvm/DialogViewModelBase.cs diff --git a/AdamController.Core/Behaviors/ActivateBehavior.cs b/AdamController.Core/Behaviors/ActivateBehavior.cs index 9de464c..9a95289 100644 --- a/AdamController.Core/Behaviors/ActivateBehavior.cs +++ b/AdamController.Core/Behaviors/ActivateBehavior.cs @@ -4,6 +4,7 @@ namespace AdamController.Core.Behaviors { + [Obsolete] public class ActivateBehavior : Behavior { private bool isActivated; diff --git a/AdamController.Core/Dialog.ViewModels/NetworkTestViewModel.cs b/AdamController.Core/Dialog.ViewModels/NetworkTestViewModel.cs index 5c52d1c..865f900 100644 --- a/AdamController.Core/Dialog.ViewModels/NetworkTestViewModel.cs +++ b/AdamController.Core/Dialog.ViewModels/NetworkTestViewModel.cs @@ -1,12 +1,11 @@ using AdamController.Core.Helpers; +using AdamController.Core.Mvvm; using AdamController.WebApi.Client.v1; using AdamController.WebApi.Client.v1.RequestModel; using MahApps.Metro.IconPacks; using MessageDialogManagerLib; using NetCoreServer; using Prism.Commands; -using Prism.Mvvm; -using Prism.Services.Dialogs; using System; using System.Collections.Generic; using System.Runtime.InteropServices; @@ -16,7 +15,7 @@ namespace AdamController.Core.Dialog.ViewModels { - public class NetworkTestViewModel : BindableBase, IDialogAware + public class NetworkTestViewModel : DialogViewModelBase { #region Const @@ -38,14 +37,16 @@ public class NetworkTestViewModel : BindableBase, IDialogAware public NetworkTestViewModel() { - SendApiComunicateCommand(ServerCommand.Start); + Title = "Тест сети"; - mComunicateTestHelper = ComunicateBenchmarkHelper.Instance; + //SendApiComunicateCommand(ServerCommand.Start); + + //mComunicateTestHelper = ComunicateBenchmarkHelper.Instance; IDialogManager = new MessageDialogManagerMahapps(Application.Current); - ComunicateBenchmarkHelper.OnTcpConnected += OnTcpConnected; - ComunicateBenchmarkHelper.OnTcpDisconnected += OnTcpDisconnected; - ComunicateBenchmarkHelper.OnTcpReconnected += OnTcpReconnected; + //ComunicateBenchmarkHelper.OnTcpConnected += OnTcpConnected; + //ComunicateBenchmarkHelper.OnTcpDisconnected += OnTcpDisconnected; + //ComunicateBenchmarkHelper.OnTcpReconnected += OnTcpReconnected; ClearTcpResultField(); TcpStatusBarManager(false); @@ -55,12 +56,12 @@ public NetworkTestViewModel() if (Properties.Settings.Default.AutoStartTestTcpConnect) { - ConnectButtonComand.Execute(); + //ConnectButtonComand.Execute(); } else { //init fields if autorun off - OnTcpDisconnected(); + //OnTcpDisconnected(); } } @@ -68,23 +69,6 @@ public NetworkTestViewModel() #region Navigation - public string Title => throw new NotImplementedException(); - - public bool CanCloseDialog() - { - return true; - } - - public void OnDialogClosed() - { - - } - - public void OnDialogOpened(IDialogParameters parameters) - { - - } - #endregion #region UI behavior @@ -1258,8 +1242,6 @@ private void SendApiComunicateCommand(ServerCommand command) private DelegateCommand saveResults; - public event Action RequestClose; - public DelegateCommand SaveResults => saveResults ??= new DelegateCommand(() => { IList envParamsShort = null; @@ -1299,8 +1281,6 @@ private void SendApiComunicateCommand(ServerCommand command) }); - - private async void FileSaveDialog(string file, string title, string fileName) { diff --git a/AdamController.Core/Dialog.ViewModels/SettingsViewModel.cs b/AdamController.Core/Dialog.ViewModels/SettingsViewModel.cs index 7a8720c..fa61050 100644 --- a/AdamController.Core/Dialog.ViewModels/SettingsViewModel.cs +++ b/AdamController.Core/Dialog.ViewModels/SettingsViewModel.cs @@ -1,13 +1,14 @@ -using Prism.Commands; +using AdamController.Core.Mvvm; +using Prism.Commands; using Prism.Mvvm; using Prism.Services.Dialogs; using System; namespace AdamController.Core.Dialog.ViewModels { - public class SettingsViewModel : BindableBase, IDialogAware + public class SettingsViewModel : DialogViewModelBase + { - public string Title { get; } #region ~ @@ -20,43 +21,7 @@ public SettingsViewModel() #region Navigation - public event Action RequestClose; - - private DelegateCommand mCloseDialogCommand; - - public DelegateCommand CloseDialogCommand => mCloseDialogCommand ??= new DelegateCommand(CloseDialog); - - public virtual void RaiseRequestClose(IDialogResult dialogResult) - { - RequestClose?.Invoke(dialogResult); - } - - public bool CanCloseDialog() - { - return true; - } - public void OnDialogClosed() - { - - } - - public void OnDialogOpened(IDialogParameters parameters) - { - - } - - protected virtual void CloseDialog(string parameter) - { - ButtonResult result = ButtonResult.None; - - if (parameter?.ToLower() == "true") - result = ButtonResult.OK; - else if (parameter?.ToLower() == "false") - result = ButtonResult.Cancel; - - RaiseRequestClose(new DialogResult(result)); - } #endregion } diff --git a/AdamController.Core/Dialog.Views/NetworkTestView.xaml b/AdamController.Core/Dialog.Views/NetworkTestView.xaml index 0338412..e31de7e 100644 --- a/AdamController.Core/Dialog.Views/NetworkTestView.xaml +++ b/AdamController.Core/Dialog.Views/NetworkTestView.xaml @@ -1,20 +1,20 @@  - - + xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" + xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + xmlns:d="http://schemas.microsoft.com/expression/blend/2008" + xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" + xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" + xmlns:behaviors="clr-namespace:AdamController.Core.Behaviors" + xmlns:s="clr-namespace:System;assembly=mscorlib" + xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks" + xmlns:properties="clr-namespace:AdamController.Core.Properties" + xmlns:Converters="clr-namespace:AdamController.Core.Converters" + xmlns:i="http://schemas.microsoft.com/xaml/behaviors" + xmlns:prism="http://prismlibrary.com/" + prism:ViewModelLocator.AutoWireViewModel="True" + Width="1000" Height="600"> + @@ -32,9 +32,23 @@ - + + + + + + + + + + @@ -19,7 +21,11 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + About + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From a68d5d8d468518f3756a820b233212f4b2cadfc0 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 17 Mar 2024 14:14:37 +1000 Subject: [PATCH 050/181] Second version hamburger menu --- AdamController/App.xaml | 156 ++++++++++++- AdamController/Views/MainWindow.xaml | 17 +- .../Views/ContentRegionView.xaml | 5 +- .../Views/HamburgerMenuView.xaml | 217 +++--------------- .../Views/HamburgerMenuViewOld.xaml | 2 +- 5 files changed, 200 insertions(+), 197 deletions(-) diff --git a/AdamController/App.xaml b/AdamController/App.xaml index d2a4d67..23de255 100644 --- a/AdamController/App.xaml +++ b/AdamController/App.xaml @@ -2,7 +2,9 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:properties="clr-namespace:AdamController.Core.Properties;assembly=AdamController.Core" - xmlns:prism="http://prismlibrary.com/"> + xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" + xmlns:prism="http://prismlibrary.com/" + xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" > @@ -15,6 +17,158 @@ + + diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index 18d5560..cb1df89 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -32,7 +32,6 @@ - @@ -85,16 +84,16 @@ - + - + - + + + + + + diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml index 358e429..e0659d3 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml @@ -3,10 +3,9 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" xmlns:prism="http://prismlibrary.com/" + xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" prism:ViewModelLocator.AutoWireViewModel="True"> + - - - diff --git a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml b/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml index 395659e..076bc94 100644 --- a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml +++ b/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml @@ -7,189 +7,40 @@ xmlns:prism="http://prismlibrary.com/" xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks" - prism:ViewModelLocator.AutoWireViewModel="True" Width="Auto" Height="Auto"> + prism:ViewModelLocator.AutoWireViewModel="True"> - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - About - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuViewOld.xaml b/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuViewOld.xaml index 4aeb046..6b44078 100644 --- a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuViewOld.xaml +++ b/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuViewOld.xaml @@ -88,7 +88,7 @@ ItemsSource="{Binding MenuItems}" OptionsItemTemplate="{StaticResource MenuItemTemplate}" OptionsItemsSource="{Binding MenuOptionItems}" - SelectedIndex="{Binding SelectedPageIndex}"> + SelectedIndex="{Binding SelectedPageIndex}"> From 4e467ff1cc953e5c97508e38ca76afac9949243c Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 17 Mar 2024 14:53:07 +1000 Subject: [PATCH 051/181] Third variam hamburger menu --- AdamController/App.xaml | 152 ------------------ AdamController/App.xaml.cs | 2 +- AdamController/Views/MainWindow.xaml | 105 +++++++++++- .../Views/HamburgerMenuView.xaml | 151 +++++++++++++---- 4 files changed, 219 insertions(+), 191 deletions(-) diff --git a/AdamController/App.xaml b/AdamController/App.xaml index 23de255..0de90ec 100644 --- a/AdamController/App.xaml +++ b/AdamController/App.xaml @@ -17,158 +17,6 @@ - - diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 873cb16..8044463 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -83,7 +83,7 @@ protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) moduleCatalog.AddModule(); moduleCatalog.AddModule(); moduleCatalog.AddModule(); - moduleCatalog.AddModule(); + //moduleCatalog.AddModule(); } private static void LoadHighlighting() diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index cb1df89..c1b6ee4 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -22,6 +22,7 @@ + @@ -74,6 +75,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -84,10 +130,61 @@ - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml b/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml index 076bc94..6c9bf2b 100644 --- a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml +++ b/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml @@ -9,38 +9,121 @@ xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks" prism:ViewModelLocator.AutoWireViewModel="True"> - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 0782d94d74b1fed04e581c40794d249efee913f5 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Wed, 20 Mar 2024 16:12:20 +1000 Subject: [PATCH 052/181] Fix: hamburger menu are worked --- AdamController/Views/MainWindow.xaml | 50 +++++++++------------------- 1 file changed, 16 insertions(+), 34 deletions(-) diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index c1b6ee4..62fed6e 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -79,18 +79,21 @@ + + + - + - - - - - - - - - + + + - - - - - - + - --> + - - - - - - - + + + + + From 9f13c0bc5b443a091e6d1a0cd8634b61b11bb270 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Thu, 21 Mar 2024 22:50:04 +1000 Subject: [PATCH 053/181] Fix issue #5 task 1. Region navigation are worked --- .../ViewModels/MainWindowViewModel.cs | 46 ++++++++++++++++--- AdamController/Views/MainWindow.xaml | 25 +++++++--- .../ViewModels/ContentRegionViewModel.cs | 8 +++- 3 files changed, 65 insertions(+), 14 deletions(-) diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index b3406c7..f37f003 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -1,15 +1,49 @@ -using Prism.Mvvm; +using AdamController.Core; +using AdamController.Core.Mvvm; +using Prism.Commands; +using Prism.Mvvm; +using Prism.Regions; +using Prism.Services.Dialogs; +using System; using System.Reflection; namespace AdamController.ViewModels { - public class MainWindowViewModel : BindableBase//BaseViewModel + public class MainWindowViewModel : BindableBase//BindableBase//BaseViewModel { + public DelegateCommand ShowRegionCommand { get; private set; } + + public IRegionManager RegionManager { get; } + + public MainWindowViewModel(IRegionManager regionManager, IDialogService dialogService) //: base(regionManager, dialogService) + { + RegionManager = regionManager; + ShowRegionCommand = new DelegateCommand(ShowRegion); + } + + private void ShowRegion(string subRegionName) + { + switch (subRegionName) + { + case SubRegionNames.SubRegionScratch: + RegionManager.RequestNavigate(RegionNames.ContentRegion, SubRegionNames.SubRegionScratch); + break; + case SubRegionNames.SubRegionScriptEditor: + RegionManager.RequestNavigate(RegionNames.ContentRegion, SubRegionNames.SubRegionScriptEditor); + break; + case SubRegionNames.SubRegionComputerVisionControl: + RegionManager.RequestNavigate(RegionNames.ContentRegion, SubRegionNames.SubRegionComputerVisionControl); + break; + case SubRegionNames.SubRegionVisualSettings: + RegionManager.RequestNavigate(RegionNames.ContentRegion, SubRegionNames.SubRegionVisualSettings); + break; + } + } #region Services - + #endregion @@ -19,8 +53,8 @@ public class MainWindowViewModel : BindableBase//BaseViewModel #endregion - public MainWindowViewModel() - { + //public MainWindowViewModel() + //{ //ComunicateHelper.OnAdamTcpConnectedEvent += OnTcpConnected; //ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; //ComunicateHelper.OnAdamTcpReconnected += OnTcpReconnected; @@ -42,7 +76,7 @@ public MainWindowViewModel() //ConnectIcon = PackIconModernKind.Connect; //IconOnConnectFlayoutButton = PackIconMaterialKind.RobotDead; //} - } + //} } } diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index 62fed6e..82e8451 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -11,6 +11,7 @@ xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" TitleCharacterCasing="Normal" WindowState="Maximized" ShowIconOnTitleBar="True" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" + x:Name="MainWindowName" Title="{Binding WindowTitle}"> @@ -107,6 +108,7 @@ + + + @@ -145,29 +149,36 @@ - - - + + + - + + - + + + + - - + + + diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs index 6f982f5..3453359 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs @@ -18,9 +18,15 @@ public ContentRegionViewModel(IRegionManager regionManager, IDialogService dialo #region Navigation + public override bool IsNavigationTarget(NavigationContext navigationContext) + { + return base.IsNavigationTarget(navigationContext); + } + public override void OnNavigatedTo(NavigationContext navigationContext) { - SubRegionsRequestNavigate(SubRegionNames.SubRegionScratch, navigationContext.Parameters); + SubRegionsRequestNavigate(navigationContext.Uri.ToString(), navigationContext.Parameters); + //SubRegionsRequestNavigate(SubRegionNames.SubRegionVisualSettings, navigationContext.Parameters); } public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) From e07d5c15ee7b2367ec01c7c4f364696c4a50ffe5 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 23 Mar 2024 11:52:45 +1000 Subject: [PATCH 054/181] Remove Hamburger menu region --- AdamController.sln | 7 - AdamController/AdamController.csproj | 1 - AdamController/App.xaml.cs | 1 - AdamController/Views/MainWindow.xaml | 25 ++-- .../ViewModels/ContentRegionViewModel.cs | 11 +- ...troller.Modules.HamburgerMenuRegion.csproj | 17 --- .../HamburgerMenuRegionModule.cs | 30 ---- .../ViewModels/HamburgerMenuViewModel.cs | 72 ---------- .../Views/HamburgerMenuView.xaml | 129 ------------------ .../Views/HamburgerMenuView.xaml.cs | 12 -- .../Views/HamburgerMenuViewOld.xaml | 117 ---------------- .../Views/HamburgerMenuViewOld.xaml.cs | 12 -- 12 files changed, 18 insertions(+), 416 deletions(-) delete mode 100644 Modules/AdamController.Modules.HamburgerMenu/AdamController.Modules.HamburgerMenuRegion.csproj delete mode 100644 Modules/AdamController.Modules.HamburgerMenu/HamburgerMenuRegionModule.cs delete mode 100644 Modules/AdamController.Modules.HamburgerMenu/ViewModels/HamburgerMenuViewModel.cs delete mode 100644 Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml delete mode 100644 Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml.cs delete mode 100644 Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuViewOld.xaml delete mode 100644 Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuViewOld.xaml.cs diff --git a/AdamController.sln b/AdamController.sln index 72cced6..9ff424c 100644 --- a/AdamController.sln +++ b/AdamController.sln @@ -19,8 +19,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamController.Services", " EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamController.Modules.FlayoutsRegion", "Modules\AdamController.Modules.FlayoutsRegion\AdamController.Modules.FlayoutsRegion.csproj", "{D17BE826-5C86-4EAC-8424-534F9CF3DFE0}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamController.Modules.HamburgerMenuRegion", "Modules\AdamController.Modules.HamburgerMenu\AdamController.Modules.HamburgerMenuRegion.csproj", "{98D2127D-CC7E-42F1-ACD1-9C9D9ADA03F8}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamController.Core", "AdamController.Core\AdamController.Core.csproj", "{F6817FD0-DE3E-4636-8443-A26F46507A6F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamBlocklyLibrary", "Legacy\AdamBlocklyLibrary\AdamBlocklyLibrary.csproj", "{941A4E7D-6A53-44F8-876C-6B33AAEDDA89}" @@ -57,10 +55,6 @@ Global {D17BE826-5C86-4EAC-8424-534F9CF3DFE0}.Debug|Any CPU.Build.0 = Debug|Any CPU {D17BE826-5C86-4EAC-8424-534F9CF3DFE0}.Release|Any CPU.ActiveCfg = Release|Any CPU {D17BE826-5C86-4EAC-8424-534F9CF3DFE0}.Release|Any CPU.Build.0 = Release|Any CPU - {98D2127D-CC7E-42F1-ACD1-9C9D9ADA03F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {98D2127D-CC7E-42F1-ACD1-9C9D9ADA03F8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {98D2127D-CC7E-42F1-ACD1-9C9D9ADA03F8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {98D2127D-CC7E-42F1-ACD1-9C9D9ADA03F8}.Release|Any CPU.Build.0 = Release|Any CPU {F6817FD0-DE3E-4636-8443-A26F46507A6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F6817FD0-DE3E-4636-8443-A26F46507A6F}.Debug|Any CPU.Build.0 = Debug|Any CPU {F6817FD0-DE3E-4636-8443-A26F46507A6F}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -82,7 +76,6 @@ Global {6F12ECFD-3891-40AE-A18D-B3362C6A2946} = {BF38E868-9FEB-4645-9B2B-15AC47844075} {05913116-D1EA-49C3-92C4-B4316E7C0A9C} = {BF38E868-9FEB-4645-9B2B-15AC47844075} {D17BE826-5C86-4EAC-8424-534F9CF3DFE0} = {BF38E868-9FEB-4645-9B2B-15AC47844075} - {98D2127D-CC7E-42F1-ACD1-9C9D9ADA03F8} = {BF38E868-9FEB-4645-9B2B-15AC47844075} {941A4E7D-6A53-44F8-876C-6B33AAEDDA89} = {511F4919-C2FC-4775-92A4-C446E51B49DB} {771220FE-2F25-441B-815E-7DD63918BA95} = {511F4919-C2FC-4775-92A4-C446E51B49DB} EndGlobalSection diff --git a/AdamController/AdamController.csproj b/AdamController/AdamController.csproj index d2bf8ea..9f194d6 100644 --- a/AdamController/AdamController.csproj +++ b/AdamController/AdamController.csproj @@ -39,7 +39,6 @@ - diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 8044463..b938aeb 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -83,7 +83,6 @@ protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) moduleCatalog.AddModule(); moduleCatalog.AddModule(); moduleCatalog.AddModule(); - //moduleCatalog.AddModule(); } private static void LoadHighlighting() diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index 82e8451..7532326 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -68,12 +68,15 @@ + + + @@ -149,16 +152,24 @@ - - - + + + - + @@ -168,18 +179,12 @@ - - - - - - diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs index 3453359..f03a495 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs @@ -18,15 +18,11 @@ public ContentRegionViewModel(IRegionManager regionManager, IDialogService dialo #region Navigation - public override bool IsNavigationTarget(NavigationContext navigationContext) - { - return base.IsNavigationTarget(navigationContext); - } - public override void OnNavigatedTo(NavigationContext navigationContext) { - SubRegionsRequestNavigate(navigationContext.Uri.ToString(), navigationContext.Parameters); - //SubRegionsRequestNavigate(SubRegionNames.SubRegionVisualSettings, navigationContext.Parameters); + //SubRegionsRequestNavigate(navigationContext.Uri.ToString(), navigationContext.Parameters); + //is loaded on startup region + SubRegionsRequestNavigate(SubRegionNames.SubRegionScratch, navigationContext.Parameters); } public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) @@ -43,7 +39,6 @@ private void SubRegionsRequestNavigate(string tag, NavigationParameters paramete switch (tag) { - case SubRegionNames.SubRegionScratch: RegionManager.RequestNavigate(SubRegionNames.InsideConentRegion, nameof(ScratchControlView), parameters); break; diff --git a/Modules/AdamController.Modules.HamburgerMenu/AdamController.Modules.HamburgerMenuRegion.csproj b/Modules/AdamController.Modules.HamburgerMenu/AdamController.Modules.HamburgerMenuRegion.csproj deleted file mode 100644 index c6be1ee..0000000 --- a/Modules/AdamController.Modules.HamburgerMenu/AdamController.Modules.HamburgerMenuRegion.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - net7.0-windows7.0 - true - - - - - - - - - - Code - - - \ No newline at end of file diff --git a/Modules/AdamController.Modules.HamburgerMenu/HamburgerMenuRegionModule.cs b/Modules/AdamController.Modules.HamburgerMenu/HamburgerMenuRegionModule.cs deleted file mode 100644 index 9680f31..0000000 --- a/Modules/AdamController.Modules.HamburgerMenu/HamburgerMenuRegionModule.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AdamController.Core; -using AdamController.Modules.HamburgerMenuRegion.Views; -using Prism.Ioc; -using Prism.Modularity; -using Prism.Regions; - -namespace AdamController.Modules.HamburgerMenu -{ - public class HamburgerMenuRegionModule : IModule - { - private readonly IRegionManager mRegionManager; - - public HamburgerMenuRegionModule(IRegionManager regionManager) - { - mRegionManager = regionManager; - } - - public void OnInitialized(IContainerProvider containerProvider) - { - mRegionManager.RequestNavigate(RegionNames.HamburgerMenuRegion, nameof(HamburgerMenuView)); - } - - public void RegisterTypes(IContainerRegistry containerRegistry) - { - containerRegistry.RegisterForNavigation(); - - containerRegistry.RegisterForNavigation(nameof(HamburgerMenuView)); - } - } -} \ No newline at end of file diff --git a/Modules/AdamController.Modules.HamburgerMenu/ViewModels/HamburgerMenuViewModel.cs b/Modules/AdamController.Modules.HamburgerMenu/ViewModels/HamburgerMenuViewModel.cs deleted file mode 100644 index e9bded0..0000000 --- a/Modules/AdamController.Modules.HamburgerMenu/ViewModels/HamburgerMenuViewModel.cs +++ /dev/null @@ -1,72 +0,0 @@ -using AdamController.Core.Mvvm; -using AdamController.ViewModels.HamburgerMenu; -using Prism.Regions; -using Prism.Services.Dialogs; -using System.Collections.ObjectModel; - -namespace AdamController.Modules.HamburgerMenuRegion.ViewModels -{ - - public class HamburgerMenuViewModel : RegionViewModelBase - { - private ObservableCollection mMenuItems; - private ObservableCollection mMenuOptionItems; - - public HamburgerMenuViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) - { - //CreateMenuItems(); - } - - public void CreateMenuItems() - { - MenuItems = new ObservableCollection - { - //new ScratchControlView(this) - //new ScratchControlViewModel() - //{ - // Icon = new PackIconSimpleIcons() {Kind = PackIconSimpleIconsKind.Scratch }, - // Label = "Cкретч", - // ToolTip = "Скретч редактор" - //}, - //new ScriptEditorControlView(this) - //new ScriptEditorControlViewModel() - //{ - // Icon = new PackIconModern() {Kind = PackIconModernKind.PageEdit}, - // Label = "Редактор", - // ToolTip = "Редактор скриптов" - //}, - //new ComputerVisionControlView(this) - //new ComputerVisionControlViewModel() - //{ - // Icon = new PackIconModern() { Kind = PackIconModernKind.Video }, - // Label = "Компьютерное зрение", - // ToolTip = "Компьютерное зрение" - //} - }; - - MenuOptionItems = new ObservableCollection - { - //new VisualSettingsControlView(this) - //new VisualSettingsControlView() - //{ - // Icon = new PackIconMaterial() {Kind = PackIconMaterialKind.Cog}, - // Label = "Настройки", - // ToolTip = "Графические настройки приложения" - //} - }; - } - - public ObservableCollection MenuItems - { - get => mMenuItems; - set => SetProperty(ref mMenuItems, value); - } - - public ObservableCollection MenuOptionItems - { - get => mMenuOptionItems; - set => SetProperty(ref mMenuOptionItems, value); - } - - } -} diff --git a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml b/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml deleted file mode 100644 index 6c9bf2b..0000000 --- a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml.cs b/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml.cs deleted file mode 100644 index 56d9e90..0000000 --- a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuView.xaml.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Windows.Controls; - -namespace AdamController.Modules.HamburgerMenuRegion.Views -{ - public partial class HamburgerMenuView : UserControl - { - public HamburgerMenuView() - { - InitializeComponent(); - } - } -} diff --git a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuViewOld.xaml b/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuViewOld.xaml deleted file mode 100644 index 6b44078..0000000 --- a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuViewOld.xaml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuViewOld.xaml.cs b/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuViewOld.xaml.cs deleted file mode 100644 index 8c0ebd5..0000000 --- a/Modules/AdamController.Modules.HamburgerMenu/Views/HamburgerMenuViewOld.xaml.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Windows.Controls; - -namespace AdamController.Modules.HamburgerMenuRegion.Views -{ - public partial class HamburgerMenuViewOld : UserControl - { - public HamburgerMenuViewOld() - { - InitializeComponent(); - } - } -} From ca706fc9997fcb86321b27e432c3a2c06e9d7019 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 23 Mar 2024 12:58:51 +1000 Subject: [PATCH 055/181] Fix: wrong namespace in visual setting vew model --- AdamController/App.xaml.cs | 1 - .../ViewModels/MainWindowViewModel.cs | 11 +++++++-- AdamController/Views/MainWindow.xaml | 23 ++++++++++++------- .../ContentRegionModule.cs | 4 ++-- .../ViewModels/ContentRegionViewModel.cs | 2 +- .../VisualSettingsControlViewModel.cs | 19 ++++++++++++--- 6 files changed, 43 insertions(+), 17 deletions(-) diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index b938aeb..be00936 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -17,7 +17,6 @@ using AdamController.Services; using AdamController.Modules.StatusBarRegion; using AdamController.Modules.FlayoutsRegion; -using AdamController.Modules.HamburgerMenu; using AdamController.Core.Dialog.Views; using AdamController.Core.Dialog.ViewModels; diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index f37f003..e6389b4 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -9,16 +9,23 @@ namespace AdamController.ViewModels { - public class MainWindowViewModel : BindableBase//BindableBase//BaseViewModel + public class MainWindowViewModel : BindableBase { public DelegateCommand ShowRegionCommand { get; private set; } public IRegionManager RegionManager { get; } - public MainWindowViewModel(IRegionManager regionManager, IDialogService dialogService) //: base(regionManager, dialogService) + public MainWindowViewModel(IRegionManager regionManager, IDialogService dialogService) { RegionManager = regionManager; ShowRegionCommand = new DelegateCommand(ShowRegion); + + System.Windows.Application.Current.MainWindow.Loaded += MainWindow_Loaded; + } + + private void MainWindow_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + ShowRegionCommand.Execute(SubRegionNames.SubRegionScratch); } private void ShowRegion(string subRegionName) diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index 7532326..cea36bf 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -11,7 +11,6 @@ xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" TitleCharacterCasing="Normal" WindowState="Maximized" ShowIconOnTitleBar="True" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" - x:Name="MainWindowName" Title="{Binding WindowTitle}"> @@ -140,45 +139,53 @@ + + Command="{Binding ShowRegionCommand}" + CommandParameter="{x:Static core:SubRegionNames.SubRegionScratch}"/> + Command="{Binding ShowRegionCommand}" + CommandParameter="{x:Static core:SubRegionNames.SubRegionScriptEditor}"/> + Command="{Binding ShowRegionCommand}" + CommandParameter="{x:Static core:SubRegionNames.SubRegionComputerVisionControl}"/> + + + + + + diff --git a/Modules/AdamController.Modules.ContentRegion/ContentRegionModule.cs b/Modules/AdamController.Modules.ContentRegion/ContentRegionModule.cs index 303f4ad..c8f34e0 100644 --- a/Modules/AdamController.Modules.ContentRegion/ContentRegionModule.cs +++ b/Modules/AdamController.Modules.ContentRegion/ContentRegionModule.cs @@ -22,9 +22,9 @@ public void OnInitialized(IContainerProvider containerProvider) public void RegisterTypes(IContainerRegistry containerRegistry) { - containerRegistry.RegisterForNavigation(); - + //containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(nameof(ContentRegionView)); + containerRegistry.RegisterForNavigation(nameof(ScratchControlView)); containerRegistry.RegisterForNavigation(nameof(ComputerVisionControlView)); containerRegistry.RegisterForNavigation(nameof(ScriptEditorControlView)); diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs index f03a495..0b8423f 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs @@ -22,7 +22,7 @@ public override void OnNavigatedTo(NavigationContext navigationContext) { //SubRegionsRequestNavigate(navigationContext.Uri.ToString(), navigationContext.Parameters); //is loaded on startup region - SubRegionsRequestNavigate(SubRegionNames.SubRegionScratch, navigationContext.Parameters); + //SubRegionsRequestNavigate(SubRegionNames.SubRegionScratch, navigationContext.Parameters); } public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index a72aa96..0c05bed 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -12,15 +12,28 @@ using System.Linq; using System.Windows; -namespace AdamController.Modules.HamburgerMenu.ViewModels +namespace AdamController.Modules.ContentRegion.ViewModels { - public class VisualSettingsControlViewModel : RegionViewModelBase //: HamburgerMenuItemView + public class VisualSettingsControlViewModel : RegionViewModelBase { public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) { + sbyte s = 4; } - //public VisualSettingsControlView(HamburgerMenuView hamburgerMenuView) : base(hamburgerMenuView) {} + #region Navigation + + public override void OnNavigatedFrom(NavigationContext navigationContext) + { + + } + + public override void OnNavigatedTo(NavigationContext navigationContext) + { + + } + + #endregion public static ObservableCollection BlocklyThemes { get; private set; } = ThemesCollection.BlocklyThemes; From 0c13513bdbbcf704a2a1851c922887c6af1309fd Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 24 Mar 2024 11:33:38 +1000 Subject: [PATCH 056/181] Fix issue #6 --- .../HamburgerMenu/HamburgerMenuItemView.cs | 44 ----- .../Mvvm/RegionViewModelBase.cs | 10 +- AdamController.Core/Mvvm/ViewModelBase.cs | 15 +- AdamController.Core/RegionNames.cs | 2 - .../ISubRegionChangeAwareService.cs | 10 ++ .../SubRegionChangeAwareService.cs | 28 ++++ AdamController/App.xaml.cs | 12 +- .../ViewModels/MainWindowViewModel.cs | 157 ++++++++++++++---- AdamController/Views/MainWindow.xaml | 2 + .../ComputerVisionControlViewModel.cs | 1 + .../ViewModels/ContentRegionViewModel.cs | 31 ++-- .../ViewModels/ScratchControlViewModel.cs | 1 + .../ScriptEditorControlViewModel.cs | 1 + .../VisualSettingsControlViewModel.cs | 2 +- .../Views/ComputerVisionControlView.xaml.cs | 25 ++- .../ViewModels/FlayoutsViewModel.cs | 1 + .../ViewModels/NotificationViewModel.cs | 1 + .../ViewModels/MenuRegionViewModel.cs | 1 + .../ViewModels/StatusBarViewModel.cs | 1 + 19 files changed, 233 insertions(+), 112 deletions(-) delete mode 100644 AdamController.Core/Mvvm/HamburgerMenu/HamburgerMenuItemView.cs create mode 100644 AdamController.Services/Interfaces/ISubRegionChangeAwareService.cs create mode 100644 AdamController.Services/SubRegionChangeAwareService.cs diff --git a/AdamController.Core/Mvvm/HamburgerMenu/HamburgerMenuItemView.cs b/AdamController.Core/Mvvm/HamburgerMenu/HamburgerMenuItemView.cs deleted file mode 100644 index 1734bdb..0000000 --- a/AdamController.Core/Mvvm/HamburgerMenu/HamburgerMenuItemView.cs +++ /dev/null @@ -1,44 +0,0 @@ -using MahApps.Metro.Controls; -using Prism.Mvvm; - -namespace AdamController.ViewModels.HamburgerMenu -{ - public class HamburgerMenuItemView : BindableBase, IHamburgerMenuItemBase - { - private object _icon; - private object _label; - private object _toolTip; - private bool _isVisible = true; - - //public HamburgerMenuItemView(HamburgerMenuView hamburgerMenuView) - //{ - // HamburgerMenuView = hamburgerMenuView; - //} - - //public HamburgerMenuView HamburgerMenuView { get; } - - public object Icon - { - get => _icon; - set => SetProperty(ref _icon, value); - } - - public object Label - { - get => _label; - set => SetProperty(ref _label, value); - } - - public object ToolTip - { - get => _toolTip; - set => SetProperty(ref _toolTip, value); - } - - public bool IsVisible - { - get => _isVisible; - set => SetProperty(ref _isVisible, value); - } - } -} diff --git a/AdamController.Core/Mvvm/RegionViewModelBase.cs b/AdamController.Core/Mvvm/RegionViewModelBase.cs index 1ad3e5c..74f9d02 100644 --- a/AdamController.Core/Mvvm/RegionViewModelBase.cs +++ b/AdamController.Core/Mvvm/RegionViewModelBase.cs @@ -1,4 +1,5 @@ -using Prism.Regions; +using AdamController.Services.Interfaces; +using Prism.Regions; using Prism.Services.Dialogs; using System; @@ -7,8 +8,9 @@ namespace AdamController.Core.Mvvm { public class RegionViewModelBase : ViewModelBase, INavigationAware, IConfirmNavigationRequest { - + #region private service + protected IRegionManager RegionManager { get; } protected IDialogService DialogService { get; } @@ -32,8 +34,11 @@ public virtual void ConfirmNavigationRequest(NavigationContext navigationContext continuationCallback?.Invoke(true); } + public virtual bool IsNavigationTarget(NavigationContext navigationContext) { + + return true; } @@ -49,6 +54,7 @@ public virtual void OnNavigatedFrom(NavigationContext navigationContext) /// public virtual void OnNavigatedTo(NavigationContext navigationContext) { + } } } diff --git a/AdamController.Core/Mvvm/ViewModelBase.cs b/AdamController.Core/Mvvm/ViewModelBase.cs index cb70a15..bb0678c 100644 --- a/AdamController.Core/Mvvm/ViewModelBase.cs +++ b/AdamController.Core/Mvvm/ViewModelBase.cs @@ -1,11 +1,20 @@ -using Prism.Mvvm; +using AdamController.Services.Interfaces; +using Prism.Mvvm; using Prism.Navigation; namespace AdamController.Core.Mvvm { public class ViewModelBase : BindableBase, IDestructible { - protected ViewModelBase() { } - public void Destroy() { } + public event SubRegionChangeEventHandler RaiseRegionChangeEvent; + + protected ViewModelBase() + { + + } + + public void Destroy() + { + } } } diff --git a/AdamController.Core/RegionNames.cs b/AdamController.Core/RegionNames.cs index 5555ee8..53f7c87 100644 --- a/AdamController.Core/RegionNames.cs +++ b/AdamController.Core/RegionNames.cs @@ -6,7 +6,5 @@ public class RegionNames public const string ContentRegion = $"{nameof(ContentRegion)}"; public const string MenuRegion = $"{nameof(MenuRegion)}"; public const string StatusBarRegion = $"{nameof(StatusBarRegion)}"; - - } } diff --git a/AdamController.Services/Interfaces/ISubRegionChangeAwareService.cs b/AdamController.Services/Interfaces/ISubRegionChangeAwareService.cs new file mode 100644 index 0000000..fbdf6a3 --- /dev/null +++ b/AdamController.Services/Interfaces/ISubRegionChangeAwareService.cs @@ -0,0 +1,10 @@ +namespace AdamController.Services.Interfaces +{ + public delegate void SubRegionChangeEventHandler(object sender); + + public interface ISubRegionChangeAwareService + { + public event SubRegionChangeEventHandler RaiseSubRegionChangeEvent; + public string InsideRegionNavigationRequestName { get; set; } + } +} diff --git a/AdamController.Services/SubRegionChangeAwareService.cs b/AdamController.Services/SubRegionChangeAwareService.cs new file mode 100644 index 0000000..8b1a0bb --- /dev/null +++ b/AdamController.Services/SubRegionChangeAwareService.cs @@ -0,0 +1,28 @@ +using AdamController.Services.Interfaces; + +namespace AdamController.Services +{ + public class SubRegionChangeAwareService : ISubRegionChangeAwareService + { + public SubRegionChangeAwareService() { } + + public event SubRegionChangeEventHandler RaiseSubRegionChangeEvent; + + private string mRegionNavigtedToName; + public string InsideRegionNavigationRequestName + { + get { return mRegionNavigtedToName; } + set + { + mRegionNavigtedToName = value; + OnRaiseRegionChangeEvent(); + } + } + + protected virtual void OnRaiseRegionChangeEvent() + { + SubRegionChangeEventHandler raiseEvent = RaiseSubRegionChangeEvent; + raiseEvent?.Invoke(this); + } + } +} diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index be00936..c179973 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -19,6 +19,8 @@ using AdamController.Modules.FlayoutsRegion; using AdamController.Core.Dialog.Views; using AdamController.Core.Dialog.ViewModels; +using AdamController.Services.Interfaces; +using AdamController.Core.Mvvm; #endregion @@ -34,7 +36,8 @@ public App() protected override Window CreateShell() { - var window = Container.Resolve(); + MainWindow window = Container.Resolve(); + return window; } @@ -69,9 +72,14 @@ protected override void OnStartup(StartupEventArgs e) protected override void RegisterTypes(IContainerRegistry containerRegistry) { + containerRegistry.RegisterSingleton(containerRegistry => + { + return new SubRegionChangeAwareService(); + }); + //here must be ip/port containerRegistry.Register(); - + containerRegistry.RegisterDialog(); containerRegistry.RegisterDialog(); } diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index e6389b4..4fd725e 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -1,33 +1,125 @@ using AdamController.Core; -using AdamController.Core.Mvvm; +using AdamController.Services.Interfaces; using Prism.Commands; using Prism.Mvvm; using Prism.Regions; -using Prism.Services.Dialogs; -using System; using System.Reflection; +using System.Windows; namespace AdamController.ViewModels { public class MainWindowViewModel : BindableBase { + #region Command + public DelegateCommand ShowRegionCommand { get; private set; } + #endregion + + #region Services + public IRegionManager RegionManager { get; } + private ISubRegionChangeAwareService SubRegionChangeAwareService { get; } - public MainWindowViewModel(IRegionManager regionManager, IDialogService dialogService) + #endregion + + #region ~ + + public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService) { RegionManager = regionManager; ShowRegionCommand = new DelegateCommand(ShowRegion); - - System.Windows.Application.Current.MainWindow.Loaded += MainWindow_Loaded; + SubRegionChangeAwareService = subRegionChangeAwareService; + + SubRegionChangeAwareService.RaiseSubRegionChangeEvent += RaiseSubRegionChangeEvent; + Application.Current.MainWindow.Loaded += MainWindowLoaded; } - private void MainWindow_Loaded(object sender, System.Windows.RoutedEventArgs e) + #endregion + + #region Events + + /// + /// Load default region at startup + /// Need to call it after loading the main window + /// + private void MainWindowLoaded(object sender, RoutedEventArgs e) { ShowRegionCommand.Execute(SubRegionNames.SubRegionScratch); } + /// + /// Changes the selected section in the hamburger menu + /// + private void RaiseSubRegionChangeEvent(object sender) + { + var changeRegionName = SubRegionChangeAwareService?.InsideRegionNavigationRequestName; + ChangeSelectedIndexByRegionName(changeRegionName); + } + + #endregion + + #region Fields + + /// + /// -1 is not selected + /// + private int mHamburgerMenuSelectedIndex = -1; + public int HamburgerMenuSelectedIndex + { + get { return mHamburgerMenuSelectedIndex; } + set + { + if(mHamburgerMenuSelectedIndex == value) + return; + + SetProperty(ref mHamburgerMenuSelectedIndex, value); + } + } + + /// + /// -1 is not selected + /// + private int mHamburgerMenuSelectedOptionsIndex = -1; + + public int HamburgerMenuSelectedOptionsIndex + { + get { return mHamburgerMenuSelectedOptionsIndex; } + + set + { + if (mHamburgerMenuSelectedOptionsIndex == value) + return; + + SetProperty(ref mHamburgerMenuSelectedOptionsIndex, value); + } + } + + public string WindowTitle => $"Adam IDE {Assembly.GetExecutingAssembly().GetName().Version}"; + + #endregion + + #region Methods + + private void ChangeSelectedIndexByRegionName(string subRegionName) + { + switch (subRegionName) + { + case SubRegionNames.SubRegionScratch: + HamburgerMenuSelectedIndex = 0; + break; + case SubRegionNames.SubRegionScriptEditor: + HamburgerMenuSelectedIndex = 1; + break; + case SubRegionNames.SubRegionComputerVisionControl: + HamburgerMenuSelectedIndex = 2; + break; + case SubRegionNames.SubRegionVisualSettings: + HamburgerMenuSelectedOptionsIndex = 0; + break; + } + } + private void ShowRegion(string subRegionName) { switch (subRegionName) @@ -47,43 +139,36 @@ private void ShowRegion(string subRegionName) } } - - #region Services - - - #endregion - #region Fields + #region Old - public string WindowTitle => $"Adam IDE {Assembly.GetExecutingAssembly().GetName().Version}"; + //public MainWindowViewModel() + //{ + //ComunicateHelper.OnAdamTcpConnectedEvent += OnTcpConnected; + //ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; + //ComunicateHelper.OnAdamTcpReconnected += OnTcpReconnected; + //ComunicateHelper.OnAdamLogServerUdpReceivedEvent += ComunicateHelperOnAdamUdpReceived; - #endregion - //public MainWindowViewModel() + //InitAction(); + + //if (Settings.Default.AutoStartTcpConnect) //{ - //ComunicateHelper.OnAdamTcpConnectedEvent += OnTcpConnected; - //ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; - //ComunicateHelper.OnAdamTcpReconnected += OnTcpReconnected; - //ComunicateHelper.OnAdamLogServerUdpReceivedEvent += ComunicateHelperOnAdamUdpReceived; - + // ConnectButtonComand.Execute(null); + //} + //else + //{ + //init fields if autorun off + //TextOnConnectFlayotButton = mConnectButtonStatusDisconnected; + //TextOnStatusConnectToolbar = mToolbarStatusClientDisconnected; - //InitAction(); - - //if (Settings.Default.AutoStartTcpConnect) - //{ - // ConnectButtonComand.Execute(null); - //} - //else - //{ - //init fields if autorun off - //TextOnConnectFlayotButton = mConnectButtonStatusDisconnected; - //TextOnStatusConnectToolbar = mToolbarStatusClientDisconnected; - - //ConnectIcon = PackIconModernKind.Connect; - //IconOnConnectFlayoutButton = PackIconMaterialKind.RobotDead; - //} + //ConnectIcon = PackIconModernKind.Connect; + //IconOnConnectFlayoutButton = PackIconMaterialKind.RobotDead; + //} //} + #endregion + } } diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index cea36bf..3918817 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -141,6 +141,8 @@ diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs index f6eaa5e..568873b 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs @@ -1,6 +1,7 @@ using AdamController.Core.Helpers; using AdamController.Core.Model; using AdamController.Core.Mvvm; +using AdamController.Services.Interfaces; using AdamController.WebApi.Client.v1; using Newtonsoft.Json; using Prism.Commands; diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs index 0b8423f..3e7296d 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs @@ -3,6 +3,7 @@ using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Modules.ContentRegion.Views; +using AdamController.Services.Interfaces; using Prism.Regions; using Prism.Services.Dialogs; using System; @@ -11,35 +12,37 @@ namespace AdamController.Modules.ContentRegion.ViewModels { public class ContentRegionViewModel : RegionViewModelBase { - public ContentRegionViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) + private ISubRegionChangeAwareService RegionChangeAwareService { get; } + + public ContentRegionViewModel(IRegionManager regionManager, IDialogService dialogService, ISubRegionChangeAwareService regionChangeAwareService) : base(regionManager, dialogService) { - + RegionChangeAwareService = regionChangeAwareService; } #region Navigation - public override void OnNavigatedTo(NavigationContext navigationContext) - { - //SubRegionsRequestNavigate(navigationContext.Uri.ToString(), navigationContext.Parameters); - //is loaded on startup region - //SubRegionsRequestNavigate(SubRegionNames.SubRegionScratch, navigationContext.Parameters); - } - public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) { - SubRegionsRequestNavigate(navigationContext.Uri.ToString(), navigationContext.Parameters); + if (navigationContext.NavigationService.Region.Name == RegionNames.ContentRegion) + { + var insideRegionName = navigationContext.Uri.OriginalString; + + RegionChangeAwareService.InsideRegionNavigationRequestName = insideRegionName; + SubRegionsRequestNavigate(insideRegionName, navigationContext.Parameters); + } } - private void SubRegionsRequestNavigate(string tag, NavigationParameters parameters) + private void SubRegionsRequestNavigate(string uri, NavigationParameters parameters) { - if (string.IsNullOrEmpty(tag)) + if (string.IsNullOrEmpty(uri)) return; - - switch (tag) + + switch (uri) { case SubRegionNames.SubRegionScratch: + RegionManager.RequestNavigate(SubRegionNames.InsideConentRegion, nameof(ScratchControlView), parameters); break; diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index 9fc6d7e..be192a8 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -8,6 +8,7 @@ using AdamController.Core.Mvvm; using AdamController.Core.Properties; using AdamController.Modules.ContentRegion.Views; +using AdamController.Services.Interfaces; using AdamController.WebApi.Client.v1; using MessageDialogManagerLib; using Newtonsoft.Json; diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs index 3057f66..2dcff7f 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs @@ -1,5 +1,6 @@ using AdamController.Core.Helpers; using AdamController.Core.Mvvm; +using AdamController.Services.Interfaces; using AdamController.WebApi.Client.v1; using AdamController.WebApi.Client.v1.ResponseModel; using MessageDialogManagerLib; diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index 0c05bed..42d4a77 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -18,7 +18,7 @@ public class VisualSettingsControlViewModel : RegionViewModelBase { public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) { - sbyte s = 4; + } #region Navigation diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs b/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs index 2ede72f..7b1f1d4 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs +++ b/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs @@ -23,14 +23,23 @@ public ComputerVisionControlView() private void VideoView_Loaded(object sender, RoutedEventArgs e) { - mLibVLC = new LibVLC(enableDebugLogs: false); - mMediaPlayer = new MediaPlayer(mLibVLC); + try + { + mLibVLC = new LibVLC(enableDebugLogs: false); + mMediaPlayer = new MediaPlayer(mLibVLC); + + VideoView.MediaPlayer = mMediaPlayer; - VideoView.MediaPlayer = mMediaPlayer; + mMediaPlayer.EnableHardwareDecoding = true; + mMediaPlayer.NetworkCaching = 1000; + mMediaPlayer.Scale = 0.72f; + } + catch + { + //fix for + //LibVLCSharp.Shared.VLCException: "Failed to load required native libraries + } - mMediaPlayer.EnableHardwareDecoding = true; - mMediaPlayer.NetworkCaching = 1000; - mMediaPlayer.Scale = 0.72f; } private void UserControlUnloaded(object sender, RoutedEventArgs e) @@ -42,8 +51,8 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - mMediaPlayer.Dispose(); - mLibVLC.Dispose(); + mMediaPlayer?.Dispose(); + mLibVLC?.Dispose(); } } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs index 4d65425..94f1d26 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs @@ -1,4 +1,5 @@ using AdamController.Core.Mvvm; +using AdamController.Services.Interfaces; using Prism.Regions; using Prism.Services.Dialogs; diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index 58819ce..b08b8bc 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -1,6 +1,7 @@ using AdamController.Core.Helpers; using AdamController.Core.Mvvm; using AdamController.Core.Properties; +using AdamController.Services.Interfaces; using MahApps.Metro.IconPacks; using Prism.Commands; using Prism.Regions; diff --git a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs index ec1a66e..cde4d57 100644 --- a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs +++ b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs @@ -5,6 +5,7 @@ using Prism.Regions; using Prism.Services.Dialogs; using System.Windows; +using AdamController.Services.Interfaces; namespace AdamController.Modules.MenuRegion.ViewModels { diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index f6d3dc3..0874ca7 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -1,4 +1,5 @@ using AdamController.Core.Mvvm; +using AdamController.Services.Interfaces; using MahApps.Metro.IconPacks; using Prism.Commands; using Prism.Regions; From fd2c120e5e07dd48ec57c2e220101d462896518d Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 24 Mar 2024 11:53:59 +1000 Subject: [PATCH 057/181] Remove unused code. Fix naming for adamtcp service --- .../Helpers/ComunicateBenchmarkHelper.cs | 2 +- .../Helpers/ComunicateHelper.cs | 2 +- ...amTcpClient.cs => AdamTcpClientService.cs} | 43 +------- .../Interfaces/IAdamTcpClientService.cs | 41 +++++++ AdamController/App.xaml.cs | 2 +- AdamController/Commands/RelayCommand.cs | 100 ------------------ 6 files changed, 47 insertions(+), 143 deletions(-) rename AdamController.Services/{AdamTcpClient.cs => AdamTcpClientService.cs} (80%) create mode 100644 AdamController.Services/Interfaces/IAdamTcpClientService.cs delete mode 100644 AdamController/Commands/RelayCommand.cs diff --git a/AdamController.Core/Helpers/ComunicateBenchmarkHelper.cs b/AdamController.Core/Helpers/ComunicateBenchmarkHelper.cs index 7842bc4..2820cfb 100644 --- a/AdamController.Core/Helpers/ComunicateBenchmarkHelper.cs +++ b/AdamController.Core/Helpers/ComunicateBenchmarkHelper.cs @@ -50,7 +50,7 @@ public static ComunicateBenchmarkHelper Instance public bool TcpClientIsConnected => mAdamTcpClient != null && mAdamTcpClient.IsConnected; - private static AdamTcpClient mAdamTcpClient; + private static AdamTcpClientService mAdamTcpClient; #region ~ diff --git a/AdamController.Core/Helpers/ComunicateHelper.cs b/AdamController.Core/Helpers/ComunicateHelper.cs index 5e5af11..2c11929 100644 --- a/AdamController.Core/Helpers/ComunicateHelper.cs +++ b/AdamController.Core/Helpers/ComunicateHelper.cs @@ -32,7 +32,7 @@ public sealed class ComunicateHelper public static bool TcpClientIsConnected => mAdamTcpClient != null && mAdamTcpClient.IsConnected; - private static AdamTcpClient mAdamTcpClient; + private static AdamTcpClientService mAdamTcpClient; private static AdamUdpClient mAdamUdpMessageClient; private static AdamUdpServer mAdamUdpLogServer; private static AdamWebSocketClient mAdamWebSocketClient; diff --git a/AdamController.Services/AdamTcpClient.cs b/AdamController.Services/AdamTcpClientService.cs similarity index 80% rename from AdamController.Services/AdamTcpClient.cs rename to AdamController.Services/AdamTcpClientService.cs index 37f5bf6..9a0a9ff 100644 --- a/AdamController.Services/AdamTcpClient.cs +++ b/AdamController.Services/AdamTcpClientService.cs @@ -1,4 +1,5 @@ using AdamController.Services.AdamTcpClientDependency; +using AdamController.Services.Interfaces; using System; using System.Net.Sockets; using System.Threading; @@ -6,45 +7,7 @@ namespace AdamController.Services { - #region Events - - public delegate void TcpCientConnected(object sender); - public delegate void TcpCientSent(object sender, long sent, long pending); - public delegate void TcpClientDisconnect(object sender); - public delegate void TcpClientError(object sender, SocketError error); - public delegate void TcpClientReceived(object sender, byte[] buffer, long offset, long size); - public delegate void TcpClientReconnected(object sender, int reconnectCount); - - #endregion - - public interface IAdamTcpClient - { - #region Events - - public event TcpCientConnected RaiseTcpCientConnected; - public event TcpCientSent RaiseTcpCientSent; - public event TcpClientDisconnect RaiseTcpClientDisconnected; - public event TcpClientError RaiseTcpClientError; - public event TcpClientReceived RaiseTcpClientReceived; - public event TcpClientReconnected RaiseTcpClientReconnected; - - #endregion - - /// - /// The number of reconnections when the connection is lost - /// - public int ReconnectCount { get; } - - /// - /// Reconnection timeout - /// - public int ReconnectTimeout { get; } - - public void DisconnectAndStop(); - - } - - public class AdamTcpClient : NetCoreServer.TcpClient, IAdamTcpClient + public class AdamTcpClientService : NetCoreServer.TcpClient, IAdamTcpClientService { #region Events @@ -69,7 +32,7 @@ public class AdamTcpClient : NetCoreServer.TcpClient, IAdamTcpClient #region ~ - public AdamTcpClient(string address, int port, AdamTcpClientOption option) : base(address, port) + public AdamTcpClientService(string address, int port, AdamTcpClientOption option) : base(address, port) { ReconnectCount = option.ReconnectCount; ReconnectTimeout = option.ReconnectTimeout; diff --git a/AdamController.Services/Interfaces/IAdamTcpClientService.cs b/AdamController.Services/Interfaces/IAdamTcpClientService.cs new file mode 100644 index 0000000..cb3ae81 --- /dev/null +++ b/AdamController.Services/Interfaces/IAdamTcpClientService.cs @@ -0,0 +1,41 @@ +using System.Net.Sockets; + +namespace AdamController.Services.Interfaces +{ + #region Events + + public delegate void TcpCientConnected(object sender); + public delegate void TcpCientSent(object sender, long sent, long pending); + public delegate void TcpClientDisconnect(object sender); + public delegate void TcpClientError(object sender, SocketError error); + public delegate void TcpClientReceived(object sender, byte[] buffer, long offset, long size); + public delegate void TcpClientReconnected(object sender, int reconnectCount); + + #endregion + + public interface IAdamTcpClientService + { + #region Events + + public event TcpCientConnected RaiseTcpCientConnected; + public event TcpCientSent RaiseTcpCientSent; + public event TcpClientDisconnect RaiseTcpClientDisconnected; + public event TcpClientError RaiseTcpClientError; + public event TcpClientReceived RaiseTcpClientReceived; + public event TcpClientReconnected RaiseTcpClientReconnected; + + #endregion + + /// + /// The number of reconnections when the connection is lost + /// + public int ReconnectCount { get; } + + /// + /// Reconnection timeout + /// + public int ReconnectTimeout { get; } + + public void DisconnectAndStop(); + } +} diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index c179973..5426ca6 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -78,7 +78,7 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) }); //here must be ip/port - containerRegistry.Register(); + containerRegistry.Register(); containerRegistry.RegisterDialog(); containerRegistry.RegisterDialog(); diff --git a/AdamController/Commands/RelayCommand.cs b/AdamController/Commands/RelayCommand.cs deleted file mode 100644 index ba680fd..0000000 --- a/AdamController/Commands/RelayCommand.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; -using System.Windows.Input; - -namespace AdamController.Commands -{ - /// Provides an implementation of the interface. - public class RelayCommand : ICommand - { - private readonly Action mExecute; - private readonly Func mCanExecute; - - public RelayCommand(Action execute, Func canExecute = null) - { - mExecute = execute; - mCanExecute = canExecute; - } - - public event EventHandler CanExecuteChanged - { - add { CommandManager.RequerySuggested += value; } - remove { CommandManager.RequerySuggested -= value; } - } - - public bool CanExecute(object parameter) - { - return mCanExecute == null || mCanExecute(parameter); - } - - public void Execute(object parameter) - { - mExecute(parameter); - } - } - - public class RelayCommand : ICommand - { - #region Fields - - private readonly Action mExecute; - private readonly Predicate mCanExecute; - - #endregion - - #region Constructors - - /// - /// Initializes a new instance of DelegateCommand{T}/>. - /// - /// Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate. - /// will always return true. - public RelayCommand(Action execute) : this(execute, null){} - - /// - /// Creates a new command. - /// - /// The execution logic. - /// The execution status logic. - public RelayCommand(Action execute, Predicate canExecute) - { - mExecute = execute ?? throw new ArgumentNullException(nameof(execute)); - mCanExecute = canExecute; - } - - #endregion - - #region ICommand Members - - /// - /// - /// Defines the method that determines whether the command can execute in its current state. - /// - /// Data used by the command. If the command does not require data to be passed, this object can be set to null. - /// - /// true if this command can be executed; otherwise, false. - /// - public bool CanExecute(object parameter) => mCanExecute?.Invoke((T)parameter) ?? true; - - /// - /// - /// Occurs when changes occur that affect whether or not the command should execute. - /// - public event EventHandler CanExecuteChanged - { - add { CommandManager.RequerySuggested += value; } - remove { CommandManager.RequerySuggested -= value; } - } - - /// - /// - /// Defines the method to be called when the command is invoked. - /// - /// Data used by the command. If the command does not require data to be passed, this object can be set to . - public void Execute(object parameter) - { - mExecute((T)parameter); - } - - #endregion - } -} From d5abd793a3ad05cf922bf6cad5db828f1ce0c205 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 24 Mar 2024 12:04:15 +1000 Subject: [PATCH 058/181] Move AdamPython.xshd to Core resources --- .../AdamController.Core.csproj | 19 +++ .../Properties/AdamPython.xshd | 0 .../Properties/Resource.Designer.cs | 73 +++++++++++ AdamController.Core/Properties/Resource.resx | 124 ++++++++++++++++++ AdamController/AdamController.csproj | 10 +- AdamController/App.xaml.cs | 2 +- .../Properties/Resources.Designer.cs | 16 +-- AdamController/Properties/Resources.resx | 8 +- 8 files changed, 228 insertions(+), 24 deletions(-) rename {AdamController => AdamController.Core}/Properties/AdamPython.xshd (100%) create mode 100644 AdamController.Core/Properties/Resource.Designer.cs create mode 100644 AdamController.Core/Properties/Resource.resx diff --git a/AdamController.Core/AdamController.Core.csproj b/AdamController.Core/AdamController.Core.csproj index 4443191..4edbbd0 100644 --- a/AdamController.Core/AdamController.Core.csproj +++ b/AdamController.Core/AdamController.Core.csproj @@ -10,6 +10,14 @@ bin\x64\Release\ + + + + + + Always + + @@ -31,12 +39,23 @@ + + True + True + Resource.resx + True Settings.settings True + + + PublicResXFileCodeGenerator + Resource.Designer.cs + + Settings.Designer.cs diff --git a/AdamController/Properties/AdamPython.xshd b/AdamController.Core/Properties/AdamPython.xshd similarity index 100% rename from AdamController/Properties/AdamPython.xshd rename to AdamController.Core/Properties/AdamPython.xshd diff --git a/AdamController.Core/Properties/Resource.Designer.cs b/AdamController.Core/Properties/Resource.Designer.cs new file mode 100644 index 0000000..dbdc537 --- /dev/null +++ b/AdamController.Core/Properties/Resource.Designer.cs @@ -0,0 +1,73 @@ +//------------------------------------------------------------------------------ +// +// Этот код создан программой. +// Исполняемая версия:4.0.30319.42000 +// +// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае +// повторной генерации кода. +// +//------------------------------------------------------------------------------ + +namespace AdamController.Core.Properties { + using System; + + + /// + /// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д. + /// + // Этот класс создан автоматически классом StronglyTypedResourceBuilder + // с помощью такого средства, как ResGen или Visual Studio. + // Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen + // с параметром /str или перестройте свой проект VS. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Resource { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resource() { + } + + /// + /// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AdamController.Core.Properties.Resource", typeof(Resource).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Перезаписывает свойство CurrentUICulture текущего потока для всех + /// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Поиск локализованного ресурса типа System.Byte[]. + /// + public static byte[] AdamPython { + get { + object obj = ResourceManager.GetObject("AdamPython", resourceCulture); + return ((byte[])(obj)); + } + } + } +} diff --git a/AdamController.Core/Properties/Resource.resx b/AdamController.Core/Properties/Resource.resx new file mode 100644 index 0000000..07a7479 --- /dev/null +++ b/AdamController.Core/Properties/Resource.resx @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + AdamPython.xshd;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/AdamController/AdamController.csproj b/AdamController/AdamController.csproj index 9f194d6..d19873d 100644 --- a/AdamController/AdamController.csproj +++ b/AdamController/AdamController.csproj @@ -32,7 +32,6 @@ - @@ -44,9 +43,6 @@ - - Always - @@ -64,4 +60,10 @@ Resources.resx + + + ResXFileCodeGenerator + Resources.Designer.cs + + \ No newline at end of file diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 5426ca6..db0c274 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -96,7 +96,7 @@ private static void LoadHighlighting() { try { - using var stream = new MemoryStream(AdamController.Properties.Resources.AdamPython); + using var stream = new MemoryStream(Core.Properties.Resource.AdamPython); using var reader = new XmlTextReader(stream); HighlightingManager.Instance.RegisterHighlighting("AdamPython", Array.Empty(), ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader, HighlightingManager.Instance)); diff --git a/AdamController/Properties/Resources.Designer.cs b/AdamController/Properties/Resources.Designer.cs index 1f8e8d2..6f39a80 100644 --- a/AdamController/Properties/Resources.Designer.cs +++ b/AdamController/Properties/Resources.Designer.cs @@ -22,7 +22,7 @@ namespace AdamController.Properties { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - public class Resources { + internal class Resources { private static global::System.Resources.ResourceManager resourceMan; @@ -36,7 +36,7 @@ internal Resources() { /// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Resources.ResourceManager ResourceManager { + internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AdamController.Properties.Resources", typeof(Resources).Assembly); @@ -51,7 +51,7 @@ internal Resources() { /// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Globalization.CultureInfo Culture { + internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -59,15 +59,5 @@ internal Resources() { resourceCulture = value; } } - - /// - /// Поиск локализованного ресурса типа System.Byte[]. - /// - public static byte[] AdamPython { - get { - object obj = ResourceManager.GetObject("AdamPython", resourceCulture); - return ((byte[])(obj)); - } - } } } diff --git a/AdamController/Properties/Resources.resx b/AdamController/Properties/Resources.resx index 9ad5cd9..1af7de1 100644 --- a/AdamController/Properties/Resources.resx +++ b/AdamController/Properties/Resources.resx @@ -112,13 +112,9 @@ 2.0 - System.Resources.ResXResourceReader, System.Windows.Forms, Version=6.0.2.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=6.0.2.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - AdamPython.xshd;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - \ No newline at end of file From 0a8bd69023e133e0897af20183729e7f53f042eb Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 24 Mar 2024 18:45:38 +1000 Subject: [PATCH 059/181] Move main icon to core resources --- .../AdamController.Core.csproj | 4 + .../Properties/Icons/main_app_icon.ico | Bin .../Properties/Resource.Designer.cs | 10 + AdamController.Core/Properties/Resource.resx | 3 + AdamController/AdamController.csproj | 23 - .../Properties/Resources.Designer.cs | 63 - AdamController/Properties/Resources.resx | 120 -- .../Properties/Settings.Designer.cs | 1058 ----------------- AdamController/Properties/Settings.settings | 264 ---- 9 files changed, 17 insertions(+), 1528 deletions(-) rename AdamController/Images/Icons/AdamIconAndRGBPageIcon.ico => AdamController.Core/Properties/Icons/main_app_icon.ico (100%) delete mode 100644 AdamController/Properties/Resources.Designer.cs delete mode 100644 AdamController/Properties/Resources.resx delete mode 100644 AdamController/Properties/Settings.Designer.cs delete mode 100644 AdamController/Properties/Settings.settings diff --git a/AdamController.Core/AdamController.Core.csproj b/AdamController.Core/AdamController.Core.csproj index 4edbbd0..9744ef3 100644 --- a/AdamController.Core/AdamController.Core.csproj +++ b/AdamController.Core/AdamController.Core.csproj @@ -12,6 +12,7 @@ + @@ -38,6 +39,9 @@ + + + True diff --git a/AdamController/Images/Icons/AdamIconAndRGBPageIcon.ico b/AdamController.Core/Properties/Icons/main_app_icon.ico similarity index 100% rename from AdamController/Images/Icons/AdamIconAndRGBPageIcon.ico rename to AdamController.Core/Properties/Icons/main_app_icon.ico diff --git a/AdamController.Core/Properties/Resource.Designer.cs b/AdamController.Core/Properties/Resource.Designer.cs index dbdc537..d2dbece 100644 --- a/AdamController.Core/Properties/Resource.Designer.cs +++ b/AdamController.Core/Properties/Resource.Designer.cs @@ -69,5 +69,15 @@ public static byte[] AdamPython { return ((byte[])(obj)); } } + + /// + /// Поиск локализованного ресурса типа System.Drawing.Icon, аналогичного (Значок). + /// + public static System.Drawing.Icon main_app_icon { + get { + object obj = ResourceManager.GetObject("main_app_icon", resourceCulture); + return ((System.Drawing.Icon)(obj)); + } + } } } diff --git a/AdamController.Core/Properties/Resource.resx b/AdamController.Core/Properties/Resource.resx index 07a7479..572b121 100644 --- a/AdamController.Core/Properties/Resource.resx +++ b/AdamController.Core/Properties/Resource.resx @@ -121,4 +121,7 @@ AdamPython.xshd;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Icons\main_app_icon.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + \ No newline at end of file diff --git a/AdamController/AdamController.csproj b/AdamController/AdamController.csproj index d19873d..46e2905 100644 --- a/AdamController/AdamController.csproj +++ b/AdamController/AdamController.csproj @@ -2,7 +2,6 @@ Dynamic False - Images\Icons\AdamIconAndRGBPageIcon.ico MIT-Modern-Variant 1.0.2.4 1.0.2.4 @@ -28,12 +27,6 @@ 1701;1702;CA1416 - - - - - - @@ -41,9 +34,6 @@ - - - @@ -53,17 +43,4 @@ - - - True - True - Resources.resx - - - - - ResXFileCodeGenerator - Resources.Designer.cs - - \ No newline at end of file diff --git a/AdamController/Properties/Resources.Designer.cs b/AdamController/Properties/Resources.Designer.cs deleted file mode 100644 index 6f39a80..0000000 --- a/AdamController/Properties/Resources.Designer.cs +++ /dev/null @@ -1,63 +0,0 @@ -//------------------------------------------------------------------------------ -// -// Этот код создан программой. -// Исполняемая версия:4.0.30319.42000 -// -// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае -// повторной генерации кода. -// -//------------------------------------------------------------------------------ - -namespace AdamController.Properties { - using System; - - - /// - /// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д. - /// - // Этот класс создан автоматически классом StronglyTypedResourceBuilder - // с помощью такого средства, как ResGen или Visual Studio. - // Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen - // с параметром /str или перестройте свой проект VS. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AdamController.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Перезаписывает свойство CurrentUICulture текущего потока для всех - /// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - } -} diff --git a/AdamController/Properties/Resources.resx b/AdamController/Properties/Resources.resx deleted file mode 100644 index 1af7de1..0000000 --- a/AdamController/Properties/Resources.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/AdamController/Properties/Settings.Designer.cs b/AdamController/Properties/Settings.Designer.cs deleted file mode 100644 index 283bb7b..0000000 --- a/AdamController/Properties/Settings.Designer.cs +++ /dev/null @@ -1,1058 +0,0 @@ -//------------------------------------------------------------------------------ -// -// Этот код создан программой. -// Исполняемая версия:4.0.30319.42000 -// -// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае -// повторной генерации кода. -// -//------------------------------------------------------------------------------ - -namespace AdamController.Properties { - - - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.6.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { - - private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default { - get { - return defaultInstance; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("18000")] - public string VideoDataExchangePort { - get { - return ((string)(this["VideoDataExchangePort"])); - } - set { - this["VideoDataExchangePort"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("15005")] - public string MessageDataExchangePort { - get { - return ((string)(this["MessageDataExchangePort"])); - } - set { - this["MessageDataExchangePort"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("192.168.50.10")] - public string ServerIP { - get { - return ((string)(this["ServerIP"])); - } - set { - this["ServerIP"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("Light")] - public string BaseTheme { - get { - return ((string)(this["BaseTheme"])); - } - set { - this["BaseTheme"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("Blue")] - public string ThemeColorScheme { - get { - return ((string)(this["ThemeColorScheme"])); - } - set { - this["ThemeColorScheme"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("0")] - public int DisplaySetBlocks { - get { - return ((int)(this["DisplaySetBlocks"])); - } - set { - this["DisplaySetBlocks"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("False")] - public bool BlocklyShowTrashcan { - get { - return ((bool)(this["BlocklyShowTrashcan"])); - } - set { - this["BlocklyShowTrashcan"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("20")] - public short BlocklyGridSpacing { - get { - return ((short)(this["BlocklyGridSpacing"])); - } - set { - this["BlocklyGridSpacing"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("0")] - public short BlocklyGridLenth { - get { - return ((short)(this["BlocklyGridLenth"])); - } - set { - this["BlocklyGridLenth"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyGridColour { - get { - return ((string)(this["BlocklyGridColour"])); - } - set { - this["BlocklyGridColour"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklySnapToGridNodes { - get { - return ((bool)(this["BlocklySnapToGridNodes"])); - } - set { - this["BlocklySnapToGridNodes"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklyShowGrid { - get { - return ((bool)(this["BlocklyShowGrid"])); - } - set { - this["BlocklyShowGrid"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("ru")] - public string AppLanguage { - get { - return ((string)(this["AppLanguage"])); - } - set { - this["AppLanguage"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("ru")] - public global::AdamBlocklyLibrary.Enum.BlocklyLanguage BlocklyToolboxLanguage { - get { - return ((global::AdamBlocklyLibrary.Enum.BlocklyLanguage)(this["BlocklyToolboxLanguage"])); - } - set { - this["BlocklyToolboxLanguage"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("ru")] - public global::AdamBlocklyLibrary.Enum.BlocklyLanguage BlocklyWorkspaceLanguage { - get { - return ((global::AdamBlocklyLibrary.Enum.BlocklyLanguage)(this["BlocklyWorkspaceLanguage"])); - } - set { - this["BlocklyWorkspaceLanguage"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklyLogicCategoryState { - get { - return ((bool)(this["BlocklyLogicCategoryState"])); - } - set { - this["BlocklyLogicCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklyColorCategoryState { - get { - return ((bool)(this["BlocklyColorCategoryState"])); - } - set { - this["BlocklyColorCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklyListsCategoryState { - get { - return ((bool)(this["BlocklyListsCategoryState"])); - } - set { - this["BlocklyListsCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklyLoopCategoryState { - get { - return ((bool)(this["BlocklyLoopCategoryState"])); - } - set { - this["BlocklyLoopCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklyMathCategoryState { - get { - return ((bool)(this["BlocklyMathCategoryState"])); - } - set { - this["BlocklyMathCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklyProcedureCategoryState { - get { - return ((bool)(this["BlocklyProcedureCategoryState"])); - } - set { - this["BlocklyProcedureCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("False")] - public bool BlocklyDynamicVariableCategoryState { - get { - return ((bool)(this["BlocklyDynamicVariableCategoryState"])); - } - set { - this["BlocklyDynamicVariableCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklyVariableCategoryState { - get { - return ((bool)(this["BlocklyVariableCategoryState"])); - } - set { - this["BlocklyVariableCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyLogicCategoryAlternateName { - get { - return ((string)(this["BlocklyLogicCategoryAlternateName"])); - } - set { - this["BlocklyLogicCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyColourCategoryAlternateName { - get { - return ((string)(this["BlocklyColourCategoryAlternateName"])); - } - set { - this["BlocklyColourCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyListsCategoryAlternateName { - get { - return ((string)(this["BlocklyListsCategoryAlternateName"])); - } - set { - this["BlocklyListsCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyLoopCategoryAlternateName { - get { - return ((string)(this["BlocklyLoopCategoryAlternateName"])); - } - set { - this["BlocklyLoopCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyMathCategoryAlternateName { - get { - return ((string)(this["BlocklyMathCategoryAlternateName"])); - } - set { - this["BlocklyMathCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyProcedureCategoryAlternateName { - get { - return ((string)(this["BlocklyProcedureCategoryAlternateName"])); - } - set { - this["BlocklyProcedureCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyDynamicVariableCategoryAlternateName { - get { - return ((string)(this["BlocklyDynamicVariableCategoryAlternateName"])); - } - set { - this["BlocklyDynamicVariableCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyVariableCategoryAlternateName { - get { - return ((string)(this["BlocklyVariableCategoryAlternateName"])); - } - set { - this["BlocklyVariableCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("Classic")] - public global::AdamBlocklyLibrary.Enum.BlocklyTheme BlocklyTheme { - get { - return ((global::AdamBlocklyLibrary.Enum.BlocklyTheme)(this["BlocklyTheme"])); - } - set { - this["BlocklyTheme"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("False")] - public bool ChangeToolboxLanguageToggleSwitchState { - get { - return ((bool)(this["ChangeToolboxLanguageToggleSwitchState"])); - } - set { - this["ChangeToolboxLanguageToggleSwitchState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("False")] - public bool ChangeBlocklyThemeToggleSwitchState { - get { - return ((bool)(this["ChangeBlocklyThemeToggleSwitchState"])); - } - set { - this["ChangeBlocklyThemeToggleSwitchState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("False")] - public bool ChangeGridColorSwitchToggleSwitchState { - get { - return ((bool)(this["ChangeGridColorSwitchToggleSwitchState"])); - } - set { - this["ChangeGridColorSwitchToggleSwitchState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("False")] - public bool ChangeSpacingSwitchToggleSwitchState { - get { - return ((bool)(this["ChangeSpacingSwitchToggleSwitchState"])); - } - set { - this["ChangeSpacingSwitchToggleSwitchState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("854")] - public double BlocklyEditorWidth { - get { - return ((double)(this["BlocklyEditorWidth"])); - } - set { - this["BlocklyEditorWidth"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("512")] - public double BlocklySourceEditorHeight { - get { - return ((double)(this["BlocklySourceEditorHeight"])); - } - set { - this["BlocklySourceEditorHeight"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklyRestoreBlockOnLoad { - get { - return ((bool)(this["BlocklyRestoreBlockOnLoad"])); - } - set { - this["BlocklyRestoreBlockOnLoad"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string SavedUserWorkspaceFolderPath { - get { - return ((string)(this["SavedUserWorkspaceFolderPath"])); - } - set { - this["SavedUserWorkspaceFolderPath"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string SavedUserCustomBlocksFolderPath { - get { - return ((string)(this["SavedUserCustomBlocksFolderPath"])); - } - set { - this["SavedUserCustomBlocksFolderPath"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string SavedUserScriptsFolderPath { - get { - return ((string)(this["SavedUserScriptsFolderPath"])); - } - set { - this["SavedUserScriptsFolderPath"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string SavedUserToolboxFolderPath { - get { - return ((string)(this["SavedUserToolboxFolderPath"])); - } - set { - this["SavedUserToolboxFolderPath"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyTextCategoryAlternateName { - get { - return ((string)(this["BlocklyTextCategoryAlternateName"])); - } - set { - this["BlocklyTextCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklyTextCategoryState { - get { - return ((bool)(this["BlocklyTextCategoryState"])); - } - set { - this["BlocklyTextCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool ShadowWorkspaceInDebug { - get { - return ((bool)(this["ShadowWorkspaceInDebug"])); - } - set { - this["ShadowWorkspaceInDebug"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("15000")] - public int TcpConnectStatePort { - get { - return ((int)(this["TcpConnectStatePort"])); - } - set { - this["TcpConnectStatePort"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("32")] - public int BenchmarkTcpSizeByteArray { - get { - return ((int)(this["BenchmarkTcpSizeByteArray"])); - } - set { - this["BenchmarkTcpSizeByteArray"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("192.168.50.10")] - public string BenchmarkTestServerIp { - get { - return ((string)(this["BenchmarkTestServerIp"])); - } - set { - this["BenchmarkTestServerIp"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("15000")] - public int BenchmarkTestTcpServerPort { - get { - return ((int)(this["BenchmarkTestTcpServerPort"])); - } - set { - this["BenchmarkTestTcpServerPort"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("1")] - public int BenchmarkTestTcpClientsQty { - get { - return ((int)(this["BenchmarkTestTcpClientsQty"])); - } - set { - this["BenchmarkTestTcpClientsQty"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("1000")] - public int BenchmarkTestTcpMessageQty { - get { - return ((int)(this["BenchmarkTestTcpMessageQty"])); - } - set { - this["BenchmarkTestTcpMessageQty"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("10")] - public int BenchmarkTestTcpTime { - get { - return ((int)(this["BenchmarkTestTcpTime"])); - } - set { - this["BenchmarkTestTcpTime"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("10")] - public int BenchmarkTestUdpTime { - get { - return ((int)(this["BenchmarkTestUdpTime"])); - } - set { - this["BenchmarkTestUdpTime"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("16001")] - public int BenchmarkTcpTestPort { - get { - return ((int)(this["BenchmarkTcpTestPort"])); - } - set { - this["BenchmarkTcpTestPort"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("16002")] - public int BenchmarkUdpTestPort { - get { - return ((int)(this["BenchmarkUdpTestPort"])); - } - set { - this["BenchmarkUdpTestPort"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("32")] - public int BenchmarkUdpSizeByteArray { - get { - return ((int)(this["BenchmarkUdpSizeByteArray"])); - } - set { - this["BenchmarkUdpSizeByteArray"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("1000")] - public int BenchmarkTestUdpMessageQty { - get { - return ((int)(this["BenchmarkTestUdpMessageQty"])); - } - set { - this["BenchmarkTestUdpMessageQty"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("1")] - public int BenchmarkTestUdpClientsQty { - get { - return ((int)(this["BenchmarkTestUdpClientsQty"])); - } - set { - this["BenchmarkTestUdpClientsQty"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("16000")] - public int BenchmarkTcpConnectStatePort { - get { - return ((int)(this["BenchmarkTcpConnectStatePort"])); - } - set { - this["BenchmarkTcpConnectStatePort"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("False")] - public bool BenchmarkAddEnvironmentParametersToResult { - get { - return ((bool)(this["BenchmarkAddEnvironmentParametersToResult"])); - } - set { - this["BenchmarkAddEnvironmentParametersToResult"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string SavedResultsNetworkTestsFolderPath { - get { - return ((string)(this["SavedResultsNetworkTestsFolderPath"])); - } - set { - this["SavedResultsNetworkTestsFolderPath"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("3")] - public int ReconnectQtyComunicateTcpClient { - get { - return ((int)(this["ReconnectQtyComunicateTcpClient"])); - } - set { - this["ReconnectQtyComunicateTcpClient"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("0")] - public int ReconnectQtyBenchmarkComunicateTcpClient { - get { - return ((int)(this["ReconnectQtyBenchmarkComunicateTcpClient"])); - } - set { - this["ReconnectQtyBenchmarkComunicateTcpClient"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("5")] - public int ReconnectTimeoutComunicateTcpClient { - get { - return ((int)(this["ReconnectTimeoutComunicateTcpClient"])); - } - set { - this["ReconnectTimeoutComunicateTcpClient"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("0")] - public int ReconnectTimeoutBenchmarkComunicateTcpClient { - get { - return ((int)(this["ReconnectTimeoutBenchmarkComunicateTcpClient"])); - } - set { - this["ReconnectTimeoutBenchmarkComunicateTcpClient"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool AutoStartTcpConnect { - get { - return ((bool)(this["AutoStartTcpConnect"])); - } - set { - this["AutoStartTcpConnect"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("False")] - public bool AutoStartTestTcpConnect { - get { - return ((bool)(this["AutoStartTestTcpConnect"])); - } - set { - this["AutoStartTestTcpConnect"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool IsMessageShowOnAbortMainConnection { - get { - return ((bool)(this["IsMessageShowOnAbortMainConnection"])); - } - set { - this["IsMessageShowOnAbortMainConnection"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("1")] - public double NotificationOpacity { - get { - return ((double)(this["NotificationOpacity"])); - } - set { - this["NotificationOpacity"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklyAdamThreeCategoryState { - get { - return ((bool)(this["BlocklyAdamThreeCategoryState"])); - } - set { - this["BlocklyAdamThreeCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("False")] - public bool BlocklyAdamTwoCategoryState { - get { - return ((bool)(this["BlocklyAdamTwoCategoryState"])); - } - set { - this["BlocklyAdamTwoCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyAdamThreeCategoryAlternateName { - get { - return ((string)(this["BlocklyAdamThreeCategoryAlternateName"])); - } - set { - this["BlocklyAdamThreeCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyAdamTwoCategoryAlternateName { - get { - return ((string)(this["BlocklyAdamTwoCategoryAlternateName"])); - } - set { - this["BlocklyAdamTwoCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool BlocklyAdamCommonCategoryState { - get { - return ((bool)(this["BlocklyAdamCommonCategoryState"])); - } - set { - this["BlocklyAdamCommonCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyAdamCommonCategoryAlternateName { - get { - return ((string)(this["BlocklyAdamCommonCategoryAlternateName"])); - } - set { - this["BlocklyAdamCommonCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("False")] - public bool BlocklyDateTimeCategoryState { - get { - return ((bool)(this["BlocklyDateTimeCategoryState"])); - } - set { - this["BlocklyDateTimeCategoryState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("")] - public string BlocklyDateTimeCategoryAlternateName { - get { - return ((string)(this["BlocklyDateTimeCategoryAlternateName"])); - } - set { - this["BlocklyDateTimeCategoryAlternateName"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("adam")] - public string ApiLogin { - get { - return ((string)(this["ApiLogin"])); - } - set { - this["ApiLogin"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("adam1234")] - public string ApiPassword { - get { - return ((string)(this["ApiPassword"])); - } - set { - this["ApiPassword"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("5147")] - public int ApiPort { - get { - return ((int)(this["ApiPort"])); - } - set { - this["ApiPort"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool CheckServerVersion { - get { - return ((bool)(this["CheckServerVersion"])); - } - set { - this["CheckServerVersion"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("7071")] - public int LogServerPort { - get { - return ((int)(this["LogServerPort"])); - } - set { - this["LogServerPort"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("False")] - public bool ChangeExtendedExecuteReportToggleSwitchState { - get { - return ((bool)(this["ChangeExtendedExecuteReportToggleSwitchState"])); - } - set { - this["ChangeExtendedExecuteReportToggleSwitchState"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("True")] - public bool DontShowBrowserMenuInBlockly { - get { - return ((bool)(this["DontShowBrowserMenuInBlockly"])); - } - set { - this["DontShowBrowserMenuInBlockly"] = value; - } - } - - [global::System.Configuration.UserScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.DefaultSettingValueAttribute("8000")] - public int SoketServerPort { - get { - return ((int)(this["SoketServerPort"])); - } - set { - this["SoketServerPort"] = value; - } - } - } -} diff --git a/AdamController/Properties/Settings.settings b/AdamController/Properties/Settings.settings deleted file mode 100644 index 6e6d614..0000000 --- a/AdamController/Properties/Settings.settings +++ /dev/null @@ -1,264 +0,0 @@ - - - - - - 18000 - - - 15005 - - - 192.168.50.10 - - - Light - - - Blue - - - 0 - - - False - - - 20 - - - 0 - - - - - - True - - - True - - - ru - - - ru - - - ru - - - True - - - True - - - True - - - True - - - True - - - True - - - False - - - True - - - - - - - - - - - - - - - - - - - - - - - - - - - Classic - - - False - - - False - - - False - - - False - - - 854 - - - 512 - - - True - - - - - - - - - - - - - - - - - - True - - - True - - - 15000 - - - 32 - - - 192.168.50.10 - - - 15000 - - - 1 - - - 1000 - - - 10 - - - 10 - - - 16001 - - - 16002 - - - 32 - - - 1000 - - - 1 - - - 16000 - - - False - - - - - - 3 - - - 0 - - - 5 - - - 0 - - - True - - - False - - - True - - - 1 - - - True - - - False - - - - - - - - - True - - - - - - False - - - - - - adam - - - adam1234 - - - 5147 - - - True - - - 7071 - - - False - - - True - - - 8000 - - - \ No newline at end of file From 3cbebf3127e525ee1acba1cf6754be1710defc9a Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 24 Mar 2024 18:47:07 +1000 Subject: [PATCH 060/181] Clean --- AdamController.Core/Mvvm/RegionViewModelBase.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/AdamController.Core/Mvvm/RegionViewModelBase.cs b/AdamController.Core/Mvvm/RegionViewModelBase.cs index 74f9d02..d20d508 100644 --- a/AdamController.Core/Mvvm/RegionViewModelBase.cs +++ b/AdamController.Core/Mvvm/RegionViewModelBase.cs @@ -1,5 +1,4 @@ -using AdamController.Services.Interfaces; -using Prism.Regions; +using Prism.Regions; using Prism.Services.Dialogs; using System; @@ -37,8 +36,6 @@ public virtual void ConfirmNavigationRequest(NavigationContext navigationContext public virtual bool IsNavigationTarget(NavigationContext navigationContext) { - - return true; } From 4de8d1809cdb5eb8e969f77f1122eddb989ebc6a Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 25 Mar 2024 22:30:49 +1000 Subject: [PATCH 061/181] Fix path to main app icon --- AdamController/AdamController.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/AdamController/AdamController.csproj b/AdamController/AdamController.csproj index 46e2905..eb92cc0 100644 --- a/AdamController/AdamController.csproj +++ b/AdamController/AdamController.csproj @@ -20,6 +20,7 @@ AdamController.App + ..\AdamController.Core\Properties\Icons\main_app_icon.ico 1701;1702;CA1416 From 03d3cf31643f0c44219200446d7dcbefd9d725d0 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Thu, 28 Mar 2024 16:40:56 +1000 Subject: [PATCH 062/181] Experimental fix #11 --- AdamController.Core/FlayoutsRegionNames.cs | 3 +- AdamController.Core/RegionNames.cs | 4 +- .../FlayoutsRegionChangeOpenedAwareService.cs | 42 +++++++++++++++++++ ...IFlayoutsRegionChangeOpenedAwareService.cs | 11 +++++ AdamController/App.xaml.cs | 5 +++ .../ViewModels/MainWindowViewModel.cs | 5 ++- AdamController/Views/MainWindow.xaml | 3 +- .../ContentRegionModule.cs | 1 - .../VisualSettingsControlViewModel.cs | 24 +++++++++-- .../FlayoutsRegionModule.cs | 8 ++-- .../AdvancedBlocklySettingsViewModel.cs | 36 ++++++++++++++-- .../ViewModels/FlayoutsViewModel.cs | 2 +- .../ViewModels/NotificationViewModel.cs | 19 +++++++++ .../Views/AdvancedBlocklySettingsView.xaml | 27 ++++++------ .../Views/FlayoutsView.xaml | 10 ++--- .../Views/NotificationView.xaml.cs | 18 +------- 16 files changed, 163 insertions(+), 55 deletions(-) create mode 100644 AdamController.Services/FlayoutsRegionChangeOpenedAwareService.cs create mode 100644 AdamController.Services/Interfaces/IFlayoutsRegionChangeOpenedAwareService.cs diff --git a/AdamController.Core/FlayoutsRegionNames.cs b/AdamController.Core/FlayoutsRegionNames.cs index 56b5a43..0c1892e 100644 --- a/AdamController.Core/FlayoutsRegionNames.cs +++ b/AdamController.Core/FlayoutsRegionNames.cs @@ -2,8 +2,7 @@ { public class FlayoutsRegionNames { - public const string FlayoutsRegion = $"{nameof(FlayoutsRegion)}"; - + public const string FlayoutsInsideRegion = $"{nameof(FlayoutsInsideRegion)}"; public const string FlayotAdvancedBlocklySettings = $"{nameof(FlayotAdvancedBlocklySettings)}"; public const string FlayoutNotification = $"{nameof(FlayoutNotification)}"; } diff --git a/AdamController.Core/RegionNames.cs b/AdamController.Core/RegionNames.cs index 53f7c87..f64b2e8 100644 --- a/AdamController.Core/RegionNames.cs +++ b/AdamController.Core/RegionNames.cs @@ -2,9 +2,9 @@ { public class RegionNames { - public const string HamburgerMenuRegion = $"{nameof(HamburgerMenuRegion)}"; - public const string ContentRegion = $"{nameof(ContentRegion)}"; public const string MenuRegion = $"{nameof(MenuRegion)}"; + public const string ContentRegion = $"{nameof(ContentRegion)}"; + public const string FlayoutsRegion = $"{nameof(FlayoutsRegion)}"; public const string StatusBarRegion = $"{nameof(StatusBarRegion)}"; } } diff --git a/AdamController.Services/FlayoutsRegionChangeOpenedAwareService.cs b/AdamController.Services/FlayoutsRegionChangeOpenedAwareService.cs new file mode 100644 index 0000000..4290b73 --- /dev/null +++ b/AdamController.Services/FlayoutsRegionChangeOpenedAwareService.cs @@ -0,0 +1,42 @@ +using AdamController.Services.Interfaces; + +namespace AdamController.Services +{ + public class FlayoutsRegionChangeOpenedAwareService : IFlayoutsRegionChangeOpenedAwareService + { + public event AdvancedBlocklySettingsIsOpenChangeEventHandler RaiseAdvancedBlocklySettingsIsOpenChange; + + + private bool mAdvancedBlocklySettingsIsOpen; + public bool AdvancedBlocklySettingsIsOpen + { + get { return mAdvancedBlocklySettingsIsOpen; } + set + { + mAdvancedBlocklySettingsIsOpen = value; + OnRaiseAdvancedBlocklySettingsIsOpenChange(); + } + } + + private bool mNotificationFlayoutsIsOpen; + + public bool NotificationFlayoutsIsOpen + { + get { return mNotificationFlayoutsIsOpen; } + set + { + mNotificationFlayoutsIsOpen = value; + } + } + + + protected virtual void OnRaiseAdvancedBlocklySettingsIsOpenChange() + { + AdvancedBlocklySettingsIsOpenChangeEventHandler raiseEvent = RaiseAdvancedBlocklySettingsIsOpenChange; + raiseEvent?.Invoke(this); + + } + + + } +} diff --git a/AdamController.Services/Interfaces/IFlayoutsRegionChangeOpenedAwareService.cs b/AdamController.Services/Interfaces/IFlayoutsRegionChangeOpenedAwareService.cs new file mode 100644 index 0000000..a304373 --- /dev/null +++ b/AdamController.Services/Interfaces/IFlayoutsRegionChangeOpenedAwareService.cs @@ -0,0 +1,11 @@ +namespace AdamController.Services.Interfaces +{ + public delegate void AdvancedBlocklySettingsIsOpenChangeEventHandler(object sender); + + public interface IFlayoutsRegionChangeOpenedAwareService + { + public event AdvancedBlocklySettingsIsOpenChangeEventHandler RaiseAdvancedBlocklySettingsIsOpenChange; + public bool AdvancedBlocklySettingsIsOpen { get; set; } + public bool NotificationFlayoutsIsOpen { get; set; } + } +} diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index db0c274..be1d856 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -77,6 +77,11 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return new SubRegionChangeAwareService(); }); + containerRegistry.RegisterSingleton(containerRegistry => + { + return new FlayoutsRegionChangeOpenedAwareService(); + }); + //here must be ip/port containerRegistry.Register(); diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index 4fd725e..8712b2c 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -21,15 +21,18 @@ public class MainWindowViewModel : BindableBase public IRegionManager RegionManager { get; } private ISubRegionChangeAwareService SubRegionChangeAwareService { get; } + private IFlayoutsRegionChangeOpenedAwareService FlayoutsRegionChangeOpenedAwareService { get; } + #endregion #region ~ - public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService) + public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService, IFlayoutsRegionChangeOpenedAwareService flayoutsRegionChangeOpenedAwareService) { RegionManager = regionManager; ShowRegionCommand = new DelegateCommand(ShowRegion); SubRegionChangeAwareService = subRegionChangeAwareService; + FlayoutsRegionChangeOpenedAwareService = flayoutsRegionChangeOpenedAwareService; SubRegionChangeAwareService.RaiseSubRegionChangeEvent += RaiseSubRegionChangeEvent; Application.Current.MainWindow.Loaded += MainWindowLoaded; diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index 3918817..775baa6 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -71,7 +71,8 @@ - + diff --git a/Modules/AdamController.Modules.ContentRegion/ContentRegionModule.cs b/Modules/AdamController.Modules.ContentRegion/ContentRegionModule.cs index c8f34e0..6b6e0a0 100644 --- a/Modules/AdamController.Modules.ContentRegion/ContentRegionModule.cs +++ b/Modules/AdamController.Modules.ContentRegion/ContentRegionModule.cs @@ -22,7 +22,6 @@ public void OnInitialized(IContainerProvider containerProvider) public void RegisterTypes(IContainerRegistry containerRegistry) { - //containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(nameof(ContentRegionView)); containerRegistry.RegisterForNavigation(nameof(ScratchControlView)); diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index 42d4a77..66c08d3 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -3,6 +3,7 @@ using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Core.Properties; +using AdamController.Services.Interfaces; using ControlzEx.Theming; using Prism.Commands; using Prism.Regions; @@ -16,11 +17,24 @@ namespace AdamController.Modules.ContentRegion.ViewModels { public class VisualSettingsControlViewModel : RegionViewModelBase { - public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) + #region Service + + private IFlayoutsRegionChangeOpenedAwareService FayoutsRegionChangeOpenedService { get; } + + #endregion + + #region ~ + + public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogService dialogService, IFlayoutsRegionChangeOpenedAwareService flayoutsRegionChangeOpenedAwareService) : base(regionManager, dialogService) { - + FayoutsRegionChangeOpenedService = flayoutsRegionChangeOpenedAwareService; } + #endregion + + + + #region Navigation public override void OnNavigatedFrom(NavigationContext navigationContext) @@ -37,6 +51,7 @@ public override void OnNavigatedTo(NavigationContext navigationContext) public static ObservableCollection BlocklyThemes { get; private set; } = ThemesCollection.BlocklyThemes; + #region LanguageSettings #region AppLanguage @@ -165,7 +180,8 @@ public double NotificationOpacity private DelegateCommand openAdvancedBlocklySettingsCommand; public DelegateCommand OpenAdvancedBlocklySettingsCommand => openAdvancedBlocklySettingsCommand ??= new DelegateCommand(() => { - OpenAdvancedBlocklySettings(true); + FayoutsRegionChangeOpenedService.AdvancedBlocklySettingsIsOpen = true; + ///OpenAdvancedBlocklySettings(true); }); private DelegateCommand changeBaseColorTheme; @@ -198,7 +214,7 @@ public double NotificationOpacity public static Action ChangeNotificationOpacity { get; set; } public static Action ChangeBaseTheme { get; set; } public static Action ChangeThemeColorScheme { get; set; } - public static Action OpenAdvancedBlocklySettings { get; set; } + //public static Action OpenAdvancedBlocklySettings { get; set; } public static Action SetToolboxLanguage { get; set; } public static Action SetBlocklyThemeAndGridColor { get; set; } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs b/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs index fb89854..a16dbf3 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs @@ -17,15 +17,15 @@ public FlayoutsRegionModule(IRegionManager regionManager) public void OnInitialized(IContainerProvider containerProvider) { - mRegionManager.RequestNavigate(FlayoutsRegionNames.FlayoutsRegion, nameof(FlayoutsView)); + mRegionManager.RequestNavigate(RegionNames.FlayoutsRegion, nameof(FlayoutsView)); } public void RegisterTypes(IContainerRegistry containerRegistry) { - containerRegistry.RegisterForNavigation(); + containerRegistry.RegisterForNavigation(nameof(FlayoutsView)); - containerRegistry.RegisterForNavigation(); - containerRegistry.RegisterForNavigation(); + containerRegistry.RegisterForNavigation(nameof(NotificationView)); + containerRegistry.RegisterForNavigation(nameof(AdvancedBlocklySettingsView)); } } } \ No newline at end of file diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs index 3939be9..7788ea9 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs @@ -3,6 +3,7 @@ using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Core.Properties; +using AdamController.Services.Interfaces; using Prism.Commands; using Prism.Regions; using Prism.Services.Dialogs; @@ -14,13 +15,30 @@ namespace AdamController.Modules.FlayoutsRegion.ViewModels.Flayouts { public class AdvancedBlocklySettingsViewModel : RegionViewModelBase { - public AdvancedBlocklySettingsViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) + private IFlayoutsRegionChangeOpenedAwareService FlayoutsRegionChangeOpenedService { get; } + + public AdvancedBlocklySettingsViewModel(IRegionManager regionManager, IDialogService dialogService, IFlayoutsRegionChangeOpenedAwareService flayoutsRegionChangeOpenedAwareService ) : base(regionManager, dialogService) { + FlayoutsRegionChangeOpenedService = flayoutsRegionChangeOpenedAwareService; + + FlayoutsRegionChangeOpenedService.RaiseAdvancedBlocklySettingsIsOpenChange += RaiseAdvancedBlocklySettingsIsOpenChange; } - + #region Navigation + + public override void OnNavigatedFrom(NavigationContext navigationContext) + { + FlayoutsRegionChangeOpenedService.RaiseAdvancedBlocklySettingsIsOpenChange -= RaiseAdvancedBlocklySettingsIsOpenChange; + } - #region Open BlocklySettingsFlayots + public override void OnNavigatedTo(NavigationContext navigationContext) + { + + } + + #endregion + + #region Fields private bool advancedBlocklySettingsFlayoutsIsOpen; public bool AdvancedBlocklySettingsFlayoutsIsOpen @@ -28,7 +46,8 @@ public bool AdvancedBlocklySettingsFlayoutsIsOpen get { return advancedBlocklySettingsFlayoutsIsOpen; } set { - if (value == advancedBlocklySettingsFlayoutsIsOpen) return; + if (value == advancedBlocklySettingsFlayoutsIsOpen) + return; advancedBlocklySettingsFlayoutsIsOpen = value; SetProperty(ref advancedBlocklySettingsFlayoutsIsOpen, value); @@ -37,6 +56,15 @@ public bool AdvancedBlocklySettingsFlayoutsIsOpen #endregion + #region Raise events + + private void RaiseAdvancedBlocklySettingsIsOpenChange(object sender) + { + AdvancedBlocklySettingsFlayoutsIsOpen = FlayoutsRegionChangeOpenedService.AdvancedBlocklySettingsIsOpen; + } + + #endregion + #region BlocklyGridColour settings diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs index 94f1d26..c870cae 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs @@ -1,5 +1,4 @@ using AdamController.Core.Mvvm; -using AdamController.Services.Interfaces; using Prism.Regions; using Prism.Services.Dialogs; @@ -9,6 +8,7 @@ public class FlayoutsViewModel : RegionViewModelBase { public FlayoutsViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) { + } } } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index b08b8bc..3037e79 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -26,6 +26,25 @@ public NotificationViewModel(IRegionManager regionManager, IDialogService dialog { } + #region Fields + + private bool mNotificationFlayoutsIsOpen; + public bool NotificationFlayoutsIsOpen + { + get { return mNotificationFlayoutsIsOpen; } + set + { + if (mNotificationFlayoutsIsOpen == value) + return; + + mNotificationFlayoutsIsOpen = value; + + SetProperty(ref mNotificationFlayoutsIsOpen, value); + } + } + + #endregion + #region NotificationMessage Visiblity private Visibility noNewNotificationMessageVisibility = Visibility.Visible; diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/AdvancedBlocklySettingsView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/AdvancedBlocklySettingsView.xaml index fb80170..28b219a 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/AdvancedBlocklySettingsView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/AdvancedBlocklySettingsView.xaml @@ -12,18 +12,21 @@ - - + + + diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml index 3b97259..a9b9f55 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml @@ -1,12 +1,10 @@  + xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" + xmlns:prism="http://prismlibrary.com/" + prism:ViewModelLocator.AutoWireViewModel="True"> - + diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml.cs b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml.cs index bd4261f..ec9c626 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml.cs @@ -1,23 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Navigation; -using System.Windows.Shapes; +using System.Windows.Controls; namespace AdamController.Modules.FlayoutsRegion.Views { - /// - /// Логика взаимодействия для NotificationView.xaml - /// public partial class NotificationView : UserControl { public NotificationView() From 7f608921336b093961e49dd0ffa6f4fd5856cec4 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 30 Mar 2024 13:32:33 +1000 Subject: [PATCH 063/181] Moved all nuget package to interface project. Change platform for interface project --- .../AdamController.Core.csproj | 15 ---------- .../AdamController.Services.csproj | 15 +++++++++- AdamController/Views/MainWindow.xaml | 18 +++++++---- .../ViewModels/ContentRegionViewModel.cs | 1 - .../VisualSettingsControlViewModel.cs | 4 +-- .../Views/ContentRegionView.xaml | 3 +- .../FlayoutsRegionModule.cs | 1 + .../AdvancedBlocklySettingsViewModel.cs | 18 +++++++---- .../ViewModels/FlayoutsViewModel.cs | 30 ++++++++++++++++++- .../ViewModels/NotificationViewModel.cs | 2 +- .../Views/FlayoutsView.xaml | 6 ++-- .../Views/FlayoutsView.xaml.cs | 18 +---------- 12 files changed, 76 insertions(+), 55 deletions(-) diff --git a/AdamController.Core/AdamController.Core.csproj b/AdamController.Core/AdamController.Core.csproj index 9744ef3..d5a3bcb 100644 --- a/AdamController.Core/AdamController.Core.csproj +++ b/AdamController.Core/AdamController.Core.csproj @@ -19,21 +19,6 @@ Always - - - - - - - - - - - - - - - diff --git a/AdamController.Services/AdamController.Services.csproj b/AdamController.Services/AdamController.Services.csproj index 40fb4e5..6cf31c4 100644 --- a/AdamController.Services/AdamController.Services.csproj +++ b/AdamController.Services/AdamController.Services.csproj @@ -1,11 +1,24 @@  - net7.0 + net7.0-windows + + + + + + + + + + + + + diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index 775baa6..c94ea44 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -69,13 +69,17 @@ + - + + + + + - + @@ -139,6 +143,8 @@ + + - @@ -194,7 +199,8 @@ - + + diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs index 3e7296d..312478d 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs @@ -32,7 +32,6 @@ public override void ConfirmNavigationRequest(NavigationContext navigationContex } } - private void SubRegionsRequestNavigate(string uri, NavigationParameters parameters) { if (string.IsNullOrEmpty(uri)) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index 66c08d3..254975c 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -1,4 +1,5 @@ using AdamBlocklyLibrary.Enum; +using AdamController.Core; using AdamController.Core.DataSource; using AdamController.Core.Model; using AdamController.Core.Mvvm; @@ -180,8 +181,7 @@ public double NotificationOpacity private DelegateCommand openAdvancedBlocklySettingsCommand; public DelegateCommand OpenAdvancedBlocklySettingsCommand => openAdvancedBlocklySettingsCommand ??= new DelegateCommand(() => { - FayoutsRegionChangeOpenedService.AdvancedBlocklySettingsIsOpen = true; - ///OpenAdvancedBlocklySettings(true); + RegionManager.RequestNavigate(RegionNames.FlayoutsRegion, FlayoutsRegionNames.FlayotAdvancedBlocklySettings); }); private DelegateCommand changeBaseColorTheme; diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml index e0659d3..30d1a94 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ContentRegionView.xaml @@ -3,9 +3,8 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" xmlns:prism="http://prismlibrary.com/" - xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" prism:ViewModelLocator.AutoWireViewModel="True"> - + diff --git a/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs b/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs index a16dbf3..51fbd34 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs @@ -22,6 +22,7 @@ public void OnInitialized(IContainerProvider containerProvider) public void RegisterTypes(IContainerRegistry containerRegistry) { + containerRegistry.RegisterForNavigation(nameof(FlayoutsView)); containerRegistry.RegisterForNavigation(nameof(NotificationView)); diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs index 7788ea9..0a1dd2a 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs @@ -11,7 +11,7 @@ using System.Linq; using System.Windows.Media; -namespace AdamController.Modules.FlayoutsRegion.ViewModels.Flayouts +namespace AdamController.Modules.FlayoutsRegion.ViewModels { public class AdvancedBlocklySettingsViewModel : RegionViewModelBase { @@ -21,19 +21,22 @@ public AdvancedBlocklySettingsViewModel(IRegionManager regionManager, IDialogSer { FlayoutsRegionChangeOpenedService = flayoutsRegionChangeOpenedAwareService; - FlayoutsRegionChangeOpenedService.RaiseAdvancedBlocklySettingsIsOpenChange += RaiseAdvancedBlocklySettingsIsOpenChange; + } #region Navigation public override void OnNavigatedFrom(NavigationContext navigationContext) { - FlayoutsRegionChangeOpenedService.RaiseAdvancedBlocklySettingsIsOpenChange -= RaiseAdvancedBlocklySettingsIsOpenChange; + AdvancedBlocklySettingsFlayoutsIsOpen = false; + //FlayoutsRegionChangeOpenedService.RaiseAdvancedBlocklySettingsIsOpenChange -= RaiseAdvancedBlocklySettingsIsOpenChange; } public override void OnNavigatedTo(NavigationContext navigationContext) { - + AdvancedBlocklySettingsFlayoutsIsOpen = true; + //FlayoutsRegionChangeOpenedService.RaiseAdvancedBlocklySettingsIsOpenChange += RaiseAdvancedBlocklySettingsIsOpenChange; + } #endregion @@ -60,11 +63,11 @@ public bool AdvancedBlocklySettingsFlayoutsIsOpen private void RaiseAdvancedBlocklySettingsIsOpenChange(object sender) { - AdvancedBlocklySettingsFlayoutsIsOpen = FlayoutsRegionChangeOpenedService.AdvancedBlocklySettingsIsOpen; + //AdvancedBlocklySettingsFlayoutsIsOpen = FlayoutsRegionChangeOpenedService.AdvancedBlocklySettingsIsOpen; } #endregion - +/* #region BlocklyGridColour settings @@ -226,5 +229,8 @@ private void SelectGridColorDependingSelectedTheme(BlocklyTheme theme) #endregion + */ } + + } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs index c870cae..ed34a49 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs @@ -1,6 +1,9 @@ -using AdamController.Core.Mvvm; +using AdamController.Core; +using AdamController.Core.Mvvm; +using AdamController.Modules.FlayoutsRegion.Views; using Prism.Regions; using Prism.Services.Dialogs; +using System; namespace AdamController.Modules.FlayoutsRegion.ViewModels { @@ -8,7 +11,32 @@ public class FlayoutsViewModel : RegionViewModelBase { public FlayoutsViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) { + + } + + public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) + { + SubFlayoutsRequestNavigate(FlayoutsRegionNames.FlayotAdvancedBlocklySettings, navigationContext.Parameters); + } + + public override void OnNavigatedTo(NavigationContext navigationContext) + { } + + private void SubFlayoutsRequestNavigate(string uri, NavigationParameters parameters) + { + if (string.IsNullOrEmpty(uri)) + return; + + + switch (uri) + { + case FlayoutsRegionNames.FlayotAdvancedBlocklySettings: + RegionManager.RequestNavigate(FlayoutsRegionNames.FlayoutsInsideRegion, nameof(AdvancedBlocklySettingsView), parameters); + break; + + } + } } } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index 3037e79..b5a8c24 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -9,7 +9,7 @@ using System.Windows; using System.Windows.Threading; -namespace AdamController.Modules.FlayoutsRegion.ViewModels.Flayouts +namespace AdamController.Modules.FlayoutsRegion.ViewModels { public class NotificationViewModel : RegionViewModelBase { diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml index a9b9f55..4b7b0ef 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml @@ -4,7 +4,7 @@ xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True"> - - - + + + diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml.cs b/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml.cs index e0892a9..6fa4465 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml.cs @@ -1,23 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Navigation; -using System.Windows.Shapes; +using System.Windows.Controls; namespace AdamController.Modules.FlayoutsRegion.Views { - /// - /// Логика взаимодействия для FlayoutsView.xaml - /// public partial class FlayoutsView : UserControl { public FlayoutsView() From 47918f429de34fbd98d04aa467d035910e78d8a7 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 31 Mar 2024 11:42:11 +1000 Subject: [PATCH 064/181] Fix: build problems --- .../AdamController.Services.csproj | 1 + .../FlayoutBase.cs | 228 ++++++++++++++++++ .../FlyoutAction.cs | 48 ++++ .../FlyoutEventArgs.cs | 14 ++ .../FlyoutManager.cs | 16 ++ .../FlyoutParameters.cs | 36 +++ AdamController.Services/Interfaces/IFlyout.cs | 49 ++++ .../Interfaces/IFlyoutManager.cs | 41 ++++ 8 files changed, 433 insertions(+) create mode 100644 AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlayoutBase.cs create mode 100644 AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutAction.cs create mode 100644 AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutEventArgs.cs create mode 100644 AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs create mode 100644 AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutParameters.cs create mode 100644 AdamController.Services/Interfaces/IFlyout.cs create mode 100644 AdamController.Services/Interfaces/IFlyoutManager.cs diff --git a/AdamController.Services/AdamController.Services.csproj b/AdamController.Services/AdamController.Services.csproj index 6cf31c4..d2bfe25 100644 --- a/AdamController.Services/AdamController.Services.csproj +++ b/AdamController.Services/AdamController.Services.csproj @@ -15,6 +15,7 @@ + diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlayoutBase.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlayoutBase.cs new file mode 100644 index 0000000..de1629f --- /dev/null +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlayoutBase.cs @@ -0,0 +1,228 @@ +using AdamController.Services.Interfaces; +using Prism.Mvvm; +using System; +using System.Windows.Input; + +namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +{ + /// + /// Base class that provides and implementation of IFlyout. + /// Inherits from BindableBase to allow property binding. + /// Recommended to perform the majority of ViewModel initialization within an override of OnOpening to prevent memory leaks, + /// and clean up as many resources as possible within OnClosing as the instance of the ViewModel will remain in memory from the + /// moment of registration with the FlyoutManager until the moment of unregistration, or program exit. + /// + public abstract class FlayoutBase: BindableBase, IFlyout + { + public event EventHandler OnClosed; + public event EventHandler OnOpened; + public event EventHandler OnOpenChanged; + private bool isOpen; + private string position; + private string header; + private string theme; + private bool isModal = false; + private bool areAnimationsEnabled = true; + private bool animateOpacity; + private ICommand closeCommand; + private MouseButton externalCloseButton; + private bool closeButtonIsCancel; + private bool isPinned; + + /// + /// Bindable property to determine open/closed staus of flyout, based on private field isOpen. + /// Generally set by FlyoutManager calling Open or Close method. + /// Initial value can be set by concrete child class. + /// + public bool IsOpen + { + get { return isOpen; } + set + { + OnChanging(value); + SetProperty(ref isOpen, value); + + } + } + + + /// + /// Bindable property to determine position of flyout in window. + /// Possible values are stored in FlyoutPosition class and can be used to set property in the concrete class. + /// + public string Position + { + get { return position; } + set { SetProperty(ref position, value); } + } + + /// + /// Bindable property to determine theme of flyout. + /// Possible values are stored in FlyoutTheme class and can be used to set property in concrete class. + /// + public string Theme + { + get { return theme; } + set { SetProperty(ref theme, value); } + } + + /// + /// Bindable property to determine whether the Flyout is modal or not + /// + public bool IsModal + { + get { return isModal; } + set { SetProperty(ref isModal, value); } + } + + /// + /// Bindable property to determine whether flyout animations are enabled + /// + public bool AreAnimationsEnabled + { + get { return areAnimationsEnabled; } + set { SetProperty(ref areAnimationsEnabled, value); } + } + + /// + /// Command to execute when the close button is pressed + /// + public ICommand CloseCommand + { + get { return closeCommand; } + set { SetProperty(ref closeCommand, value); } + } + + /// + /// Designate a mousebutton that will close the flyout when pressed outside of its bounds. + /// + public MouseButton ExternalCloseButton + { + get { return externalCloseButton; } + set { SetProperty(ref externalCloseButton, value); } + } + + /// + /// Does the close button act as a cancel button. + /// + public bool CloseButtonIsCancel + { + get { return closeButtonIsCancel; } + set { SetProperty(ref closeButtonIsCancel, value); } + } + + /// + /// Is the flyout pinned. + /// + public bool IsPinned + { + get { return isPinned; } + set { SetProperty(ref isPinned, value); } + } + + /// + /// Whether the flyout is currently able to open. + /// Default: returns true + /// Override in concrete child class to implement custom logic. + /// + /// Instance of containing information on current Open request. + /// True if flyout can open, false if not. + public virtual bool CanOpen(FlyoutParameters flyoutParameters) + { + return true; + } + + + /// + /// Is opacity animated. + /// + public bool AnimateOpacity + { + get { return animateOpacity; } + set { SetProperty(ref animateOpacity, value); } + } + + /// + /// Whether the flyout is currently able to close. + /// Default: returns true. + /// Override in concrete child class to implement custom logic. + /// + /// Instance of containing information on current Close request. + /// True if flyout can close, false if not. + public virtual bool CanClose(FlyoutParameters flyoutParameters) + { + return true; + } + + /// + /// Event delegate called on flyout closing with FlyoutEventArgs. + /// + /// Instance of containing information on current Close request. + protected virtual void OnClosing(FlyoutParameters flyoutParameters) { } + + /// + /// Event delegate called on flyout closing, with FlyoutEventArgs. + /// + /// Instance of containing information on current Close request. + protected virtual void OnOpening(FlyoutParameters flyoutParameters) { } + + /// + /// Bindable property to determine header of flyout. + /// Value set by concrete child class. + /// + public string Header + { + get { return header; } + set { SetProperty(ref header, value); } + } + + /// + /// Event delegate called on flyout open status changed, with FlyoutEventArgs containing open/close direction. + /// + /// + protected virtual void OnChanging(bool isOpening) + { + var flyoutAction = isOpening ? FlyoutAction.Opening : FlyoutAction.Closing; + var flyoutEventArgs = new FlyoutEventArgs(flyoutAction); + if (OnOpenChanged != null) + OnOpenChanged(this, flyoutEventArgs); + if (flyoutAction == FlyoutAction.Opening) + if (OnOpened != null) + OnOpened(this, flyoutEventArgs); + if (flyoutAction == FlyoutAction.Closing) + if (OnClosed != null) + OnClosed(this, flyoutEventArgs); + } + + /// + /// Close the flyout. + /// + /// + public void Close(FlyoutParameters flyoutParameters) + { + OnClosing(flyoutParameters); + IsOpen = false; + } + + public void Close() + { + Close(new FlyoutParameters()); + } + + + /// + /// Open the flyout. + /// + /// + public void Open(FlyoutParameters flyoutParameters) + { + OnOpening(flyoutParameters); + IsOpen = true; + } + + public void Open() + { + Open(new FlyoutParameters()); + } + } +} diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutAction.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutAction.cs new file mode 100644 index 0000000..6152747 --- /dev/null +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutAction.cs @@ -0,0 +1,48 @@ +namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +{ + public class FlyoutAction + { + private const string mOpening = "Opening"; + private const string mClosing = "Closing"; + + private readonly string mThisAction; + + protected FlyoutAction(string action) + { + mThisAction = action; + } + + public static FlyoutAction Opening + { + get { return new FlyoutAction(mOpening); } + } + + public static FlyoutAction Closing + { + get { return new FlyoutAction(mClosing); } + } + + public string Action + { + get { return mThisAction; } + } + + public override bool Equals(object obj) + { + if (obj is not FlyoutAction other) + return false; + + return this.Action == other.Action; + } + + public override int GetHashCode() + { + return mThisAction.GetHashCode(); + } + + public override string ToString() + { + return mThisAction; + } + } +} diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutEventArgs.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutEventArgs.cs new file mode 100644 index 0000000..edba008 --- /dev/null +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutEventArgs.cs @@ -0,0 +1,14 @@ +using System; + +namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +{ + public class FlyoutEventArgs : EventArgs + { + public FlyoutAction FlyoutAction { get; set; } + + public FlyoutEventArgs(FlyoutAction flyoutAction) + { + FlyoutAction = flyoutAction; + } + } +} diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs new file mode 100644 index 0000000..b95b06c --- /dev/null +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs @@ -0,0 +1,16 @@ +using AdamController.Services.Interfaces; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +{ + public class FlyoutManager //: IFlyoutManager + { + IDictionary flyouts; + + DryIoc.Container + } +} diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutParameters.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutParameters.cs new file mode 100644 index 0000000..0b6b672 --- /dev/null +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutParameters.cs @@ -0,0 +1,36 @@ +using System.Collections; +using System.Collections.Generic; + +namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +{ + public class FlyoutParameters : IEnumerable + { + IDictionary parameters; + + public FlyoutParameters() + { + parameters = new Dictionary(); + } + + public void AddParameter(string name, object payload) + { + parameters.Add(name, payload); + } + + public object this[string key] + { + get { return parameters[key]; } + set { parameters[key] = value; } + } + + public bool ContainsKey(string key) + { + return parameters.ContainsKey(key); + } + + public IEnumerator GetEnumerator() + { + return parameters.GetEnumerator(); + } + } +} diff --git a/AdamController.Services/Interfaces/IFlyout.cs b/AdamController.Services/Interfaces/IFlyout.cs new file mode 100644 index 0000000..90bcdb9 --- /dev/null +++ b/AdamController.Services/Interfaces/IFlyout.cs @@ -0,0 +1,49 @@ +using System.Windows.Input; +using System; +using AdamController.Services.FlayoutsRegionEventAwareServiceDependency; + +namespace AdamController.Services.Interfaces +{ + + public interface IFlyout + { + + public event EventHandler OnClosed; + + public event EventHandler OnOpened; + + public event EventHandler OnOpenChanged; + + public string Position { get; set; } + + public string Header { get; set; } + + public string Theme { get; set; } + + public bool IsModal { get; set; } + + public bool AreAnimationsEnabled { get; set; } + + public bool AnimateOpacity { get; set; } + + public ICommand CloseCommand { get; set; } + + public MouseButton ExternalCloseButton { get; set; } + + public bool CloseButtonIsCancel { get; set; } + + public bool IsPinned { get; set; } + + public bool CanClose(FlyoutParameters flyoutParameters); + + public void Close(FlyoutParameters flyoutParameters); + + public void Close(); + + public bool CanOpen(FlyoutParameters flyoutParameters); + + public void Open(FlyoutParameters flyoutParameters); + + public void Open(); + } +} diff --git a/AdamController.Services/Interfaces/IFlyoutManager.cs b/AdamController.Services/Interfaces/IFlyoutManager.cs new file mode 100644 index 0000000..b9a7f1c --- /dev/null +++ b/AdamController.Services/Interfaces/IFlyoutManager.cs @@ -0,0 +1,41 @@ +using AdamController.Services.FlayoutsRegionEventAwareServiceDependency; +using Prism.Regions; +using System.Windows; + +namespace AdamController.Services.Interfaces +{ + public interface IFlyoutManager + { + public IRegionManager RegionManager { get; set; } + + public void SetDefaultFlyoutRegion(string regionName); + + public void RegisterFlyoutWithDefaultRegion(string flyoutKey) where TView : FrameworkElement; + + public void RegisterFlyoutWithDefaultRegion(string flyoutKey, IFlyout viewModel) where TView : FrameworkElement; + + public void RegisterFlyout(string flyoutKey, string regionName) where T : FrameworkElement; + + public void RegisterFlyout(string flyoutKey, string regionName, IFlyout flyoutViewModel) where T : FrameworkElement; + + public void UnRegisterFlyout(string key); + + public void UnRegisterFlyout(IFlyout flyout); + + public bool OpenFlyout(string key); + + public bool OpenFlyout(string key, FlyoutParameters flyoutParameters); + + public bool OpenFlyout(string key, bool forceOpen); + + public bool OpenFlyout(string key, FlyoutParameters flyoutParameters, bool forceOpen); + + public bool CloseFlyout(string key); + + public bool CloseFlyout(string key, FlyoutParameters flyoutParameters); + + public bool CloseFlyout(string key, bool forceClose); + + public bool CloseFlyout(string key, FlyoutParameters flyoutParameters, bool forceClose); + } +} From 28d200206d70e817a69b978c73027157b53a4f4e Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 31 Mar 2024 14:10:12 +1000 Subject: [PATCH 065/181] Added: flayouts services --- .../AdamController.Services.csproj | 13 + .../CustomUserControl/FlyoutContainer.xaml | 22 ++ .../CustomUserControl/FlyoutContainer.xaml.cs | 12 + .../{FlayoutBase.cs => FlyoutBase.cs} | 2 +- .../FlyoutManager.cs | 238 +++++++++++++++++- .../FlyoutsControlRegionAdapter.cs | 41 +++ 6 files changed, 322 insertions(+), 6 deletions(-) create mode 100644 AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml create mode 100644 AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml.cs rename AdamController.Services/FlayoutsRegionEventAwareServiceDependency/{FlayoutBase.cs => FlyoutBase.cs} (99%) create mode 100644 AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutsControlRegionAdapter.cs diff --git a/AdamController.Services/AdamController.Services.csproj b/AdamController.Services/AdamController.Services.csproj index d2bfe25..1c0fd98 100644 --- a/AdamController.Services/AdamController.Services.csproj +++ b/AdamController.Services/AdamController.Services.csproj @@ -4,8 +4,13 @@ net7.0-windows + + + + + @@ -15,6 +20,7 @@ + @@ -23,4 +29,11 @@ + + + Designer + MSBuild:Compile + + + diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml new file mode 100644 index 0000000..c49c525 --- /dev/null +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml @@ -0,0 +1,22 @@ +  + + + + + \ No newline at end of file diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml.cs new file mode 100644 index 0000000..02d0a6d --- /dev/null +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml.cs @@ -0,0 +1,12 @@ +using MahApps.Metro.Controls; + +namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency.CustomUserControl +{ + public partial class FlyoutContainer : FlyoutsControl + { + public FlyoutContainer() + { + //InitializeComponent(); + } + } +} diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlayoutBase.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutBase.cs similarity index 99% rename from AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlayoutBase.cs rename to AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutBase.cs index de1629f..a966671 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlayoutBase.cs +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutBase.cs @@ -12,7 +12,7 @@ namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency /// and clean up as many resources as possible within OnClosing as the instance of the ViewModel will remain in memory from the /// moment of registration with the FlyoutManager until the moment of unregistration, or program exit. /// - public abstract class FlayoutBase: BindableBase, IFlyout + public abstract class FlyoutBase: BindableBase, IFlyout { public event EventHandler OnClosed; public event EventHandler OnOpened; diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs index b95b06c..1ab93c2 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs @@ -1,16 +1,244 @@ using AdamController.Services.Interfaces; +using DryIoc; +using Prism.Regions; using System; using System.Collections.Generic; + using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Windows; namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency { - public class FlyoutManager //: IFlyoutManager + public class FlyoutManager : IFlyoutManager { - IDictionary flyouts; - DryIoc.Container + IDictionary mFlyouts; + + Container mDryIocContainer; + + string mDefaultFlyoutRegion; + + public FlyoutManager(Container container, IRegionManager regionManager) + { + mDryIocContainer = container; + RegionManager = regionManager; + + } + + public IRegionManager RegionManager { get; set; } + + public void RegisterFlyoutWithDefaultRegion(string flyoutKey) where TView : FrameworkElement + { + if (String.IsNullOrEmpty(mDefaultFlyoutRegion)) + throw new NullReferenceException("Default region not set."); + RegisterFlyout(flyoutKey, mDefaultFlyoutRegion); + } + + + public void RegisterFlyoutWithDefaultRegion(string flyoutKey, IFlyout viewModel) where TView : FrameworkElement + { + if (String.IsNullOrEmpty(mDefaultFlyoutRegion)) + throw new NullReferenceException("Default region not set."); + RegisterFlyout(flyoutKey, mDefaultFlyoutRegion, viewModel); + } + + /// + /// Register Flyout with FlyoutManager. The viewmodel will be obtained from the view, so a view-first approach must + /// be used. This method is compatible with autowireviewmodel. The viewmodel produced must derive from IFlyout. + /// + /// Type of the view used for the flyout. + /// A key to identify the flyout. + /// The region name in which to display the flyout. + public void RegisterFlyout(string flyoutKey, string flyoutRegion) where TView : FrameworkElement + { + var flyoutView = ResolveFlyoutView(); + + var flyoutViewModel = GetFlyoutViewModelFromView(flyoutView); + + AddFlyoutToCollection(flyoutKey, flyoutRegion, flyoutViewModel, flyoutView); + } + + /// + /// Register Flyout with FlyoutManager, a viewmodel must be supplied that derives from IFlyout. + /// + /// Type of the view used for the flyout. + /// /// A key to identify the flyout. + /// The region name in which to display the flyout. + /// + public void RegisterFlyout(string flyoutKey, string flyoutRegion, IFlyout flyoutViewModel) where TView : FrameworkElement + { + var flyoutView = ResolveFlyoutView(); + + AddFlyoutToCollection(flyoutKey, flyoutRegion, flyoutViewModel, flyoutView); + } + + /// + /// Remove the specified Flyout from this FlyoutManager. + /// + /// The key that identifies the flyout. + public void UnRegisterFlyout(string key) + { + mFlyouts.Remove(key); + } + + /// + /// Remove the specified Flyout from this FlyoutManager + /// + /// The flyout to remove. + public void UnRegisterFlyout(IFlyout flyout) + { + var items = mFlyouts.Where(kvp => kvp.Value == flyout).ToList(); + items.ForEach(item => UnRegisterFlyout(item.Key)); + } + + /// + /// Attempt to open the identified flyout, passing default flyoutparameters to the flyout's CanOpen method. + /// + /// Identifies the flyout to open. + /// True if opened, false if CanOpen prevented opening. + public bool OpenFlyout(string key) + { + return OpenFlyout(key, new FlyoutParameters()); + } + + /// + /// Attempt to open the identified flyout, passing the specified flyoutparameters to the flyout's CanOpen method. + /// + /// Identifies the flyout to open. + /// Passed to the flyouts CanOpen method, and indirectly to OnOpening. + /// True if opened, false if CanOpen prevented opening. + public bool OpenFlyout(string key, FlyoutParameters flyoutParameters) + { + return OpenFlyout(key, flyoutParameters, false); + } + + /// + /// Attempts to open the identified flyout + /// Default flyoutparameters are passed to the flyout's CanOpen method and the result returned, + /// but if forceOpen is true, the flyout is opened even if CanOpen returns false. + /// + /// Identifies the flyout to open. + /// Whether to force open the flyout. + /// The result of the identified flyout's CanOpen method. + public bool OpenFlyout(string key, bool forceOpen) + { + return OpenFlyout(key, new FlyoutParameters(), forceOpen); + } + + /// + /// Attempts to open the identified flyout + /// The specified flyoutparameters are passed to the flyout's CanOpen method and the result returned, + /// but if forceOpen is true, the flyout is opened even if CanOpen returns false. + /// + /// Identifies the flyout to open. + /// Passed to the flyouts CanOpen method, and indirectly to OnOpening. + /// Whether to force open the flyout. + /// The result of the identified flyout's CanOpen method. + public bool OpenFlyout(string key, FlyoutParameters flyoutParameters, bool forceOpen) + { + var flyoutToActivate = mFlyouts[key]; + bool canOpen = flyoutToActivate.CanOpen(flyoutParameters); + + if (!forceOpen && !canOpen) + return false; + + flyoutToActivate.Open(flyoutParameters); + + return canOpen; + } + + public void SetDefaultFlyoutRegion(string regionName) + { + mDefaultFlyoutRegion = regionName; + } + + /// + /// Attempt to close the identified flyout, passing default flyoutparameters to the flyout's CanClose method. + /// + /// Identifies the flyout to close. + /// Passed to the flyouts CanClose method, and indirectly to OnClosing. + /// True if closed, false if CanClose prevented closing. + public bool CloseFlyout(string key) + { + return CloseFlyout(key, new FlyoutParameters()); + } + + /// + /// Attempt to close the identified flyout, passing the provided flyoutparameters to the flyout's CanClose method. + /// + /// Identifies the flyout to close. + /// Passed to the flyouts CanClose method, and indirectly to OnClosing. + /// True if closed, false if CanClose prevented closing. + public bool CloseFlyout(string key, FlyoutParameters flyoutParameters) + { + return CloseFlyout(key, flyoutParameters, false); + } + + /// + /// Closes the identified flyout, passing default flyoutparameters to the flyout's CanClose method. + /// If forceClose is true, the flyout will be closed even if CanClose returns false. The result of CanClose + /// will be returned by this method even if closure is forced. + /// + /// Identifies the flyout to close. + /// Force flyout closure even if CanClose returns false. + /// The results of the indentified flyouts CanClose method. + public bool CloseFlyout(string key, bool forceClose) + { + return CloseFlyout(key, new FlyoutParameters(), forceClose); + } + + /// + /// Closes the identified flyout, passing the provided flyoutparameters to the flyout's CanClose method. + /// If forceClose is true, the flyout will be closed even if CanClose returns false. The result of CanClose + /// will be returned by this method even if closure is forced. + /// + /// Identifies the flyout to close. + /// Passed to the flyouts CanClose method, and indirectly to OnClosing. + /// Force flyout closure even if CanClose returns false. + /// The results of the indentified flyouts CanClose method. + public bool CloseFlyout(string key, FlyoutParameters flyoutParameters, bool forceClose) + { + var flyoutToClose = mFlyouts[key]; + bool canClose = flyoutToClose.CanClose(flyoutParameters); + + if (!forceClose && !canClose) + return false; + + flyoutToClose.Open(flyoutParameters); + + return canClose; + } + + private IFlyout GetFlyoutViewModelFromView(FrameworkElement flyoutView) + { + IFlyout flyoutViewModel = flyoutView.DataContext as IFlyout; + + if (flyoutViewModel == null) + throw new ArgumentException(@"Type passed must have an auto-wired view model that implements IFlyout. + If auto-wiring is not used then pass the viewmodel instance to the overloaded + RegisterFlyout method."); + + return flyoutViewModel; + } + + private FrameworkElement ResolveFlyoutView() + { + return mDryIocContainer.Resolve() as FrameworkElement; + } + + private void RegisterFlyoutWithRegion(FrameworkElement flyoutView, string flyoutRegion) + { + RegionManager.RegisterViewWithRegion(flyoutRegion, () => + { + return flyoutView; + }); + } + + private void AddFlyoutToCollection(string flyoutKey, string flyoutRegion, IFlyout flyoutViewModel, FrameworkElement flyoutView) + { + RegisterFlyoutWithRegion(flyoutView, flyoutRegion); + + mFlyouts.Add(flyoutKey, flyoutViewModel); + } } } diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutsControlRegionAdapter.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutsControlRegionAdapter.cs new file mode 100644 index 0000000..a11ab02 --- /dev/null +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutsControlRegionAdapter.cs @@ -0,0 +1,41 @@ +using MahApps.Metro.Controls; +using Prism.Regions; +using System.Collections.Specialized; +using System.Windows; + +namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +{ + public class FlyoutsControlRegionAdapter : RegionAdapterBase + { + public FlyoutsControlRegionAdapter(IRegionBehaviorFactory factory): base(factory){} + + protected override void Adapt(IRegion region, FlyoutsControl regionTarget) + { + region.ActiveViews.CollectionChanged += (s, e) => + { + if (e.Action == NotifyCollectionChangedAction.Add) + { + foreach (FrameworkElement element in e.NewItems) + { + Flyout flyout = new Flyout(); + flyout.Content = element; + flyout.DataContext = element.DataContext; + regionTarget.Items.Add(flyout); + } + } + if (e.Action == NotifyCollectionChangedAction.Remove) + { + foreach (FrameworkElement element in e.OldItems) + { + regionTarget.Items.Remove(element); + } + } + }; + } + + protected override IRegion CreateRegion() + { + return new AllActiveRegion(); + } + } +} From dd5238ac5fcb1e7424947ce3f1439ba57474383e Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Wed, 3 Apr 2024 11:14:54 +1000 Subject: [PATCH 066/181] Worked flyout custom control --- .../AdamController.Services.csproj | 12 +---- .../CustomUserControl/FlyoutContainer.xaml | 12 ++--- .../CustomUserControl/FlyoutContainer.xaml.cs | 7 ++- .../FlyoutBase.cs | 7 ++- .../FlyoutManager.cs | 6 +-- .../FlyoutPosition.cs | 10 ++++ .../FlyoutTheme.cs | 11 +++++ AdamController/App.xaml.cs | 28 ++++++++++- AdamController/Views/MainWindow.xaml | 14 ++---- .../ComputerVisionControlViewModel.cs | 9 +++- .../VisualSettingsControlViewModel.cs | 9 ++-- .../FlayoutsRegionModule.cs | 16 +++++-- .../AdvancedBlocklySettingsViewModel.cs | 42 +++++++++++++---- .../ViewModels/FlayoutsViewModel.cs | 47 +++++++++++++++---- .../Views/FlayoutsView.xaml | 11 +++-- 15 files changed, 176 insertions(+), 65 deletions(-) create mode 100644 AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutPosition.cs create mode 100644 AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutTheme.cs diff --git a/AdamController.Services/AdamController.Services.csproj b/AdamController.Services/AdamController.Services.csproj index 1c0fd98..3560d0f 100644 --- a/AdamController.Services/AdamController.Services.csproj +++ b/AdamController.Services/AdamController.Services.csproj @@ -2,12 +2,9 @@ net7.0-windows + true - - - - @@ -29,11 +26,4 @@ - - - Designer - MSBuild:Compile - - - diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml index c49c525..ca7850c 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml @@ -1,8 +1,8 @@ -  - + + - \ No newline at end of file + diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml.cs index 02d0a6d..d9fff3b 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml.cs +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml.cs @@ -1,12 +1,15 @@ using MahApps.Metro.Controls; -namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency.CustomUserControl +namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency { + /// + /// Логика взаимодействия для FlyoutContainer.xaml + /// public partial class FlyoutContainer : FlyoutsControl { public FlyoutContainer() { - //InitializeComponent(); + InitializeComponent(); } } } diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutBase.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutBase.cs index a966671..4925a2b 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutBase.cs +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutBase.cs @@ -12,7 +12,7 @@ namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency /// and clean up as many resources as possible within OnClosing as the instance of the ViewModel will remain in memory from the /// moment of registration with the FlyoutManager until the moment of unregistration, or program exit. /// - public abstract class FlyoutBase: BindableBase, IFlyout + public abstract class FlyoutBase: BindableBase, IFlyout { public event EventHandler OnClosed; public event EventHandler OnOpened; @@ -41,7 +41,6 @@ public bool IsOpen { OnChanging(value); SetProperty(ref isOpen, value); - } } @@ -183,12 +182,16 @@ public string Header protected virtual void OnChanging(bool isOpening) { var flyoutAction = isOpening ? FlyoutAction.Opening : FlyoutAction.Closing; + var flyoutEventArgs = new FlyoutEventArgs(flyoutAction); + if (OnOpenChanged != null) OnOpenChanged(this, flyoutEventArgs); + if (flyoutAction == FlyoutAction.Opening) if (OnOpened != null) OnOpened(this, flyoutEventArgs); + if (flyoutAction == FlyoutAction.Closing) if (OnClosed != null) OnClosed(this, flyoutEventArgs); diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs index 1ab93c2..d52db98 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs @@ -14,15 +14,15 @@ public class FlyoutManager : IFlyoutManager IDictionary mFlyouts; - Container mDryIocContainer; + IContainer mDryIocContainer; string mDefaultFlyoutRegion; - public FlyoutManager(Container container, IRegionManager regionManager) + public FlyoutManager(IContainer container, IRegionManager regionManager) { mDryIocContainer = container; RegionManager = regionManager; - + mFlyouts = new Dictionary(); } public IRegionManager RegionManager { get; set; } diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutPosition.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutPosition.cs new file mode 100644 index 0000000..5443bdf --- /dev/null +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutPosition.cs @@ -0,0 +1,10 @@ +namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +{ + public class FlyoutPosition + { + public const string Right = "Right"; + public const string Left = "Left"; + public const string Top = "Top"; + public const string Bottom = "Bottom"; + } +} diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutTheme.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutTheme.cs new file mode 100644 index 0000000..85caf87 --- /dev/null +++ b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutTheme.cs @@ -0,0 +1,11 @@ +namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +{ + public class FlyoutTheme + { + public const string Adapt = "Adapt"; + public const string Inverse = "Inverse"; + public const string Dark = "Dark"; + public const string Light = "Light"; + public const string Accent = "Accent"; + } +} diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index be1d856..29fe2a6 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -21,6 +21,11 @@ using AdamController.Core.Dialog.ViewModels; using AdamController.Services.Interfaces; using AdamController.Core.Mvvm; +using AdamController.Services.FlayoutsRegionEventAwareServiceDependency; +using Prism.Regions; +using DryIoc; +using AdamController.Modules.FlayoutsRegion.Views; +using MahApps.Metro.Controls; #endregion @@ -82,19 +87,40 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return new FlayoutsRegionChangeOpenedAwareService(); }); + containerRegistry.RegisterSingleton(containerRegistry => + { + IContainer container = containerRegistry.GetContainer(); + var regionManager = containerRegistry.Resolve(); + + return new FlyoutManager(container, regionManager); + }); + //here must be ip/port containerRegistry.Register(); - + + //register custom control + //containerRegistry.RegisterForNavigation(); + + //register dialog containerRegistry.RegisterDialog(); containerRegistry.RegisterDialog(); } + protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings) + { + base.ConfigureRegionAdapterMappings(regionAdapterMappings); + + regionAdapterMappings.RegisterMapping(typeof(FlyoutsControl), Container.Resolve()); + } + protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) { moduleCatalog.AddModule(); moduleCatalog.AddModule(); moduleCatalog.AddModule(); moduleCatalog.AddModule(); + + } private static void LoadHighlighting() diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index c94ea44..57ae0f1 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -10,7 +10,9 @@ xmlns:properties="clr-namespace:AdamController.Core.Properties;assembly=AdamController.Core" xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" TitleCharacterCasing="Normal" WindowState="Maximized" ShowIconOnTitleBar="True" - xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" + xmlns:prism="http://prismlibrary.com/" + xmlns:customusercontrol="clr-namespace:AdamController.Services.FlayoutsRegionEventAwareServiceDependency;assembly=AdamController.Services" + prism:ViewModelLocator.AutoWireViewModel="True" Title="{Binding WindowTitle}"> @@ -71,13 +73,8 @@ - - - - - - - + @@ -144,7 +141,6 @@ - openAdvancedBlocklySettingsCommand ??= new DelegateCommand(() => { - RegionManager.RequestNavigate(RegionNames.FlayoutsRegion, FlayoutsRegionNames.FlayotAdvancedBlocklySettings); + FlyoutManager.OpenFlyout("FlayoutsView"); + //RegionManager.RequestNavigate(RegionNames.FlayoutsRegion, FlayoutsRegionNames.FlayotAdvancedBlocklySettings); }); private DelegateCommand changeBaseColorTheme; diff --git a/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs b/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs index 51fbd34..7007b7b 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs @@ -1,5 +1,6 @@ using AdamController.Core; using AdamController.Modules.FlayoutsRegion.Views; +using AdamController.Services.Interfaces; using Prism.Ioc; using Prism.Modularity; using Prism.Regions; @@ -9,24 +10,29 @@ namespace AdamController.Modules.FlayoutsRegion public class FlayoutsRegionModule : IModule { private readonly IRegionManager mRegionManager; + private readonly IFlyoutManager mFlyoutManager; - public FlayoutsRegionModule(IRegionManager regionManager) + public FlayoutsRegionModule(IRegionManager regionManager, IFlyoutManager flyoutManager) { mRegionManager = regionManager; + mFlyoutManager = flyoutManager; } public void OnInitialized(IContainerProvider containerProvider) { - mRegionManager.RequestNavigate(RegionNames.FlayoutsRegion, nameof(FlayoutsView)); + //mRegionManager.RequestNavigate(RegionNames.FlayoutsRegion, nameof(FlayoutsView)); } public void RegisterTypes(IContainerRegistry containerRegistry) { - containerRegistry.RegisterForNavigation(nameof(FlayoutsView)); + //containerRegistry.RegisterForNavigation(nameof(FlayoutsView)); - containerRegistry.RegisterForNavigation(nameof(NotificationView)); - containerRegistry.RegisterForNavigation(nameof(AdvancedBlocklySettingsView)); + mFlyoutManager.RegisterFlyout("FlayoutsView", RegionNames.FlayoutsRegion); + //mFlyoutManager.RegisterFlyout("AdvancedBlocklySettingsView", FlayoutsRegionNames.FlayotAdvancedBlocklySettings); + + //containerRegistry.RegisterForNavigation(nameof(NotificationView)); + //containerRegistry.RegisterForNavigation(nameof(AdvancedBlocklySettingsView)); } } } \ No newline at end of file diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs index 0a1dd2a..6035859 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs @@ -3,7 +3,9 @@ using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Core.Properties; +using AdamController.Services.FlayoutsRegionEventAwareServiceDependency; using AdamController.Services.Interfaces; +using Microsoft.VisualBasic.Logging; using Prism.Commands; using Prism.Regions; using Prism.Services.Dialogs; @@ -13,31 +15,53 @@ namespace AdamController.Modules.FlayoutsRegion.ViewModels { - public class AdvancedBlocklySettingsViewModel : RegionViewModelBase + public class AdvancedBlocklySettingsViewModel : FlyoutBase //: RegionViewModelBase { - private IFlayoutsRegionChangeOpenedAwareService FlayoutsRegionChangeOpenedService { get; } + //private IFlayoutsRegionChangeOpenedAwareService FlayoutsRegionChangeOpenedService { get; } - public AdvancedBlocklySettingsViewModel(IRegionManager regionManager, IDialogService dialogService, IFlayoutsRegionChangeOpenedAwareService flayoutsRegionChangeOpenedAwareService ) : base(regionManager, dialogService) + public AdvancedBlocklySettingsViewModel() { - FlayoutsRegionChangeOpenedService = flayoutsRegionChangeOpenedAwareService; + Position = FlyoutPosition.Right; + Theme = FlyoutTheme.Accent; + //FlayoutsRegionChangeOpenedService = flayoutsRegionChangeOpenedAwareService; + } + + protected override void OnChanging(bool isOpening) + { + base.OnChanging(isOpening); + } + + protected override void OnOpening(FlyoutParameters flyoutParameters) + { + // Because FlyoutParameters provides weakly-typed objects we need to cast the provided "dog" parameter as a Dog type + // Dog = flyoutParameters["dog"] as Dog; + + // We can set the Flyout name based on information passed via flyoutParameters + //Header = "Editing " + Dog.Name; + + // As well as setting the position + // if (Dog.Name == "Patch") + // Position = FlyoutPosition.Left; + // else + // Position = FlyoutPosition.Right; - + // And any other property you like. See the full list in the code wiki at flyoutmanager.codeplex.com } #region Navigation - public override void OnNavigatedFrom(NavigationContext navigationContext) + /*public override void OnNavigatedFrom(NavigationContext navigationContext) { AdvancedBlocklySettingsFlayoutsIsOpen = false; //FlayoutsRegionChangeOpenedService.RaiseAdvancedBlocklySettingsIsOpenChange -= RaiseAdvancedBlocklySettingsIsOpenChange; - } + }*/ - public override void OnNavigatedTo(NavigationContext navigationContext) + /*public override void OnNavigatedTo(NavigationContext navigationContext) { AdvancedBlocklySettingsFlayoutsIsOpen = true; //FlayoutsRegionChangeOpenedService.RaiseAdvancedBlocklySettingsIsOpenChange += RaiseAdvancedBlocklySettingsIsOpenChange; - } + }*/ #endregion diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs index ed34a49..cad4dbc 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs @@ -1,29 +1,60 @@ using AdamController.Core; using AdamController.Core.Mvvm; using AdamController.Modules.FlayoutsRegion.Views; +using AdamController.Services.FlayoutsRegionEventAwareServiceDependency; +using AdamController.Services.Interfaces; using Prism.Regions; using Prism.Services.Dialogs; using System; namespace AdamController.Modules.FlayoutsRegion.ViewModels { - public class FlayoutsViewModel : RegionViewModelBase + public class FlayoutsViewModel : FlyoutBase//: RegionViewModelBase { - public FlayoutsViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) - { + IFlyoutManager FlyoutManager { get; } + + public FlayoutsViewModel() + { + Position = FlyoutPosition.Right; + Theme = FlyoutTheme.Dark; } - public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) + protected override void OnChanging(bool isOpening) { - SubFlayoutsRequestNavigate(FlayoutsRegionNames.FlayotAdvancedBlocklySettings, navigationContext.Parameters); + base.OnChanging(isOpening); } - public override void OnNavigatedTo(NavigationContext navigationContext) + protected override void OnOpening(FlyoutParameters flyoutParameters) { - + base.OnOpening(flyoutParameters); + IsOpen = true; } + //public FlayoutsViewModel(IRegionManager regionManager, IDialogService dialogService, FlyoutManager flyoutManager) : base(regionManager, dialogService) + //{ + // FlyoutManager = flyoutManager; + // + // FlyoutManager.SetDefaultFlyoutRegion(FlayoutsRegionNames.FlayoutsInsideRegion); + //} + + + + //public FlayoutsViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager) : base(regionManager, dialogService) + //{ + // FlyoutManager = flyoutManager; + //} + + //public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) + //{ + // SubFlayoutsRequestNavigate(FlayoutsRegionNames.FlayotAdvancedBlocklySettings, navigationContext.Parameters); + //} + + //public override void OnNavigatedTo(NavigationContext navigationContext) + //{ + + //} + private void SubFlayoutsRequestNavigate(string uri, NavigationParameters parameters) { if (string.IsNullOrEmpty(uri)) @@ -33,7 +64,7 @@ private void SubFlayoutsRequestNavigate(string uri, NavigationParameters paramet switch (uri) { case FlayoutsRegionNames.FlayotAdvancedBlocklySettings: - RegionManager.RequestNavigate(FlayoutsRegionNames.FlayoutsInsideRegion, nameof(AdvancedBlocklySettingsView), parameters); + //RegionManager.RequestNavigate(FlayoutsRegionNames.FlayoutsInsideRegion, nameof(AdvancedBlocklySettingsView), parameters); break; } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml index 4b7b0ef..8436c2e 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml @@ -4,7 +4,12 @@ xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True"> - - - + + + + + + + + From 73135c373c0eae3a5d94e75f4288f6548f7e7e6f Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Wed, 3 Apr 2024 14:32:48 +1000 Subject: [PATCH 067/181] Close issue #12 --- .../AdamController.Controls.csproj | 14 ++++ .../FlyoutContainer}/FlyoutAction.cs | 5 +- .../FlyoutContainer}/FlyoutBase.cs | 11 ++- .../FlyoutContainer/FlyoutEventArgs.cs | 17 +++++ .../FlyoutContainer}/FlyoutParameters.cs | 10 ++- .../FlyoutContainer/FlyoutPosition.cs | 14 ++++ .../FlyoutContainer}/FlyoutTheme.cs | 6 +- .../FlyoutContainer}/IFlyout.cs | 6 +- .../FlyoutsControlRegionAdapter.cs | 18 +++-- .../CustomControls.Services}/FlyoutManager.cs | 36 ++++++---- .../IFlyoutManager.cs | 6 +- .../CustomControls}/FlyoutContainer.xaml | 3 +- .../CustomControls}/FlyoutContainer.xaml.cs | 5 +- .../AdamController.Core.csproj | 1 + .../FlayoutsRegionChangeOpenedAwareService.cs | 42 ------------ .../FlyoutEventArgs.cs | 14 ---- .../FlyoutPosition.cs | 10 --- ...IFlayoutsRegionChangeOpenedAwareService.cs | 11 --- AdamController.sln | 6 ++ AdamController/AdamController.csproj | 3 - AdamController/App.xaml.cs | 68 +++++++++---------- .../ViewModels/MainWindowViewModel.cs | 5 +- AdamController/Views/MainWindow.xaml | 8 +-- .../ComputerVisionControlViewModel.cs | 3 +- .../VisualSettingsControlViewModel.cs | 1 + .../FlayoutsRegionModule.cs | 4 +- .../AdvancedBlocklySettingsViewModel.cs | 15 +--- .../ViewModels/FlayoutsViewModel.cs | 21 +----- .../Views/FlayoutsView.xaml | 4 -- README.md | 4 ++ 30 files changed, 165 insertions(+), 206 deletions(-) create mode 100644 AdamController.Controls/AdamController.Controls.csproj rename {AdamController.Services/FlayoutsRegionEventAwareServiceDependency => AdamController.Controls/CustomControls.Mvvm/FlyoutContainer}/FlyoutAction.cs (85%) rename {AdamController.Services/FlayoutsRegionEventAwareServiceDependency => AdamController.Controls/CustomControls.Mvvm/FlyoutContainer}/FlyoutBase.cs (97%) create mode 100644 AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutEventArgs.cs rename {AdamController.Services/FlayoutsRegionEventAwareServiceDependency => AdamController.Controls/CustomControls.Mvvm/FlyoutContainer}/FlyoutParameters.cs (59%) create mode 100644 AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutPosition.cs rename {AdamController.Services/FlayoutsRegionEventAwareServiceDependency => AdamController.Controls/CustomControls.Mvvm/FlyoutContainer}/FlyoutTheme.cs (52%) rename {AdamController.Services/Interfaces => AdamController.Controls/CustomControls.Mvvm/FlyoutContainer}/IFlyout.cs (88%) rename {AdamController.Services/FlayoutsRegionEventAwareServiceDependency => AdamController.Controls/CustomControls.RegionAdapters}/FlyoutsControlRegionAdapter.cs (69%) rename {AdamController.Services/FlayoutsRegionEventAwareServiceDependency => AdamController.Controls/CustomControls.Services}/FlyoutManager.cs (89%) rename {AdamController.Services/Interfaces => AdamController.Controls/CustomControls.Services}/IFlyoutManager.cs (87%) rename {AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl => AdamController.Controls/CustomControls}/FlyoutContainer.xaml (91%) rename {AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl => AdamController.Controls/CustomControls}/FlyoutContainer.xaml.cs (50%) delete mode 100644 AdamController.Services/FlayoutsRegionChangeOpenedAwareService.cs delete mode 100644 AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutEventArgs.cs delete mode 100644 AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutPosition.cs delete mode 100644 AdamController.Services/Interfaces/IFlayoutsRegionChangeOpenedAwareService.cs diff --git a/AdamController.Controls/AdamController.Controls.csproj b/AdamController.Controls/AdamController.Controls.csproj new file mode 100644 index 0000000..75c197e --- /dev/null +++ b/AdamController.Controls/AdamController.Controls.csproj @@ -0,0 +1,14 @@ + + + + net7.0-windows + enable + true + enable + + + + + + + diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutAction.cs b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutAction.cs similarity index 85% rename from AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutAction.cs rename to AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutAction.cs index 6152747..267ebbd 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutAction.cs +++ b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutAction.cs @@ -1,5 +1,8 @@ -namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +namespace AdamController.Controls.CustomControls.Mvvm.FlyoutContainer { + /// + /// Represents the ongoing direction of change of a Flyout + /// public class FlyoutAction { private const string mOpening = "Opening"; diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutBase.cs b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutBase.cs similarity index 97% rename from AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutBase.cs rename to AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutBase.cs index 4925a2b..76b04ae 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutBase.cs +++ b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutBase.cs @@ -1,9 +1,7 @@ -using AdamController.Services.Interfaces; -using Prism.Mvvm; -using System; +using Prism.Mvvm; using System.Windows.Input; -namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +namespace AdamController.Controls.CustomControls.Mvvm.FlyoutContainer { /// /// Base class that provides and implementation of IFlyout. @@ -12,7 +10,7 @@ namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency /// and clean up as many resources as possible within OnClosing as the instance of the ViewModel will remain in memory from the /// moment of registration with the FlyoutManager until the moment of unregistration, or program exit. /// - public abstract class FlyoutBase: BindableBase, IFlyout + public abstract class FlyoutBase : BindableBase, IFlyout { public event EventHandler OnClosed; public event EventHandler OnOpened; @@ -184,7 +182,7 @@ protected virtual void OnChanging(bool isOpening) var flyoutAction = isOpening ? FlyoutAction.Opening : FlyoutAction.Closing; var flyoutEventArgs = new FlyoutEventArgs(flyoutAction); - + if (OnOpenChanged != null) OnOpenChanged(this, flyoutEventArgs); @@ -229,3 +227,4 @@ public void Open() } } } + diff --git a/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutEventArgs.cs b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutEventArgs.cs new file mode 100644 index 0000000..23b3b15 --- /dev/null +++ b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutEventArgs.cs @@ -0,0 +1,17 @@ +namespace AdamController.Controls.CustomControls.Mvvm.FlyoutContainer +{ + /// + /// Event arguments passed with the OnOpened, OnClosed and OnOpenChanged event delegates. + /// Flyout action is a required parameter to the constructor. + /// Additional FlyoutParameters can also be attached. + /// + public class FlyoutEventArgs : EventArgs + { + public FlyoutAction FlyoutAction { get; set; } + + public FlyoutEventArgs(FlyoutAction flyoutAction) + { + FlyoutAction = flyoutAction; + } + } +} diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutParameters.cs b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutParameters.cs similarity index 59% rename from AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutParameters.cs rename to AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutParameters.cs index 0b6b672..aaa66ac 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutParameters.cs +++ b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutParameters.cs @@ -1,11 +1,15 @@ using System.Collections; -using System.Collections.Generic; -namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +namespace AdamController.Controls.CustomControls.Mvvm.FlyoutContainer { + /// + /// A collection of parameters that are passed from objects requesting the Flyout to open to the IFlyout ViewModel that controls + /// the specific Flyout. + /// These parameters can also (optionally) be attached to FlyoutEventArgs when notifying subscribers of a change in the Flyout status. + /// public class FlyoutParameters : IEnumerable { - IDictionary parameters; + private readonly IDictionary parameters; public FlyoutParameters() { diff --git a/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutPosition.cs b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutPosition.cs new file mode 100644 index 0000000..d257c41 --- /dev/null +++ b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutPosition.cs @@ -0,0 +1,14 @@ +namespace AdamController.Controls.CustomControls.Mvvm.FlyoutContainer +{ + /// + /// Represents the Position of the Flyout within the (Metro) Window + /// Usually set in the constructor of the IFlyout ViewModel + /// + public class FlyoutPosition + { + public const string Right = "Right"; + public const string Left = "Left"; + public const string Top = "Top"; + public const string Bottom = "Bottom"; + } +} diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutTheme.cs b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutTheme.cs similarity index 52% rename from AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutTheme.cs rename to AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutTheme.cs index 85caf87..0552932 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutTheme.cs +++ b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutTheme.cs @@ -1,5 +1,9 @@ -namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +namespace AdamController.Controls.CustomControls.Mvvm.FlyoutContainer { + /// + /// Represents the possible values for the Flyouts Theme + /// Usually set in the constructor of the individual IFlyout ViewModel + /// public class FlyoutTheme { public const string Adapt = "Adapt"; diff --git a/AdamController.Services/Interfaces/IFlyout.cs b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/IFlyout.cs similarity index 88% rename from AdamController.Services/Interfaces/IFlyout.cs rename to AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/IFlyout.cs index 90bcdb9..66e46be 100644 --- a/AdamController.Services/Interfaces/IFlyout.cs +++ b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/IFlyout.cs @@ -1,13 +1,9 @@ using System.Windows.Input; -using System; -using AdamController.Services.FlayoutsRegionEventAwareServiceDependency; -namespace AdamController.Services.Interfaces +namespace AdamController.Controls.CustomControls.Mvvm.FlyoutContainer { - public interface IFlyout { - public event EventHandler OnClosed; public event EventHandler OnOpened; diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutsControlRegionAdapter.cs b/AdamController.Controls/CustomControls.RegionAdapters/FlyoutsControlRegionAdapter.cs similarity index 69% rename from AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutsControlRegionAdapter.cs rename to AdamController.Controls/CustomControls.RegionAdapters/FlyoutsControlRegionAdapter.cs index a11ab02..5534b0e 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutsControlRegionAdapter.cs +++ b/AdamController.Controls/CustomControls.RegionAdapters/FlyoutsControlRegionAdapter.cs @@ -3,11 +3,11 @@ using System.Collections.Specialized; using System.Windows; -namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +namespace AdamController.Controls.CustomControls.RegionAdapters { public class FlyoutsControlRegionAdapter : RegionAdapterBase { - public FlyoutsControlRegionAdapter(IRegionBehaviorFactory factory): base(factory){} + public FlyoutsControlRegionAdapter(IRegionBehaviorFactory factory) : base(factory) { } protected override void Adapt(IRegion region, FlyoutsControl regionTarget) { @@ -15,17 +15,21 @@ protected override void Adapt(IRegion region, FlyoutsControl regionTarget) { if (e.Action == NotifyCollectionChangedAction.Add) { - foreach (FrameworkElement element in e.NewItems) + foreach (FrameworkElement element in e?.NewItems) { - Flyout flyout = new Flyout(); - flyout.Content = element; - flyout.DataContext = element.DataContext; + Flyout flyout = new() + { + Content = element, + DataContext = element.DataContext + }; + regionTarget.Items.Add(flyout); } } + if (e.Action == NotifyCollectionChangedAction.Remove) { - foreach (FrameworkElement element in e.OldItems) + foreach (FrameworkElement element in e?.OldItems) { regionTarget.Items.Remove(element); } diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs b/AdamController.Controls/CustomControls.Services/FlyoutManager.cs similarity index 89% rename from AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs rename to AdamController.Controls/CustomControls.Services/FlyoutManager.cs index d52db98..425cabc 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutManager.cs +++ b/AdamController.Controls/CustomControls.Services/FlyoutManager.cs @@ -1,44 +1,56 @@ -using AdamController.Services.Interfaces; +using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; using DryIoc; using Prism.Regions; -using System; -using System.Collections.Generic; - -using System.Linq; using System.Windows; -namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +namespace AdamController.Controls.CustomControls.Services { + /// + /// Manages a collection of Flyouts, registering them with specified regions and creating their views and viewmodels. + /// Flyouts that are managed must have viewmodels that implement IFlyout. + /// public class FlyoutManager : IFlyoutManager { + private readonly IDictionary mFlyouts; - IDictionary mFlyouts; + private readonly IContainer mDryIocContainer; - IContainer mDryIocContainer; + private string mDefaultFlyoutRegion = string.Empty; - string mDefaultFlyoutRegion; + /// + /// The region manager controlling the region where the Flyouts are to be displayed. + /// Made public to allow use of sub-region managers. + /// + public IRegionManager RegionManager { get; } + /// + /// Default constructor + /// + /// DryIoc container, generally passed by dependency injection. + /// Region manager, generally passed by dependency injection. public FlyoutManager(IContainer container, IRegionManager regionManager) { mDryIocContainer = container; RegionManager = regionManager; + mFlyouts = new Dictionary(); } - public IRegionManager RegionManager { get; set; } public void RegisterFlyoutWithDefaultRegion(string flyoutKey) where TView : FrameworkElement { - if (String.IsNullOrEmpty(mDefaultFlyoutRegion)) + if (string.IsNullOrEmpty(mDefaultFlyoutRegion)) throw new NullReferenceException("Default region not set."); + RegisterFlyout(flyoutKey, mDefaultFlyoutRegion); } public void RegisterFlyoutWithDefaultRegion(string flyoutKey, IFlyout viewModel) where TView : FrameworkElement { - if (String.IsNullOrEmpty(mDefaultFlyoutRegion)) + if (string.IsNullOrEmpty(mDefaultFlyoutRegion)) throw new NullReferenceException("Default region not set."); + RegisterFlyout(flyoutKey, mDefaultFlyoutRegion, viewModel); } diff --git a/AdamController.Services/Interfaces/IFlyoutManager.cs b/AdamController.Controls/CustomControls.Services/IFlyoutManager.cs similarity index 87% rename from AdamController.Services/Interfaces/IFlyoutManager.cs rename to AdamController.Controls/CustomControls.Services/IFlyoutManager.cs index b9a7f1c..618487a 100644 --- a/AdamController.Services/Interfaces/IFlyoutManager.cs +++ b/AdamController.Controls/CustomControls.Services/IFlyoutManager.cs @@ -1,12 +1,12 @@ -using AdamController.Services.FlayoutsRegionEventAwareServiceDependency; +using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; using Prism.Regions; using System.Windows; -namespace AdamController.Services.Interfaces +namespace AdamController.Controls.CustomControls.Services { public interface IFlyoutManager { - public IRegionManager RegionManager { get; set; } + public IRegionManager RegionManager { get; } public void SetDefaultFlyoutRegion(string regionName); diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml b/AdamController.Controls/CustomControls/FlyoutContainer.xaml similarity index 91% rename from AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml rename to AdamController.Controls/CustomControls/FlyoutContainer.xaml index ca7850c..49f0ee5 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml +++ b/AdamController.Controls/CustomControls/FlyoutContainer.xaml @@ -1,5 +1,4 @@ - - diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml.cs b/AdamController.Controls/CustomControls/FlyoutContainer.xaml.cs similarity index 50% rename from AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml.cs rename to AdamController.Controls/CustomControls/FlyoutContainer.xaml.cs index d9fff3b..0106a6c 100644 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/CustomUserControl/FlyoutContainer.xaml.cs +++ b/AdamController.Controls/CustomControls/FlyoutContainer.xaml.cs @@ -1,10 +1,7 @@ using MahApps.Metro.Controls; -namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency +namespace AdamController.Controls.CustomControls { - /// - /// Логика взаимодействия для FlyoutContainer.xaml - /// public partial class FlyoutContainer : FlyoutsControl { public FlyoutContainer() diff --git a/AdamController.Core/AdamController.Core.csproj b/AdamController.Core/AdamController.Core.csproj index d5a3bcb..b784f98 100644 --- a/AdamController.Core/AdamController.Core.csproj +++ b/AdamController.Core/AdamController.Core.csproj @@ -20,6 +20,7 @@ + diff --git a/AdamController.Services/FlayoutsRegionChangeOpenedAwareService.cs b/AdamController.Services/FlayoutsRegionChangeOpenedAwareService.cs deleted file mode 100644 index 4290b73..0000000 --- a/AdamController.Services/FlayoutsRegionChangeOpenedAwareService.cs +++ /dev/null @@ -1,42 +0,0 @@ -using AdamController.Services.Interfaces; - -namespace AdamController.Services -{ - public class FlayoutsRegionChangeOpenedAwareService : IFlayoutsRegionChangeOpenedAwareService - { - public event AdvancedBlocklySettingsIsOpenChangeEventHandler RaiseAdvancedBlocklySettingsIsOpenChange; - - - private bool mAdvancedBlocklySettingsIsOpen; - public bool AdvancedBlocklySettingsIsOpen - { - get { return mAdvancedBlocklySettingsIsOpen; } - set - { - mAdvancedBlocklySettingsIsOpen = value; - OnRaiseAdvancedBlocklySettingsIsOpenChange(); - } - } - - private bool mNotificationFlayoutsIsOpen; - - public bool NotificationFlayoutsIsOpen - { - get { return mNotificationFlayoutsIsOpen; } - set - { - mNotificationFlayoutsIsOpen = value; - } - } - - - protected virtual void OnRaiseAdvancedBlocklySettingsIsOpenChange() - { - AdvancedBlocklySettingsIsOpenChangeEventHandler raiseEvent = RaiseAdvancedBlocklySettingsIsOpenChange; - raiseEvent?.Invoke(this); - - } - - - } -} diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutEventArgs.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutEventArgs.cs deleted file mode 100644 index edba008..0000000 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutEventArgs.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency -{ - public class FlyoutEventArgs : EventArgs - { - public FlyoutAction FlyoutAction { get; set; } - - public FlyoutEventArgs(FlyoutAction flyoutAction) - { - FlyoutAction = flyoutAction; - } - } -} diff --git a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutPosition.cs b/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutPosition.cs deleted file mode 100644 index 5443bdf..0000000 --- a/AdamController.Services/FlayoutsRegionEventAwareServiceDependency/FlyoutPosition.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace AdamController.Services.FlayoutsRegionEventAwareServiceDependency -{ - public class FlyoutPosition - { - public const string Right = "Right"; - public const string Left = "Left"; - public const string Top = "Top"; - public const string Bottom = "Bottom"; - } -} diff --git a/AdamController.Services/Interfaces/IFlayoutsRegionChangeOpenedAwareService.cs b/AdamController.Services/Interfaces/IFlayoutsRegionChangeOpenedAwareService.cs deleted file mode 100644 index a304373..0000000 --- a/AdamController.Services/Interfaces/IFlayoutsRegionChangeOpenedAwareService.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace AdamController.Services.Interfaces -{ - public delegate void AdvancedBlocklySettingsIsOpenChangeEventHandler(object sender); - - public interface IFlayoutsRegionChangeOpenedAwareService - { - public event AdvancedBlocklySettingsIsOpenChangeEventHandler RaiseAdvancedBlocklySettingsIsOpenChange; - public bool AdvancedBlocklySettingsIsOpen { get; set; } - public bool NotificationFlayoutsIsOpen { get; set; } - } -} diff --git a/AdamController.sln b/AdamController.sln index 9ff424c..5b251e1 100644 --- a/AdamController.sln +++ b/AdamController.sln @@ -25,6 +25,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamBlocklyLibrary", "Legac EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdamController.WebApi.Client", "Legacy\AdamController.WebApi.Client\AdamController.WebApi.Client.csproj", "{771220FE-2F25-441B-815E-7DD63918BA95}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdamController.Controls", "AdamController.Controls\AdamController.Controls.csproj", "{1BADFDB1-D66E-4580-8EAF-CAEE37761640}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -67,6 +69,10 @@ Global {771220FE-2F25-441B-815E-7DD63918BA95}.Debug|Any CPU.Build.0 = Debug|Any CPU {771220FE-2F25-441B-815E-7DD63918BA95}.Release|Any CPU.ActiveCfg = Release|Any CPU {771220FE-2F25-441B-815E-7DD63918BA95}.Release|Any CPU.Build.0 = Release|Any CPU + {1BADFDB1-D66E-4580-8EAF-CAEE37761640}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1BADFDB1-D66E-4580-8EAF-CAEE37761640}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1BADFDB1-D66E-4580-8EAF-CAEE37761640}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1BADFDB1-D66E-4580-8EAF-CAEE37761640}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/AdamController/AdamController.csproj b/AdamController/AdamController.csproj index eb92cc0..ce603eb 100644 --- a/AdamController/AdamController.csproj +++ b/AdamController/AdamController.csproj @@ -38,9 +38,6 @@ - - - diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 29fe2a6..b65ea4e 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -1,16 +1,25 @@ -using AdamController.Views; -using ControlzEx.Theming; -using ICSharpCode.AvalonEdit.Highlighting; +#region system + using System; using System.IO; using System.Windows; using System.Xml; +#endregion + #region prism using Prism.Ioc; using Prism.DryIoc; using Prism.Modularity; +using Prism.Regions; +using DryIoc; + +#endregion + +#region innerhit + +using AdamController.Views; using AdamController.Modules.MenuRegion; using AdamController.Modules.ContentRegion; using AdamController.Core.Helpers; @@ -20,25 +29,28 @@ using AdamController.Core.Dialog.Views; using AdamController.Core.Dialog.ViewModels; using AdamController.Services.Interfaces; -using AdamController.Core.Mvvm; -using AdamController.Services.FlayoutsRegionEventAwareServiceDependency; -using Prism.Regions; -using DryIoc; -using AdamController.Modules.FlayoutsRegion.Views; +using AdamController.Controls.CustomControls.Services; +using AdamController.Controls.CustomControls.RegionAdapters; + +#endregion + +#region mahapps + using MahApps.Metro.Controls; #endregion +#region other + +using ControlzEx.Theming; +using ICSharpCode.AvalonEdit.Highlighting; + +#endregion + namespace AdamController { public partial class App : PrismApplication { - - public App() - { - - } - protected override Window CreateShell() { MainWindow window = Container.Resolve(); @@ -48,14 +60,10 @@ protected override Window CreateShell() protected override void OnStartup(StartupEventArgs e) { + base.OnStartup(e); LoadHighlighting(); - // side menu context, MUST inherit from MainViewModel - // HamburgerMenuView : MainWindowView - // and MainWindowView MUST inherit from BaseViewModel - // MainWindowView : BaseViewModel - _ = FolderHelper.CreateAppDataFolder(); //TODO check theme before ChangeTheme @@ -71,8 +79,6 @@ protected override void OnStartup(StartupEventArgs e) string password = Core.Properties.Settings.Default.ApiPassword; WebApi.Client.v1.BaseApi.SetAuthenticationHeader(login, password); - - base.OnStartup(e); } protected override void RegisterTypes(IContainerRegistry containerRegistry) @@ -82,26 +88,22 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return new SubRegionChangeAwareService(); }); - containerRegistry.RegisterSingleton(containerRegistry => - { - return new FlayoutsRegionChangeOpenedAwareService(); - }); - containerRegistry.RegisterSingleton(containerRegistry => { IContainer container = containerRegistry.GetContainer(); - var regionManager = containerRegistry.Resolve(); + IRegionManager regionManager = containerRegistry.Resolve(); return new FlyoutManager(container, regionManager); }); //here must be ip/port - containerRegistry.Register(); + containerRegistry.RegisterSingleton(); - //register custom control - //containerRegistry.RegisterForNavigation(); + RegisterDialogs(containerRegistry); + } - //register dialog + private static void RegisterDialogs(IContainerRegistry containerRegistry) + { containerRegistry.RegisterDialog(); containerRegistry.RegisterDialog(); } @@ -118,9 +120,7 @@ protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) moduleCatalog.AddModule(); moduleCatalog.AddModule(); moduleCatalog.AddModule(); - moduleCatalog.AddModule(); - - + moduleCatalog.AddModule(); } private static void LoadHighlighting() diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index 8712b2c..4fd725e 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -21,18 +21,15 @@ public class MainWindowViewModel : BindableBase public IRegionManager RegionManager { get; } private ISubRegionChangeAwareService SubRegionChangeAwareService { get; } - private IFlayoutsRegionChangeOpenedAwareService FlayoutsRegionChangeOpenedAwareService { get; } - #endregion #region ~ - public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService, IFlayoutsRegionChangeOpenedAwareService flayoutsRegionChangeOpenedAwareService) + public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService) { RegionManager = regionManager; ShowRegionCommand = new DelegateCommand(ShowRegion); SubRegionChangeAwareService = subRegionChangeAwareService; - FlayoutsRegionChangeOpenedAwareService = flayoutsRegionChangeOpenedAwareService; SubRegionChangeAwareService.RaiseSubRegionChangeEvent += RaiseSubRegionChangeEvent; Application.Current.MainWindow.Loaded += MainWindowLoaded; diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index 57ae0f1..59c5bbf 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -11,7 +11,7 @@ xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" TitleCharacterCasing="Normal" WindowState="Maximized" ShowIconOnTitleBar="True" xmlns:prism="http://prismlibrary.com/" - xmlns:customusercontrol="clr-namespace:AdamController.Services.FlayoutsRegionEventAwareServiceDependency;assembly=AdamController.Services" + xmlns:customusercontrol="clr-namespace:AdamController.Controls.CustomControls;assembly=AdamController.Controls" prism:ViewModelLocator.AutoWireViewModel="True" Title="{Binding WindowTitle}"> @@ -57,7 +57,7 @@ - - + diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs index afc5b0a..8e958ec 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs @@ -1,4 +1,5 @@ -using AdamController.Core.Helpers; +using AdamController.Controls.CustomControls.Services; +using AdamController.Core.Helpers; using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Services.Interfaces; diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index 7371e7e..e935bf7 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -1,4 +1,5 @@ using AdamBlocklyLibrary.Enum; +using AdamController.Controls.CustomControls.Services; using AdamController.Core; using AdamController.Core.DataSource; using AdamController.Core.Model; diff --git a/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs b/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs index 7007b7b..addcda3 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs @@ -1,6 +1,6 @@ -using AdamController.Core; +using AdamController.Controls.CustomControls.Services; +using AdamController.Core; using AdamController.Modules.FlayoutsRegion.Views; -using AdamController.Services.Interfaces; using Prism.Ioc; using Prism.Modularity; using Prism.Regions; diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs index 6035859..ff01afa 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs @@ -1,17 +1,4 @@ -using AdamBlocklyLibrary.Enum; -using AdamController.Core.DataSource; -using AdamController.Core.Model; -using AdamController.Core.Mvvm; -using AdamController.Core.Properties; -using AdamController.Services.FlayoutsRegionEventAwareServiceDependency; -using AdamController.Services.Interfaces; -using Microsoft.VisualBasic.Logging; -using Prism.Commands; -using Prism.Regions; -using Prism.Services.Dialogs; -using System.Collections.ObjectModel; -using System.Linq; -using System.Windows.Media; +using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; namespace AdamController.Modules.FlayoutsRegion.ViewModels { diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs index cad4dbc..851d651 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs @@ -1,11 +1,7 @@ -using AdamController.Core; -using AdamController.Core.Mvvm; -using AdamController.Modules.FlayoutsRegion.Views; -using AdamController.Services.FlayoutsRegionEventAwareServiceDependency; -using AdamController.Services.Interfaces; +using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; +using AdamController.Controls.CustomControls.Services; +using AdamController.Core; using Prism.Regions; -using Prism.Services.Dialogs; -using System; namespace AdamController.Modules.FlayoutsRegion.ViewModels { @@ -20,17 +16,6 @@ public FlayoutsViewModel() Theme = FlyoutTheme.Dark; } - protected override void OnChanging(bool isOpening) - { - base.OnChanging(isOpening); - } - - protected override void OnOpening(FlyoutParameters flyoutParameters) - { - base.OnOpening(flyoutParameters); - IsOpen = true; - } - //public FlayoutsViewModel(IRegionManager regionManager, IDialogService dialogService, FlyoutManager flyoutManager) : base(regionManager, dialogService) //{ // FlyoutManager = flyoutManager; diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml index 8436c2e..25ba18c 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml @@ -5,10 +5,6 @@ xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True"> - - - - diff --git a/README.md b/README.md index 9d95b2e..1e302b7 100644 --- a/README.md +++ b/README.md @@ -11,3 +11,7 @@ For a successful launch, the following components must be installed in the syste * [MicrosoftEdgeWebView2RuntimeInstaller.113.0.1774.50.X64](https://disk.yandex.ru/d/vT4lVRCzDylGYA) * [VC_redist.14.29.30135.0.x64](https://disk.yandex.ru/d/0hzuZSiQIxZxLQ) * [windowsdesktop-runtime-7.0.5-win-x64](https://disk.yandex.ru/d/TQ2qIRYBnq2Ecw) + +# Thanks + +The Flyout solution is copied from [here](https://github.com/alsiola/FlyoutManager). From 376242ddce80467d622f8f01737b3c8fc7f45293 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Wed, 3 Apr 2024 15:41:14 +1000 Subject: [PATCH 068/181] Close issue #13 --- .../FlyoutContainer/FlyoutBase.cs | 78 ++-- AdamController.Core/FlayoutsRegionNames.cs | 9 - AdamController.Core/FlyoutNames.cs | 11 + .../VisualSettingsControlViewModel.cs | 4 +- .../FlayoutsRegionModule.cs | 20 +- .../AdvancedBlocklySettingsViewModel.cs | 86 +--- .../ViewModels/FlayoutsViewModel.cs | 58 --- .../ViewModels/NotificationViewModel.cs | 15 +- .../Views/AdvancedBlocklySettingsView.xaml | 411 +++++++++--------- .../Views/FlayoutsView.xaml | 11 - .../Views/FlayoutsView.xaml.cs | 12 - .../Views/NotificationView.xaml | 169 ++++--- .../ViewModels/StatusBarViewModel.cs | 23 +- 13 files changed, 374 insertions(+), 533 deletions(-) delete mode 100644 AdamController.Core/FlayoutsRegionNames.cs create mode 100644 AdamController.Core/FlyoutNames.cs delete mode 100644 Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs delete mode 100644 Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml delete mode 100644 Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml.cs diff --git a/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutBase.cs b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutBase.cs index 76b04ae..704a10d 100644 --- a/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutBase.cs +++ b/AdamController.Controls/CustomControls.Mvvm/FlyoutContainer/FlyoutBase.cs @@ -15,17 +15,20 @@ public abstract class FlyoutBase : BindableBase, IFlyout public event EventHandler OnClosed; public event EventHandler OnOpened; public event EventHandler OnOpenChanged; - private bool isOpen; - private string position; - private string header; - private string theme; - private bool isModal = false; - private bool areAnimationsEnabled = true; - private bool animateOpacity; - private ICommand closeCommand; - private MouseButton externalCloseButton; - private bool closeButtonIsCancel; - private bool isPinned; + + private bool mIsOpen; + private bool mIsModal = true; + private bool mAreAnimationsEnabled = true; + private bool mAnimateOpacity = true; + private bool mCloseButtonIsCancel; + private bool mIsPinned; + + private string mPosition = FlyoutPosition.Right; + private string mHeader = string.Empty; + private string mTheme = FlyoutTheme.Adapt; + + private ICommand mCloseCommand; + private MouseButton mExternalCloseButton; /// /// Bindable property to determine open/closed staus of flyout, based on private field isOpen. @@ -34,11 +37,11 @@ public abstract class FlyoutBase : BindableBase, IFlyout /// public bool IsOpen { - get { return isOpen; } + get { return mIsOpen; } set { OnChanging(value); - SetProperty(ref isOpen, value); + SetProperty(ref mIsOpen, value); } } @@ -49,8 +52,8 @@ public bool IsOpen /// public string Position { - get { return position; } - set { SetProperty(ref position, value); } + get { return mPosition; } + set { SetProperty(ref mPosition, value); } } /// @@ -59,8 +62,8 @@ public string Position /// public string Theme { - get { return theme; } - set { SetProperty(ref theme, value); } + get { return mTheme; } + set { SetProperty(ref mTheme, value); } } /// @@ -68,8 +71,8 @@ public string Theme /// public bool IsModal { - get { return isModal; } - set { SetProperty(ref isModal, value); } + get { return mIsModal; } + set { SetProperty(ref mIsModal, value); } } /// @@ -77,8 +80,8 @@ public bool IsModal /// public bool AreAnimationsEnabled { - get { return areAnimationsEnabled; } - set { SetProperty(ref areAnimationsEnabled, value); } + get { return mAreAnimationsEnabled; } + set { SetProperty(ref mAreAnimationsEnabled, value); } } /// @@ -86,8 +89,8 @@ public bool AreAnimationsEnabled /// public ICommand CloseCommand { - get { return closeCommand; } - set { SetProperty(ref closeCommand, value); } + get { return mCloseCommand; } + set { SetProperty(ref mCloseCommand, value); } } /// @@ -95,8 +98,8 @@ public ICommand CloseCommand /// public MouseButton ExternalCloseButton { - get { return externalCloseButton; } - set { SetProperty(ref externalCloseButton, value); } + get { return mExternalCloseButton; } + set { SetProperty(ref mExternalCloseButton, value); } } /// @@ -104,8 +107,8 @@ public MouseButton ExternalCloseButton /// public bool CloseButtonIsCancel { - get { return closeButtonIsCancel; } - set { SetProperty(ref closeButtonIsCancel, value); } + get { return mCloseButtonIsCancel; } + set { SetProperty(ref mCloseButtonIsCancel, value); } } /// @@ -113,8 +116,8 @@ public bool CloseButtonIsCancel /// public bool IsPinned { - get { return isPinned; } - set { SetProperty(ref isPinned, value); } + get { return mIsPinned; } + set { SetProperty(ref mIsPinned, value); } } /// @@ -135,8 +138,8 @@ public virtual bool CanOpen(FlyoutParameters flyoutParameters) /// public bool AnimateOpacity { - get { return animateOpacity; } - set { SetProperty(ref animateOpacity, value); } + get { return mAnimateOpacity; } + set { SetProperty(ref mAnimateOpacity, value); } } /// @@ -169,8 +172,8 @@ protected virtual void OnOpening(FlyoutParameters flyoutParameters) { } /// public string Header { - get { return header; } - set { SetProperty(ref header, value); } + get { return mHeader; } + set { SetProperty(ref mHeader, value); } } /// @@ -183,16 +186,13 @@ protected virtual void OnChanging(bool isOpening) var flyoutEventArgs = new FlyoutEventArgs(flyoutAction); - if (OnOpenChanged != null) - OnOpenChanged(this, flyoutEventArgs); + OnOpenChanged?.Invoke(this, flyoutEventArgs); if (flyoutAction == FlyoutAction.Opening) - if (OnOpened != null) - OnOpened(this, flyoutEventArgs); + OnOpened?.Invoke(this, flyoutEventArgs); if (flyoutAction == FlyoutAction.Closing) - if (OnClosed != null) - OnClosed(this, flyoutEventArgs); + OnClosed?.Invoke(this, flyoutEventArgs); } /// diff --git a/AdamController.Core/FlayoutsRegionNames.cs b/AdamController.Core/FlayoutsRegionNames.cs deleted file mode 100644 index 0c1892e..0000000 --- a/AdamController.Core/FlayoutsRegionNames.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace AdamController.Core -{ - public class FlayoutsRegionNames - { - public const string FlayoutsInsideRegion = $"{nameof(FlayoutsInsideRegion)}"; - public const string FlayotAdvancedBlocklySettings = $"{nameof(FlayotAdvancedBlocklySettings)}"; - public const string FlayoutNotification = $"{nameof(FlayoutNotification)}"; - } -} diff --git a/AdamController.Core/FlyoutNames.cs b/AdamController.Core/FlyoutNames.cs new file mode 100644 index 0000000..870af35 --- /dev/null +++ b/AdamController.Core/FlyoutNames.cs @@ -0,0 +1,11 @@ +namespace AdamController.Core +{ + /// + /// + /// + public class FlyoutNames + { + public const string FlyotAdvancedBlocklySettings = "AdvancedBlocklySettingsView"; + public const string FlyoutNotification = "NotificationView"; + } +} diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index e935bf7..14ce19f 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -5,7 +5,6 @@ using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Core.Properties; -using AdamController.Services.Interfaces; using ControlzEx.Theming; using Prism.Commands; using Prism.Regions; @@ -182,8 +181,7 @@ public double NotificationOpacity private DelegateCommand openAdvancedBlocklySettingsCommand; public DelegateCommand OpenAdvancedBlocklySettingsCommand => openAdvancedBlocklySettingsCommand ??= new DelegateCommand(() => { - FlyoutManager.OpenFlyout("FlayoutsView"); - //RegionManager.RequestNavigate(RegionNames.FlayoutsRegion, FlayoutsRegionNames.FlayotAdvancedBlocklySettings); + FlyoutManager.OpenFlyout(FlyoutNames.FlyotAdvancedBlocklySettings); }); private DelegateCommand changeBaseColorTheme; diff --git a/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs b/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs index addcda3..b6c72f7 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/FlayoutsRegionModule.cs @@ -3,36 +3,24 @@ using AdamController.Modules.FlayoutsRegion.Views; using Prism.Ioc; using Prism.Modularity; -using Prism.Regions; namespace AdamController.Modules.FlayoutsRegion { public class FlayoutsRegionModule : IModule { - private readonly IRegionManager mRegionManager; private readonly IFlyoutManager mFlyoutManager; - public FlayoutsRegionModule(IRegionManager regionManager, IFlyoutManager flyoutManager) + public FlayoutsRegionModule(IFlyoutManager flyoutManager) { - mRegionManager = regionManager; mFlyoutManager = flyoutManager; } - public void OnInitialized(IContainerProvider containerProvider) - { - //mRegionManager.RequestNavigate(RegionNames.FlayoutsRegion, nameof(FlayoutsView)); - } + public void OnInitialized(IContainerProvider containerProvider){} public void RegisterTypes(IContainerRegistry containerRegistry) { - - //containerRegistry.RegisterForNavigation(nameof(FlayoutsView)); - - mFlyoutManager.RegisterFlyout("FlayoutsView", RegionNames.FlayoutsRegion); - //mFlyoutManager.RegisterFlyout("AdvancedBlocklySettingsView", FlayoutsRegionNames.FlayotAdvancedBlocklySettings); - - //containerRegistry.RegisterForNavigation(nameof(NotificationView)); - //containerRegistry.RegisterForNavigation(nameof(AdvancedBlocklySettingsView)); + mFlyoutManager.RegisterFlyout(nameof(AdvancedBlocklySettingsView), RegionNames.FlayoutsRegion); + mFlyoutManager.RegisterFlyout(nameof(NotificationView), RegionNames.FlayoutsRegion); } } } \ No newline at end of file diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs index ff01afa..387fbc9 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs @@ -1,85 +1,34 @@ -using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; +using AdamBlocklyLibrary.Enum; +using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; +using AdamController.Core.DataSource; +using AdamController.Core.Model; +using AdamController.Core.Properties; +using Prism.Commands; +using System.Collections.ObjectModel; +using System.Linq; +using System.Windows.Media; + namespace AdamController.Modules.FlayoutsRegion.ViewModels { - public class AdvancedBlocklySettingsViewModel : FlyoutBase //: RegionViewModelBase + public class AdvancedBlocklySettingsViewModel : FlyoutBase { - //private IFlayoutsRegionChangeOpenedAwareService FlayoutsRegionChangeOpenedService { get; } - public AdvancedBlocklySettingsViewModel() { - Position = FlyoutPosition.Right; - Theme = FlyoutTheme.Accent; - //FlayoutsRegionChangeOpenedService = flayoutsRegionChangeOpenedAwareService; - } - - protected override void OnChanging(bool isOpening) - { - base.OnChanging(isOpening); + Header = "Продвинутые настройки скретч-редактора"; + } protected override void OnOpening(FlyoutParameters flyoutParameters) { - // Because FlyoutParameters provides weakly-typed objects we need to cast the provided "dog" parameter as a Dog type - // Dog = flyoutParameters["dog"] as Dog; - - // We can set the Flyout name based on information passed via flyoutParameters - //Header = "Editing " + Dog.Name; - - // As well as setting the position - // if (Dog.Name == "Patch") - // Position = FlyoutPosition.Left; - // else - // Position = FlyoutPosition.Right; - - // And any other property you like. See the full list in the code wiki at flyoutmanager.codeplex.com - } - - #region Navigation - - /*public override void OnNavigatedFrom(NavigationContext navigationContext) - { - AdvancedBlocklySettingsFlayoutsIsOpen = false; - //FlayoutsRegionChangeOpenedService.RaiseAdvancedBlocklySettingsIsOpenChange -= RaiseAdvancedBlocklySettingsIsOpenChange; - }*/ - - /*public override void OnNavigatedTo(NavigationContext navigationContext) - { - AdvancedBlocklySettingsFlayoutsIsOpen = true; - //FlayoutsRegionChangeOpenedService.RaiseAdvancedBlocklySettingsIsOpenChange += RaiseAdvancedBlocklySettingsIsOpenChange; - - }*/ - - #endregion - - #region Fields - - private bool advancedBlocklySettingsFlayoutsIsOpen; - public bool AdvancedBlocklySettingsFlayoutsIsOpen - { - get { return advancedBlocklySettingsFlayoutsIsOpen; } - set - { - if (value == advancedBlocklySettingsFlayoutsIsOpen) - return; - - advancedBlocklySettingsFlayoutsIsOpen = value; - SetProperty(ref advancedBlocklySettingsFlayoutsIsOpen, value); - } + base.OnOpening(flyoutParameters); } - #endregion - - #region Raise events - - private void RaiseAdvancedBlocklySettingsIsOpenChange(object sender) + protected override void OnClosing(FlyoutParameters flyoutParameters) { - //AdvancedBlocklySettingsFlayoutsIsOpen = FlayoutsRegionChangeOpenedService.AdvancedBlocklySettingsIsOpen; + base.OnClosing(flyoutParameters); } - #endregion -/* - #region BlocklyGridColour settings private Color? selectedBlocklyGridColour = MahApps.Metro.Controls.ColorHelper.ColorFromString(Settings.Default.BlocklyGridColour); @@ -194,7 +143,6 @@ private void SelectGridColorDependingSelectedTheme(BlocklyTheme theme) }); - private DelegateCommand changeGridColorToggleSwitchCommand; public DelegateCommand ChangeGridColorToggleSwitchCommand => changeGridColorToggleSwitchCommand ??= new DelegateCommand(obj => { @@ -239,8 +187,6 @@ private void SelectGridColorDependingSelectedTheme(BlocklyTheme theme) }); #endregion - - */ } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs deleted file mode 100644 index 851d651..0000000 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/FlayoutsViewModel.cs +++ /dev/null @@ -1,58 +0,0 @@ -using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; -using AdamController.Controls.CustomControls.Services; -using AdamController.Core; -using Prism.Regions; - -namespace AdamController.Modules.FlayoutsRegion.ViewModels -{ - public class FlayoutsViewModel : FlyoutBase//: RegionViewModelBase - { - IFlyoutManager FlyoutManager { get; } - - - public FlayoutsViewModel() - { - Position = FlyoutPosition.Right; - Theme = FlyoutTheme.Dark; - } - - //public FlayoutsViewModel(IRegionManager regionManager, IDialogService dialogService, FlyoutManager flyoutManager) : base(regionManager, dialogService) - //{ - // FlyoutManager = flyoutManager; - // - // FlyoutManager.SetDefaultFlyoutRegion(FlayoutsRegionNames.FlayoutsInsideRegion); - //} - - - - //public FlayoutsViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager) : base(regionManager, dialogService) - //{ - // FlyoutManager = flyoutManager; - //} - - //public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) - //{ - // SubFlayoutsRequestNavigate(FlayoutsRegionNames.FlayotAdvancedBlocklySettings, navigationContext.Parameters); - //} - - //public override void OnNavigatedTo(NavigationContext navigationContext) - //{ - - //} - - private void SubFlayoutsRequestNavigate(string uri, NavigationParameters parameters) - { - if (string.IsNullOrEmpty(uri)) - return; - - - switch (uri) - { - case FlayoutsRegionNames.FlayotAdvancedBlocklySettings: - //RegionManager.RequestNavigate(FlayoutsRegionNames.FlayoutsInsideRegion, nameof(AdvancedBlocklySettingsView), parameters); - break; - - } - } - } -} diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index b5a8c24..fe4e9e4 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -1,7 +1,9 @@ -using AdamController.Core.Helpers; +using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; +using AdamController.Core.Helpers; using AdamController.Core.Mvvm; using AdamController.Core.Properties; using AdamController.Services.Interfaces; +using LibVLCSharp.Shared; using MahApps.Metro.IconPacks; using Prism.Commands; using Prism.Regions; @@ -11,7 +13,7 @@ namespace AdamController.Modules.FlayoutsRegion.ViewModels { - public class NotificationViewModel : RegionViewModelBase + public class NotificationViewModel : FlyoutBase { #region Const @@ -22,10 +24,17 @@ public class NotificationViewModel : RegionViewModelBase #endregion - public NotificationViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) + #region ~ + + public NotificationViewModel() { + Theme = FlyoutTheme.Inverse; + Header= "Центр уведомлений"; + IsModal = false; } + #endregion + #region Fields private bool mNotificationFlayoutsIsOpen; diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/AdvancedBlocklySettingsView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/AdvancedBlocklySettingsView.xaml index 28b219a..d3acb00 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/AdvancedBlocklySettingsView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/AdvancedBlocklySettingsView.xaml @@ -12,53 +12,38 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - - - Red - Green - Blue - Black - Yellow - White - Gray - + Red + Green + Blue + Black + Yellow + White + Gray + - - + - + - - - Red - Green - Blue - Black - Yellow - White - Gray - + Red + Green + Blue + Black + Yellow + White + Gray + - - + - + - - - Red - Green - Blue - Black - Yellow - White - Gray - + Red + Green + Blue + Black + Yellow + White + Gray + - - + - + - - - Red - Green - Blue - Black - Yellow - White - Gray - + Red + Green + Blue + Black + Yellow + White + Gray + - - + - + - - - Red - Green - Blue - Black - Yellow - White - Gray - + Red + Green + Blue + Black + Yellow + White + Gray + - - + - + - - - Red - Green - Blue - Black - Yellow - White - Gray - + Red + Green + Blue + Black + Yellow + White + Gray + - - + - + - - - Red - Green - Blue - Black - Yellow - White - Gray - + Red + Green + Blue + Black + Yellow + White + Gray + - - + - + - - - Red - Green - Blue - Black - Yellow - White - Gray - + Red + Green + Blue + Black + Yellow + White + Gray + - - + - + - - + - - - - - - - + + + + + + - + - - + - - + - - Red - Green - Blue - Black - Yellow - White - Gray + Red + Green + Blue + Black + Yellow + White + Gray - - - - - - - + + + + + + + - + - + - - + - - - - - - - + + + + + + - + - + - Отображение сетки отключено в основных настройках. Включить... - + - + - - + - - - - - - - + + + + + + - + - - - - - - - + + diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml deleted file mode 100644 index 25ba18c..0000000 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml.cs b/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml.cs deleted file mode 100644 index 6fa4465..0000000 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/FlayoutsView.xaml.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Windows.Controls; - -namespace AdamController.Modules.FlayoutsRegion.Views -{ - public partial class FlayoutsView : UserControl - { - public FlayoutsView() - { - InitializeComponent(); - } - } -} diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml index 82a3992..d560710 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml @@ -6,74 +6,56 @@ xmlns:local="clr-namespace:AdamController.Modules.FlayoutsRegion.Views" xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks" - mc:Ignorable="d" - d:DesignHeight="450" d:DesignWidth="800"> + xmlns:prism="http://prismlibrary.com/" + prism:ViewModelLocator.AutoWireViewModel="True" + > - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - + + - + - - + - + - - - - - - - + + + + + + + - + - + - - - + + diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index 0874ca7..c4bed5a 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -1,4 +1,6 @@ -using AdamController.Core.Mvvm; +using AdamController.Controls.CustomControls.Services; +using AdamController.Core; +using AdamController.Core.Mvvm; using AdamController.Services.Interfaces; using MahApps.Metro.IconPacks; using Prism.Commands; @@ -9,13 +11,26 @@ namespace AdamController.Modules.StatusBarRegion.ViewModels { public class StatusBarViewModel : RegionViewModelBase { + + #region Services + + private IFlyoutManager mFlyoutManager; + + #endregion + + #region const + private const string mToolbarStatusClientDisconnected = "Робот Адам: отключен"; private const string mToolbarStatusClientConnected = "Робот Адам: подключен"; private const string mToolbarStatusClientReconnected = "Робот Адам: переподключение"; - public StatusBarViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) + #endregion + + + + public StatusBarViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager) : base(regionManager, dialogService) { - + mFlyoutManager = flyoutManager; } #region ProgressRing field @@ -158,7 +173,7 @@ public bool NotificationFlayoutsIsOpen private DelegateCommand openNotificationPanel; public DelegateCommand OpenNotificationPanel => openNotificationPanel ??= new DelegateCommand(obj => { - NotificationFlayoutsIsOpen = !NotificationFlayoutsIsOpen; + mFlyoutManager.OpenFlyout(FlyoutNames.FlyoutNotification); }); #endregion From 17bac6c0034e6fccf925176243951ea4b6735899 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 8 Apr 2024 15:37:04 +1000 Subject: [PATCH 069/181] Close #14 --- AdamController.Services/AdamController.Services.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/AdamController.Services/AdamController.Services.csproj b/AdamController.Services/AdamController.Services.csproj index 3560d0f..d25918a 100644 --- a/AdamController.Services/AdamController.Services.csproj +++ b/AdamController.Services/AdamController.Services.csproj @@ -2,7 +2,6 @@ net7.0-windows - true From be07749396742d26baf7e4e0d42816d826ab0e9c Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Tue, 9 Apr 2024 13:21:40 +1000 Subject: [PATCH 070/181] StatusBarViewModel fixed according to Code of Conduct #10 --- .../ViewModels/NotificationViewModel.cs | 41 +------ .../Views/NotificationView.xaml | 5 - .../ViewModels/StatusBarViewModel.cs | 116 +++++++++--------- .../Views/StatusBarView.xaml | 37 +++--- 4 files changed, 79 insertions(+), 120 deletions(-) diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index fe4e9e4..e2a97d4 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -1,13 +1,8 @@ using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; using AdamController.Core.Helpers; -using AdamController.Core.Mvvm; using AdamController.Core.Properties; -using AdamController.Services.Interfaces; -using LibVLCSharp.Shared; using MahApps.Metro.IconPacks; using Prism.Commands; -using Prism.Regions; -using Prism.Services.Dialogs; using System.Windows; using System.Windows.Threading; @@ -15,12 +10,11 @@ namespace AdamController.Modules.FlayoutsRegion.ViewModels { public class NotificationViewModel : FlyoutBase { - #region Const - private const string mConnectButtonStatusDisconnected = "Подключить"; - private const string mConnectButtonStatusConnected = "Отключить"; - private const string mConnectButtonStatusReconnected = "Подождите"; + private const string cConnectButtonStatusDisconnected = "Подключить"; + private const string cConnectButtonStatusConnected = "Отключить"; + private const string cConnectButtonStatusReconnected = "Подождите"; #endregion @@ -35,25 +29,6 @@ public NotificationViewModel() #endregion - #region Fields - - private bool mNotificationFlayoutsIsOpen; - public bool NotificationFlayoutsIsOpen - { - get { return mNotificationFlayoutsIsOpen; } - set - { - if (mNotificationFlayoutsIsOpen == value) - return; - - mNotificationFlayoutsIsOpen = value; - - SetProperty(ref mNotificationFlayoutsIsOpen, value); - } - } - - #endregion - #region NotificationMessage Visiblity private Visibility noNewNotificationMessageVisibility = Visibility.Visible; @@ -108,8 +83,9 @@ public double NotificationOpacity #endregion - #region NotificationBadge + #region NotificationBadge + /* #16 */ private void ClearNotification() { //BadgeCounter = 0; @@ -154,6 +130,7 @@ public PackIconMaterialKind IconOnConnectFlayoutButton public DelegateCommand ConnectButtonComand => connectButtonComand ??= new DelegateCommand(async () => { bool isNotifyButton = false; //(string)obj == "IsNotificationButtonCalling"; + if (isNotifyButton) { ClearNotification(); @@ -186,12 +163,6 @@ public PackIconMaterialKind IconOnConnectFlayoutButton ClearNotification(); }); - private DelegateCommand closeNotificationFlayots; - public DelegateCommand CloseNotificationFlayots => closeNotificationFlayots ??= new DelegateCommand(() => - { - //NotificationFlayoutsIsOpen = false; - }); - #endregion } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml index d560710..5037bfe 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml @@ -11,8 +11,6 @@ > - - @@ -148,8 +146,5 @@ - - - diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index c4bed5a..e2cd75f 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -1,7 +1,6 @@ using AdamController.Controls.CustomControls.Services; using AdamController.Core; using AdamController.Core.Mvvm; -using AdamController.Services.Interfaces; using MahApps.Metro.IconPacks; using Prism.Commands; using Prism.Regions; @@ -11,34 +10,46 @@ namespace AdamController.Modules.StatusBarRegion.ViewModels { public class StatusBarViewModel : RegionViewModelBase { + #region DelegateCommands + + public DelegateCommand OpenNotificationPanelDelegateCommand { get; } + + #endregion #region Services - private IFlyoutManager mFlyoutManager; + private readonly IFlyoutManager mFlyoutManager; #endregion - #region const + #region Const - private const string mToolbarStatusClientDisconnected = "Робот Адам: отключен"; - private const string mToolbarStatusClientConnected = "Робот Адам: подключен"; - private const string mToolbarStatusClientReconnected = "Робот Адам: переподключение"; + private const string cTextOnStatusConnectToolbarDisconnected = "Робот Адам: отключен"; + private const string cTextOnStatusConnectToolbarConnected = "Робот Адам: подключен"; + private const string cTextOnStatusConnectToolbarReconnected = "Робот Адам: переподключение"; - #endregion + private const string cCompileLogStatusBar = "Лог робота"; + private const string cAppLogStatusBar = "Лог приложения"; + #endregion + #region ~ public StatusBarViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager) : base(regionManager, dialogService) { mFlyoutManager = flyoutManager; + + OpenNotificationPanelDelegateCommand = new DelegateCommand(OpenNotificationPanel, OpenNotificationPanelCanExecute); } - #region ProgressRing field + #endregion + + #region public fields - private bool progressRingStart = false; + private bool progressRingStart; public bool ProgressRingStart { - get => progressRingStart; + get { return progressRingStart; } set { if (value == progressRingStart) return; @@ -48,15 +59,10 @@ public bool ProgressRingStart } } - - #endregion - - #region CompileLogStatusBar field - - private string compileLogStatusBar = "Лог робота"; + private string compileLogStatusBar = cCompileLogStatusBar; public string CompileLogStatusBar { - get => compileLogStatusBar; + get { return compileLogStatusBar; } set { if (value == compileLogStatusBar) @@ -69,14 +75,10 @@ public string CompileLogStatusBar } } - #endregion - - #region AppStatusBar field - - private string appLogStatusBar = "Лог приложения"; + private string appLogStatusBar = cAppLogStatusBar; public string AppLogStatusBar { - get => appLogStatusBar; + get { return appLogStatusBar; } set { if (value == appLogStatusBar) @@ -89,12 +91,10 @@ public string AppLogStatusBar } } - #endregion - private PackIconModernKind connectIcon = PackIconModernKind.Connect; public PackIconModernKind ConnectIcon { - get => connectIcon; + get { return connectIcon; } set { if (value == connectIcon) return; @@ -104,11 +104,10 @@ public PackIconModernKind ConnectIcon } } - - private string textOnStatusConnectToolbar; + private string textOnStatusConnectToolbar = cTextOnStatusConnectToolbarDisconnected; public string TextOnStatusConnectToolbar { - get => textOnStatusConnectToolbar; + get { return textOnStatusConnectToolbar; } set { if (value == textOnStatusConnectToolbar) return; @@ -118,30 +117,10 @@ public string TextOnStatusConnectToolbar } } - private int badgeCounter = 0; - private int BadgeCounter - { - get => badgeCounter; - set - { - if (value == badgeCounter) return; - if (value == 0) - { - badgeCounter = value; - NotificationBadge = ""; - return; - } - - badgeCounter = value; - - NotificationBadge = $"{BadgeCounter}"; - } - } - private string notificationBadge; public string NotificationBadge { - get => notificationBadge; + get { return notificationBadge; } set { if (value == notificationBadge) return; @@ -151,31 +130,46 @@ public string NotificationBadge } } - #region Open NotificationFlayouts + #endregion + + #region Private fields - private bool notificationFlayoutsIsOpen; - public bool NotificationFlayoutsIsOpen + private int badgeCounter = 0; + private int BadgeCounter { - get { return notificationFlayoutsIsOpen; } + get { return badgeCounter; } set { - if (value == notificationFlayoutsIsOpen) return; + if (value == badgeCounter) return; + + if (value == 0) + { + badgeCounter = value; + NotificationBadge = ""; + return; + } + + badgeCounter = value; - notificationFlayoutsIsOpen = value; - SetProperty(ref notificationFlayoutsIsOpen, value); + NotificationBadge = $"{BadgeCounter}"; } } #endregion - #region Commands + #region DelegateCommands methods - private DelegateCommand openNotificationPanel; - public DelegateCommand OpenNotificationPanel => openNotificationPanel ??= new DelegateCommand(obj => + private void OpenNotificationPanel() { mFlyoutManager.OpenFlyout(FlyoutNames.FlyoutNotification); - }); + } + + private bool OpenNotificationPanelCanExecute() + { + return true; + } #endregion + } } diff --git a/Modules/AdamController.Modules.StatusBar/Views/StatusBarView.xaml b/Modules/AdamController.Modules.StatusBar/Views/StatusBarView.xaml index 086a486..6d6265d 100644 --- a/Modules/AdamController.Modules.StatusBar/Views/StatusBarView.xaml +++ b/Modules/AdamController.Modules.StatusBar/Views/StatusBarView.xaml @@ -102,43 +102,42 @@ + VerticalAlignment="Center" + FontWeight="Medium" + Text="{Binding TextOnStatusConnectToolbar, Mode=TwoWay}" /> + Margin="5 0 5 0" + Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}" + Style="{StaticResource MahApps.Styles.Separator.StatusBar}"/> + Margin="0 8 5 0" + BadgeBackground="Red" + BadgePlacementMode="TopRight" + Badge="{Binding NotificationBadge}"> + Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}" + Style="{StaticResource MahApps.Styles.Separator.StatusBar}"/> From b1ec7b906350f72201f1788e177d5e62256fc4b5 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Wed, 10 Apr 2024 10:13:16 +1000 Subject: [PATCH 071/181] Close #19 --- .../Helpers/ComunicateHelper.cs | 64 ++++---- .../AdamTcpClientService.cs | 15 +- .../CommunicationProviderService.cs | 152 ++++++++++++++++++ .../Interfaces/IAdamTcpClientService.cs | 8 +- .../ICommunicationProviderService.cs | 39 +++++ .../ISubRegionChangeAwareService.cs | 15 +- .../SubRegionChangeAwareService.cs | 2 + AdamController/App.xaml.cs | 121 ++++++++++++-- .../ViewModels/NotificationViewModel.cs | 4 +- 9 files changed, 360 insertions(+), 60 deletions(-) create mode 100644 AdamController.Services/CommunicationProviderService.cs create mode 100644 AdamController.Services/Interfaces/ICommunicationProviderService.cs diff --git a/AdamController.Core/Helpers/ComunicateHelper.cs b/AdamController.Core/Helpers/ComunicateHelper.cs index 2c11929..6607d4d 100644 --- a/AdamController.Core/Helpers/ComunicateHelper.cs +++ b/AdamController.Core/Helpers/ComunicateHelper.cs @@ -46,16 +46,16 @@ static ComunicateHelper() private static void LazyInitializer() { - if(mAdamTcpClient == null) - { - AdamTcpClientOption option = new() - { - ReconnectCount = Settings.Default.ReconnectQtyComunicateTcpClient, - ReconnectTimeout = Settings.Default.ReconnectTimeoutComunicateTcpClient - }; + //if(mAdamTcpClient == null) + //{ + //AdamTcpClientOption option = new() + //{ + // ReconnectCount = Settings.Default.ReconnectQtyComunicateTcpClient, + // ReconnectTimeout = Settings.Default.ReconnectTimeoutComunicateTcpClient + //}; - mAdamTcpClient = new(Settings.Default.ServerIP, Settings.Default.TcpConnectStatePort, option); - } + //mAdamTcpClient = new(Settings.Default.ServerIP, Settings.Default.TcpConnectStatePort, option); + //} mAdamUdpMessageClient ??= new(IPAddress.Any, int.Parse(Settings.Default.MessageDataExchangePort)) { @@ -76,11 +76,11 @@ private static void LazyInitializer() #endif - mAdamTcpClient.RaiseTcpCientConnected += TcpCientConnected; - mAdamTcpClient.RaiseTcpClientDisconnected += TcpClientDisconnected; - mAdamTcpClient.RaiseTcpClientError += TcpClientError; - mAdamTcpClient.RaiseTcpClientReceived += TcpClientReceived; - mAdamTcpClient.RaiseTcpClientReconnected += TcpClientReconnected; + //mAdamTcpClient.RaiseTcpCientConnected += TcpCientConnected; + //mAdamTcpClient.RaiseTcpClientDisconnected += TcpClientDisconnected; + //mAdamTcpClient.RaiseTcpClientError += TcpClientError; + //mAdamTcpClient.RaiseTcpClientReceived += TcpClientReceived; + //mAdamTcpClient.RaiseTcpClientReconnected += TcpClientReconnected; mAdamWebSocketClient.WebSocketConnectedEvent += WebSocketConnectedEvent; mAdamWebSocketClient.WebSocketClientReceivedEvent += WebSocketClientReceived; @@ -166,32 +166,32 @@ private static void TcpClientReconnected(object sender, int reconnectCount) #region Tcp/Udp connect - private static void Connect() - { - _ = Task.Run(() => mAdamTcpClient?.ConnectAsync()); - _ = Task.Run(() => mAdamUdpMessageClient?.Start()); - _ = Task.Run(() => mAdamWebSocketClient?.ConnectAsync()); - } - - public static void ConnectAllAsync() - { - _ = Task.Run(() => Connect()); - } + //private static void Connect() + //{ + //_ = Task.Run(() => mAdamTcpClient?.ConnectAsync()); + //_ = Task.Run(() => mAdamUdpMessageClient?.Start()); + //_ = Task.Run(() => mAdamWebSocketClient?.ConnectAsync()); + //} + + //public static void ConnectAllAsync() + //{ + //_ = Task.Run(() => Connect()); + //} #endregion # region Tcp/Upd disconnect - public static void DisconnectAll() - { - _ = Task.Run(()=> mAdamTcpClient?.DisconnectAndStop()); - _ = Task.Run(() => mAdamUdpMessageClient?.Stop()); - _ = Task.Run(() => mAdamWebSocketClient?.DisconnectAsync()); - } + //public static void DisconnectAll() + //{ + //_ = Task.Run(()=> mAdamTcpClient?.DisconnectAndStop()); + //_ = Task.Run(() => mAdamUdpMessageClient?.Stop()); + //_ = Task.Run(() => mAdamWebSocketClient?.DisconnectAsync()); + //} public static void DisconnectAllAndDestroy() { - DisconnectAll(); + //DisconnectAll(); if(mAdamTcpClient != null) { diff --git a/AdamController.Services/AdamTcpClientService.cs b/AdamController.Services/AdamTcpClientService.cs index 9a0a9ff..5deed36 100644 --- a/AdamController.Services/AdamTcpClientService.cs +++ b/AdamController.Services/AdamTcpClientService.cs @@ -167,44 +167,43 @@ protected override void OnError(SocketError error) protected override void OnReceived(byte[] buffer, long offset, long size) { OnRaiseTcpClientReceived(buffer, offset, size); - } #endregion - #region RaiseEvents + #region OnRaiseEvents - public virtual void OnRaiseTcpCientConnected() + protected virtual void OnRaiseTcpCientConnected() { TcpCientConnected raiseEvent = RaiseTcpCientConnected; raiseEvent?.Invoke(this); } - public virtual void OnRaiseTcpCientSent(long sent, long pending) + protected virtual void OnRaiseTcpCientSent(long sent, long pending) { TcpCientSent raiseEvent = RaiseTcpCientSent; raiseEvent?.Invoke(this, sent, pending); } - public virtual void OnRaiseTcpClientDisconnected() + protected virtual void OnRaiseTcpClientDisconnected() { TcpClientDisconnect raiseEvent = RaiseTcpClientDisconnected; raiseEvent?.Invoke(this); } - public virtual void OnRaiseTcpClientError(SocketError socketError) + protected virtual void OnRaiseTcpClientError(SocketError socketError) { TcpClientError raiseEvent = RaiseTcpClientError; raiseEvent?.Invoke(this, socketError); } - public virtual void OnRaiseTcpClientReceived(byte[] buffer, long offset, long size) + protected virtual void OnRaiseTcpClientReceived(byte[] buffer, long offset, long size) { TcpClientReceived raiseEvent = RaiseTcpClientReceived; raiseEvent?.Invoke(this, buffer, offset, size); } - public virtual void OnRaiseTcpClientReconnected(int reconnectCount) + protected virtual void OnRaiseTcpClientReconnected(int reconnectCount) { TcpClientReconnected raiseEvent = RaiseTcpClientReconnected; raiseEvent?.Invoke(this, reconnectCount); diff --git a/AdamController.Services/CommunicationProviderService.cs b/AdamController.Services/CommunicationProviderService.cs new file mode 100644 index 0000000..6c7fa06 --- /dev/null +++ b/AdamController.Services/CommunicationProviderService.cs @@ -0,0 +1,152 @@ +using AdamController.Services.Interfaces; +using System.Threading.Tasks; + +namespace AdamController.Services +{ + public class CommunicationProviderService : ICommunicationProviderService + { + #region Events + + public event AdamTcpCientConnected RaiseAdamTcpCientConnected; + public event AdamTcpClientDisconnect RaiseAdamTcpClientDisconnect; + public event AdamTcpClientReconnected RaiseAdamTcpClientReconnected; + public event AdamUdpServerReceived RaiseAdamUdpServerReceived; + public event AdamUdpMessageReceived RaiseAdamUdpMessageReceived; + + #endregion + + #region Services + + IAdamTcpClientService mAdamTcpClientService; + + #endregion + + public CommunicationProviderService(IAdamTcpClientService adamTcpClientService) + { + mAdamTcpClientService = adamTcpClientService; + + Subscribe(); + } + + #region Public methods + + public void ConnectAllAsync() + { + //_ = Task.Run(() => mAdamTcpClient?.ConnectAsync()); + //_ = Task.Run(() => mAdamUdpMessageClient?.Start()); + //_ = Task.Run(() => mAdamWebSocketClient?.ConnectAsync()); + } + + public void DisconnectAllAsync() + { + //_ = Task.Run(() => mAdamTcpClient?.DisconnectAndStop()); + //_ = Task.Run(() => mAdamUdpMessageClient?.Stop()); + //_ = Task.Run(() => mAdamWebSocketClient?.DisconnectAsync()); + } + + public void DisconnectAllAndDestroy() + { + ///throw new System.NotImplementedException(); + } + + public void Dispose() + { + Unsubscribe(); + } + + #endregion + + #region Private methods + + #endregion + + #region Subscriptions + + private void Subscribe() + { + mAdamTcpClientService.RaiseTcpClientReconnected += RaiseTcpClientReconnected; + mAdamTcpClientService.RaiseTcpCientConnected += RaiseTcpCientConnected; + mAdamTcpClientService.RaiseTcpClientDisconnected += RaiseTcpClientDisconnected; + } + + private void Unsubscribe() + { + mAdamTcpClientService.RaiseTcpClientReconnected -= RaiseTcpClientReconnected; + mAdamTcpClientService.RaiseTcpCientConnected -= RaiseTcpCientConnected; + mAdamTcpClientService.RaiseTcpClientDisconnected -= RaiseTcpClientDisconnected; + } + + #endregion + + #region Events methods + + private void RaiseTcpCientConnected(object sender) + { + //OnAdamTcpConnectedEvent?.Invoke(); + + //if (!mAdamUdpLogServer.IsStarted) + // mAdamUdpLogServer?.Start(); + + //if (!mAdamWebSocketClient.IsStarted) + //mAdamWebSocketClient.ConnectAsync(); + } + + private void RaiseTcpClientDisconnected(object sender) + { + //OnAdamTcpDisconnectedEvent?.Invoke(); + + //if (mAdamUdpLogServer != null) + //{ + // if (mAdamUdpLogServer.IsStarted) + // mAdamUdpLogServer?.Stop(); + //} + + //if (mAdamWebSocketClient != null) + //{ + //if (mAdamWebSocketClient.IsRunning) + // mAdamWebSocketClient.DisconnectAsync(); + //} + } + + private void RaiseTcpClientReconnected(object sender, int reconnectCount) + { + //OnAdamTcpReconnected?.Invoke(reconnectCount); + } + + #endregion + + #region OnRaise events + + protected virtual void OnRaiseAdamTcpCientConnected() + { + AdamTcpCientConnected raiseEvent = RaiseAdamTcpCientConnected; + raiseEvent.Invoke(this); + } + + protected virtual void OnRaiseAdamTcpClientDisconnect() + { + AdamTcpClientDisconnect raiseEvent = RaiseAdamTcpClientDisconnect; + raiseEvent.Invoke(this); + } + + public virtual void OnRaiseAdamTcpClientReconnected(int reconnectCounter) + { + AdamTcpClientReconnected raiseEvent = RaiseAdamTcpClientReconnected; + raiseEvent.Invoke(this, reconnectCounter); + } + + protected virtual void OnRaiseAdamUdpServerReceived() + { + AdamUdpServerReceived raiseEvent = RaiseAdamUdpServerReceived; + raiseEvent.Equals(this); + } + + protected virtual void OnRaiseAdamUdpMessageReceived(string message) + { + AdamUdpMessageReceived raiseEvent = RaiseAdamUdpMessageReceived; + raiseEvent.Invoke(this, message); + } + + #endregion + } +} diff --git a/AdamController.Services/Interfaces/IAdamTcpClientService.cs b/AdamController.Services/Interfaces/IAdamTcpClientService.cs index cb3ae81..092bcae 100644 --- a/AdamController.Services/Interfaces/IAdamTcpClientService.cs +++ b/AdamController.Services/Interfaces/IAdamTcpClientService.cs @@ -1,8 +1,9 @@ -using System.Net.Sockets; +using System; +using System.Net.Sockets; namespace AdamController.Services.Interfaces { - #region Events + #region Delegate public delegate void TcpCientConnected(object sender); public delegate void TcpCientSent(object sender, long sent, long pending); @@ -13,8 +14,9 @@ namespace AdamController.Services.Interfaces #endregion - public interface IAdamTcpClientService + public interface IAdamTcpClientService : IDisposable { + #region Events public event TcpCientConnected RaiseTcpCientConnected; diff --git a/AdamController.Services/Interfaces/ICommunicationProviderService.cs b/AdamController.Services/Interfaces/ICommunicationProviderService.cs new file mode 100644 index 0000000..04be001 --- /dev/null +++ b/AdamController.Services/Interfaces/ICommunicationProviderService.cs @@ -0,0 +1,39 @@ +using System; +using System.Net.Sockets; + +namespace AdamController.Services.Interfaces +{ + #region Delegate + + public delegate void AdamTcpCientConnected(object sender); + public delegate void AdamTcpClientDisconnect(object sender); + public delegate void AdamTcpClientReconnected(object sender, int reconnectCounter); + public delegate void AdamUdpServerReceived(object sender, string message); + public delegate void AdamUdpMessageReceived(object sender, string message); + + #endregion + + /// + /// ComunicateHeleper functional + /// + public interface ICommunicationProviderService : IDisposable + { + #region Events + + public event AdamTcpCientConnected RaiseAdamTcpCientConnected; + public event AdamTcpClientDisconnect RaiseAdamTcpClientDisconnect; + public event AdamTcpClientReconnected RaiseAdamTcpClientReconnected; + public event AdamUdpServerReceived RaiseAdamUdpServerReceived; + public event AdamUdpMessageReceived RaiseAdamUdpMessageReceived; + + #endregion + + #region Public methods + + public void ConnectAllAsync(); + public void DisconnectAllAsync(); + public void DisconnectAllAndDestroy(); + + #endregion + } +} diff --git a/AdamController.Services/Interfaces/ISubRegionChangeAwareService.cs b/AdamController.Services/Interfaces/ISubRegionChangeAwareService.cs index fbdf6a3..a3ccf64 100644 --- a/AdamController.Services/Interfaces/ISubRegionChangeAwareService.cs +++ b/AdamController.Services/Interfaces/ISubRegionChangeAwareService.cs @@ -1,10 +1,21 @@ -namespace AdamController.Services.Interfaces +using System; + +namespace AdamController.Services.Interfaces { + #region Delegate + public delegate void SubRegionChangeEventHandler(object sender); - public interface ISubRegionChangeAwareService + #endregion + + public interface ISubRegionChangeAwareService : IDisposable { + #region Events + public event SubRegionChangeEventHandler RaiseSubRegionChangeEvent; + + #endregion + public string InsideRegionNavigationRequestName { get; set; } } } diff --git a/AdamController.Services/SubRegionChangeAwareService.cs b/AdamController.Services/SubRegionChangeAwareService.cs index 8b1a0bb..c63a061 100644 --- a/AdamController.Services/SubRegionChangeAwareService.cs +++ b/AdamController.Services/SubRegionChangeAwareService.cs @@ -24,5 +24,7 @@ protected virtual void OnRaiseRegionChangeEvent() SubRegionChangeEventHandler raiseEvent = RaiseSubRegionChangeEvent; raiseEvent?.Invoke(this); } + + public void Dispose(){} } } diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index b65ea4e..a806a23 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -44,6 +44,10 @@ using ControlzEx.Theming; using ICSharpCode.AvalonEdit.Highlighting; +using AdamController.Services.AdamTcpClientDependency; +using AdamController.Core.Properties; +using System.Diagnostics; +using System.Threading.Tasks; #endregion @@ -51,10 +55,18 @@ namespace AdamController { public partial class App : PrismApplication { + #region ~ + + public App() + { + SetupUnhandledExceptionHandling(); + } + + #endregion + protected override Window CreateShell() { MainWindow window = Container.Resolve(); - return window; } @@ -67,16 +79,16 @@ protected override void OnStartup(StartupEventArgs e) _ = FolderHelper.CreateAppDataFolder(); //TODO check theme before ChangeTheme - _ = ThemeManager.Current.ChangeTheme(this, $"{Core.Properties.Settings.Default.BaseTheme}.{Core.Properties.Settings.Default.ThemeColorScheme}", false); + _ = ThemeManager.Current.ChangeTheme(this, $"{Settings.Default.BaseTheme}.{Settings.Default.ThemeColorScheme}", false); - string ip = Core.Properties.Settings.Default.ServerIP; - int port = Core.Properties.Settings.Default.ApiPort; + string ip = Settings.Default.ServerIP; + int port = Settings.Default.ApiPort; Uri DefaultUri = new($"http://{ip}:{port}"); WebApi.Client.v1.BaseApi.SetApiClientUri(DefaultUri); - string login = Core.Properties.Settings.Default.ApiLogin; - string password = Core.Properties.Settings.Default.ApiPassword; + string login = Settings.Default.ApiLogin; + string password = Settings.Default.ApiPassword; WebApi.Client.v1.BaseApi.SetAuthenticationHeader(login, password); } @@ -96,8 +108,27 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return new FlyoutManager(container, regionManager); }); - //here must be ip/port - containerRegistry.RegisterSingleton(); + containerRegistry.RegisterSingleton(containerRegistry => + { + AdamTcpClientOption option = new() + { + ReconnectCount = Settings.Default.ReconnectQtyComunicateTcpClient, + ReconnectTimeout = Settings.Default.ReconnectTimeoutComunicateTcpClient + }; + + string ip = Settings.Default.ServerIP; + int port = Settings.Default.TcpConnectStatePort; + + AdamTcpClientService client = new(ip, port, option); + return client; + }); + + containerRegistry.RegisterSingleton(containerRegistry => + { + IAdamTcpClientService tcpClientService = containerRegistry.Resolve(); + CommunicationProviderService communicationProvider = new(tcpClientService); + return communicationProvider; + }); RegisterDialogs(containerRegistry); } @@ -120,14 +151,14 @@ protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) moduleCatalog.AddModule(); moduleCatalog.AddModule(); moduleCatalog.AddModule(); - moduleCatalog.AddModule(); + moduleCatalog.AddModule(); } private static void LoadHighlighting() { try { - using var stream = new MemoryStream(Core.Properties.Resource.AdamPython); + using var stream = new MemoryStream(Resource.AdamPython); using var reader = new XmlTextReader(stream); HighlightingManager.Instance.RegisterHighlighting("AdamPython", Array.Empty(), ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader, HighlightingManager.Instance)); @@ -140,11 +171,75 @@ private static void LoadHighlighting() protected override void OnExit(ExitEventArgs e) { - Core.Properties.Settings.Default.BaseTheme = ThemeManager.Current.DetectTheme(Current).BaseColorScheme; - Core.Properties.Settings.Default.ThemeColorScheme = ThemeManager.Current.DetectTheme(Current).ColorScheme; - Core.Properties.Settings.Default.Save(); + OnAppCrashOrExit(); base.OnExit(e); } + + private void OnAppCrashOrExit() + { + SaveSettiings(); + DisposeServices(); + Current.Shutdown(); + } + + private void SaveSettiings() + { + Settings.Default.BaseTheme = ThemeManager.Current.DetectTheme(Current).BaseColorScheme; + Settings.Default.ThemeColorScheme = ThemeManager.Current.DetectTheme(Current).ColorScheme; + Settings.Default.Save(); + } + + private void DisposeServices() + { + Container.Resolve().Dispose(); + Container.Resolve().Dispose(); + Container.Resolve().Dispose(); + } + + #region Intercepting Unhandled Exception + + private void SetupUnhandledExceptionHandling() + { + // Catch exceptions from all threads in the AppDomain. + AppDomain.CurrentDomain.UnhandledException += (sender, args) => + ShowUnhandledException(args.ExceptionObject as Exception, "AppDomain.CurrentDomain.UnhandledException", false); + + // Catch exceptions from each AppDomain that uses a task scheduler for async operations. + TaskScheduler.UnobservedTaskException += (sender, args) => + ShowUnhandledException(args.Exception, "TaskScheduler.UnobservedTaskException", false); + + // Catch exceptions from a single specific UI dispatcher thread. + Dispatcher.UnhandledException += (sender, args) => + { + // If we are debugging, let Visual Studio handle the exception and take us to the code that threw it. + if (!Debugger.IsAttached) + { + args.Handled = true; + ShowUnhandledException(args.Exception, "Dispatcher.UnhandledException", true); + } + }; + } + + private void ShowUnhandledException(Exception e, string unhandledExceptionType, bool promptUserForShutdown) + { + var messageBoxTitle = $"An unexpected error has occurred: {unhandledExceptionType}"; + var messageBoxMessage = $"The following exception occurred:\n\n{e}"; + var messageBoxButtons = MessageBoxButton.OK; + + if (promptUserForShutdown) + { + messageBoxMessage += "\n\nTo continue working, you need to exit the application. Can I do it now?"; + messageBoxButtons = MessageBoxButton.YesNo; + } + + // Let the user decide if the app should die or not (if applicable). + if (MessageBox.Show(messageBoxMessage, messageBoxTitle, messageBoxButtons) == MessageBoxResult.Yes) + { + OnAppCrashOrExit(); + } + } + + #endregion } } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index e2a97d4..ffcaa35 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -142,13 +142,13 @@ public PackIconMaterialKind IconOnConnectFlayoutButton if (ComunicateHelper.TcpClientIsConnected) { - ComunicateHelper.DisconnectAll(); + //ComunicateHelper.DisconnectAll(); return; } if (!ComunicateHelper.TcpClientIsConnected) { - ComunicateHelper.ConnectAllAsync(); + //ComunicateHelper.ConnectAllAsync(); return; } }); From e804717ad05c148e1b6fedc47287d597ab3634d1 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Wed, 10 Apr 2024 22:24:20 +1000 Subject: [PATCH 072/181] Preparatory work for #18 --- AdamController.Core/Mvvm/ViewModelBase.cs | 14 +-- .../CommunicationProviderService.cs | 28 ++--- .../Interfaces/IAdamTcpClientService.cs | 5 + .../ICommunicationProviderService.cs | 9 +- AdamController/App.xaml.cs | 21 ++++ .../ViewModels/MainWindowViewModel.cs | 109 ++++++++++-------- .../ViewModels/StatusBarViewModel.cs | 57 ++++----- 7 files changed, 145 insertions(+), 98 deletions(-) diff --git a/AdamController.Core/Mvvm/ViewModelBase.cs b/AdamController.Core/Mvvm/ViewModelBase.cs index bb0678c..29681c2 100644 --- a/AdamController.Core/Mvvm/ViewModelBase.cs +++ b/AdamController.Core/Mvvm/ViewModelBase.cs @@ -1,20 +1,12 @@ -using AdamController.Services.Interfaces; -using Prism.Mvvm; +using Prism.Mvvm; using Prism.Navigation; namespace AdamController.Core.Mvvm { public class ViewModelBase : BindableBase, IDestructible { - public event SubRegionChangeEventHandler RaiseRegionChangeEvent; + protected ViewModelBase() {} - protected ViewModelBase() - { - - } - - public void Destroy() - { - } + public virtual void Destroy() {} } } diff --git a/AdamController.Services/CommunicationProviderService.cs b/AdamController.Services/CommunicationProviderService.cs index 6c7fa06..e64bab8 100644 --- a/AdamController.Services/CommunicationProviderService.cs +++ b/AdamController.Services/CommunicationProviderService.cs @@ -17,7 +17,7 @@ public class CommunicationProviderService : ICommunicationProviderService #region Services - IAdamTcpClientService mAdamTcpClientService; + private readonly IAdamTcpClientService mAdamTcpClientService; #endregion @@ -32,25 +32,24 @@ public CommunicationProviderService(IAdamTcpClientService adamTcpClientService) public void ConnectAllAsync() { - //_ = Task.Run(() => mAdamTcpClient?.ConnectAsync()); + mAdamTcpClientService.ConnectAsync(); + //_ = Task.Run(); //_ = Task.Run(() => mAdamUdpMessageClient?.Start()); //_ = Task.Run(() => mAdamWebSocketClient?.ConnectAsync()); } public void DisconnectAllAsync() { - //_ = Task.Run(() => mAdamTcpClient?.DisconnectAndStop()); + _ = Task.Run(mAdamTcpClientService.DisconnectAndStop); //_ = Task.Run(() => mAdamUdpMessageClient?.Stop()); //_ = Task.Run(() => mAdamWebSocketClient?.DisconnectAsync()); } - public void DisconnectAllAndDestroy() - { - ///throw new System.NotImplementedException(); - } + public void DisconnectAllAndDestroy() {} public void Dispose() { + DisconnectAllAsync(); Unsubscribe(); } @@ -78,11 +77,12 @@ private void Unsubscribe() #endregion - #region Events methods + #region Event methods private void RaiseTcpCientConnected(object sender) { //OnAdamTcpConnectedEvent?.Invoke(); + OnRaiseAdamTcpCientConnected(); //if (!mAdamUdpLogServer.IsStarted) // mAdamUdpLogServer?.Start(); @@ -94,6 +94,7 @@ private void RaiseTcpCientConnected(object sender) private void RaiseTcpClientDisconnected(object sender) { //OnAdamTcpDisconnectedEvent?.Invoke(); + OnRaiseAdamTcpClientDisconnect(); //if (mAdamUdpLogServer != null) //{ @@ -111,6 +112,7 @@ private void RaiseTcpClientDisconnected(object sender) private void RaiseTcpClientReconnected(object sender, int reconnectCount) { //OnAdamTcpReconnected?.Invoke(reconnectCount); + OnRaiseAdamTcpClientReconnected(reconnectCount); } #endregion @@ -120,31 +122,31 @@ private void RaiseTcpClientReconnected(object sender, int reconnectCount) protected virtual void OnRaiseAdamTcpCientConnected() { AdamTcpCientConnected raiseEvent = RaiseAdamTcpCientConnected; - raiseEvent.Invoke(this); + raiseEvent?.Invoke(this); } protected virtual void OnRaiseAdamTcpClientDisconnect() { AdamTcpClientDisconnect raiseEvent = RaiseAdamTcpClientDisconnect; - raiseEvent.Invoke(this); + raiseEvent?.Invoke(this); } public virtual void OnRaiseAdamTcpClientReconnected(int reconnectCounter) { AdamTcpClientReconnected raiseEvent = RaiseAdamTcpClientReconnected; - raiseEvent.Invoke(this, reconnectCounter); + raiseEvent?.Invoke(this, reconnectCounter); } protected virtual void OnRaiseAdamUdpServerReceived() { AdamUdpServerReceived raiseEvent = RaiseAdamUdpServerReceived; - raiseEvent.Equals(this); + raiseEvent?.Equals(this); } protected virtual void OnRaiseAdamUdpMessageReceived(string message) { AdamUdpMessageReceived raiseEvent = RaiseAdamUdpMessageReceived; - raiseEvent.Invoke(this, message); + raiseEvent?.Invoke(this, message); } #endregion diff --git a/AdamController.Services/Interfaces/IAdamTcpClientService.cs b/AdamController.Services/Interfaces/IAdamTcpClientService.cs index 092bcae..951eb57 100644 --- a/AdamController.Services/Interfaces/IAdamTcpClientService.cs +++ b/AdamController.Services/Interfaces/IAdamTcpClientService.cs @@ -39,5 +39,10 @@ public interface IAdamTcpClientService : IDisposable public int ReconnectTimeout { get; } public void DisconnectAndStop(); + + /// + /// This method is implemented in NetCoreServer.TcpClient + /// + public bool ConnectAsync(); } } diff --git a/AdamController.Services/Interfaces/ICommunicationProviderService.cs b/AdamController.Services/Interfaces/ICommunicationProviderService.cs index 04be001..613943d 100644 --- a/AdamController.Services/Interfaces/ICommunicationProviderService.cs +++ b/AdamController.Services/Interfaces/ICommunicationProviderService.cs @@ -1,5 +1,4 @@ using System; -using System.Net.Sockets; namespace AdamController.Services.Interfaces { @@ -32,6 +31,14 @@ public interface ICommunicationProviderService : IDisposable public void ConnectAllAsync(); public void DisconnectAllAsync(); + + + /// + /// Left for backward compatibility + /// This is where events were unsubscribed, and instances of client classes were destroyed + /// This is now implemented in Dispose services + /// All calls to this method should be replaced with calls to DisconnectAllAsync() + /// public void DisconnectAllAndDestroy(); #endregion diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index a806a23..17682ef 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -48,6 +48,9 @@ using AdamController.Core.Properties; using System.Diagnostics; using System.Threading.Tasks; +using AdamController.ViewModels; +using AdamController.Core.Mvvm; +using System.Windows.Navigation; #endregion @@ -60,6 +63,8 @@ public partial class App : PrismApplication public App() { SetupUnhandledExceptionHandling(); + //? + //this.Dispatcher.UnhandledException += this.OnDispatcherUnhandledException; } #endregion @@ -93,6 +98,13 @@ protected override void OnStartup(StartupEventArgs e) WebApi.Client.v1.BaseApi.SetAuthenticationHeader(login, password); } + protected override void OnInitialized() + { + base.OnInitialized(); + + StartServices(); + } + protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterSingleton(containerRegistry => @@ -133,6 +145,12 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) RegisterDialogs(containerRegistry); } + private void StartServices() + { + if (Settings.Default.AutoStartTcpConnect) + Container.Resolve().ConnectAllAsync(); + } + private static void RegisterDialogs(IContainerRegistry containerRegistry) { containerRegistry.RegisterDialog(); @@ -190,6 +208,9 @@ private void SaveSettiings() Settings.Default.Save(); } + /// + /// The priority of resource release is important! + /// private void DisposeServices() { Container.Resolve().Dispose(); diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index 4fd725e..caed53d 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -1,5 +1,7 @@ using AdamController.Core; +using AdamController.Core.Mvvm; using AdamController.Services.Interfaces; +using DryIoc; using Prism.Commands; using Prism.Mvvm; using Prism.Regions; @@ -8,9 +10,9 @@ namespace AdamController.ViewModels { - public class MainWindowViewModel : BindableBase + public class MainWindowViewModel : ViewModelBase { - #region Command + #region DelegateCommands public DelegateCommand ShowRegionCommand { get; private set; } @@ -19,87 +21,58 @@ public class MainWindowViewModel : BindableBase #region Services public IRegionManager RegionManager { get; } - private ISubRegionChangeAwareService SubRegionChangeAwareService { get; } + private readonly ISubRegionChangeAwareService mSubRegionChangeAwareService; #endregion #region ~ - public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService) + public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService, ICommunicationProviderService communicationProviderService) { RegionManager = regionManager; - ShowRegionCommand = new DelegateCommand(ShowRegion); - SubRegionChangeAwareService = subRegionChangeAwareService; - - SubRegionChangeAwareService.RaiseSubRegionChangeEvent += RaiseSubRegionChangeEvent; - Application.Current.MainWindow.Loaded += MainWindowLoaded; - } - - #endregion + mSubRegionChangeAwareService = subRegionChangeAwareService; - #region Events - - /// - /// Load default region at startup - /// Need to call it after loading the main window - /// - private void MainWindowLoaded(object sender, RoutedEventArgs e) - { - ShowRegionCommand.Execute(SubRegionNames.SubRegionScratch); - } - - /// - /// Changes the selected section in the hamburger menu - /// - private void RaiseSubRegionChangeEvent(object sender) - { - var changeRegionName = SubRegionChangeAwareService?.InsideRegionNavigationRequestName; - ChangeSelectedIndexByRegionName(changeRegionName); + ShowRegionCommand = new DelegateCommand(ShowRegion); + Subscribe(); } #endregion - #region Fields + #region Public fields + + public string WindowTitle => $"Adam IDE {Assembly.GetExecutingAssembly().GetName().Version}"; /// /// -1 is not selected /// - private int mHamburgerMenuSelectedIndex = -1; + private int hamburgerMenuSelectedIndex = -1; public int HamburgerMenuSelectedIndex { - get { return mHamburgerMenuSelectedIndex; } + get { return hamburgerMenuSelectedIndex; } set { - if(mHamburgerMenuSelectedIndex == value) - return; - - SetProperty(ref mHamburgerMenuSelectedIndex, value); + SetProperty(ref hamburgerMenuSelectedIndex, value); } } /// /// -1 is not selected /// - private int mHamburgerMenuSelectedOptionsIndex = -1; + private int hamburgerMenuSelectedOptionsIndex = -1; public int HamburgerMenuSelectedOptionsIndex { - get { return mHamburgerMenuSelectedOptionsIndex; } + get { return hamburgerMenuSelectedOptionsIndex; } set { - if (mHamburgerMenuSelectedOptionsIndex == value) - return; - - SetProperty(ref mHamburgerMenuSelectedOptionsIndex, value); + SetProperty(ref hamburgerMenuSelectedOptionsIndex, value); } } - public string WindowTitle => $"Adam IDE {Assembly.GetExecutingAssembly().GetName().Version}"; - #endregion - #region Methods + #region Private methods private void ChangeSelectedIndexByRegionName(string subRegionName) { @@ -141,6 +114,50 @@ private void ShowRegion(string subRegionName) #endregion + #region Subscriptions + + /// + /// #20 + /// + private void Subscribe() + { + mSubRegionChangeAwareService.RaiseSubRegionChangeEvent += RaiseSubRegionChangeEvent; + Application.Current.MainWindow.Loaded += MainWindowLoaded; + } + + /// + /// #20 + /// + private void Unsubscribe() + { + mSubRegionChangeAwareService.RaiseSubRegionChangeEvent -= RaiseSubRegionChangeEvent; + Application.Current.MainWindow.Loaded -= MainWindowLoaded; + } + + #endregion + + #region Event methods + + /// + /// Load default region at startup + /// Need to call it after loading the main window + /// + private void MainWindowLoaded(object sender, RoutedEventArgs e) + { + ShowRegionCommand.Execute(SubRegionNames.SubRegionScratch); + } + + /// + /// Changes the selected section in the hamburger menu + /// + private void RaiseSubRegionChangeEvent(object sender) + { + var changeRegionName = mSubRegionChangeAwareService.InsideRegionNavigationRequestName; + ChangeSelectedIndexByRegionName(changeRegionName); + } + + #endregion + #region Old //public MainWindowViewModel() diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index e2cd75f..acfdd08 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -1,6 +1,7 @@ using AdamController.Controls.CustomControls.Services; using AdamController.Core; using AdamController.Core.Mvvm; +using AdamController.Services.Interfaces; using MahApps.Metro.IconPacks; using Prism.Commands; using Prism.Regions; @@ -19,6 +20,7 @@ public class StatusBarViewModel : RegionViewModelBase #region Services private readonly IFlyoutManager mFlyoutManager; + private readonly ICommunicationProviderService mCommunicationProviderService; #endregion @@ -35,11 +37,19 @@ public class StatusBarViewModel : RegionViewModelBase #region ~ - public StatusBarViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager) : base(regionManager, dialogService) + public StatusBarViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager, ICommunicationProviderService communicationProviderService) : base(regionManager, dialogService) { mFlyoutManager = flyoutManager; + mCommunicationProviderService = communicationProviderService; OpenNotificationPanelDelegateCommand = new DelegateCommand(OpenNotificationPanel, OpenNotificationPanelCanExecute); + + //ComunicateHelper.OnAdamTcpConnectedEvent += OnTcpConnected; + //ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; + //ComunicateHelper.OnAdamTcpReconnected += OnTcpReconnected; + + mCommunicationProviderService.RaiseAdamTcpCientConnected += RaiseAdamTcpCientConnected; + mCommunicationProviderService.RaiseAdamTcpClientDisconnect += RaiseAdamTcpClientDisconnect; } #endregion @@ -52,9 +62,6 @@ public bool ProgressRingStart get { return progressRingStart; } set { - if (value == progressRingStart) return; - - progressRingStart = value; SetProperty(ref progressRingStart, value); } } @@ -65,12 +72,6 @@ public string CompileLogStatusBar get { return compileLogStatusBar; } set { - if (value == compileLogStatusBar) - { - return; - } - - compileLogStatusBar = value; SetProperty(ref compileLogStatusBar, value); } } @@ -80,13 +81,7 @@ public string AppLogStatusBar { get { return appLogStatusBar; } set - { - if (value == appLogStatusBar) - { - return; - } - - appLogStatusBar = value; + { SetProperty(ref appLogStatusBar, value); } } @@ -97,9 +92,6 @@ public PackIconModernKind ConnectIcon get { return connectIcon; } set { - if (value == connectIcon) return; - - connectIcon = value; SetProperty(ref connectIcon, value); } } @@ -110,9 +102,6 @@ public string TextOnStatusConnectToolbar get { return textOnStatusConnectToolbar; } set { - if (value == textOnStatusConnectToolbar) return; - - textOnStatusConnectToolbar = value; SetProperty(ref textOnStatusConnectToolbar, value); } } @@ -123,9 +112,6 @@ public string NotificationBadge get { return notificationBadge; } set { - if (value == notificationBadge) return; - - notificationBadge = value; SetProperty(ref notificationBadge, value); } } @@ -140,7 +126,8 @@ private int BadgeCounter get { return badgeCounter; } set { - if (value == badgeCounter) return; + if (badgeCounter == value) + return; if (value == 0) { @@ -157,6 +144,22 @@ private int BadgeCounter #endregion + #region Event methods + + private void RaiseAdamTcpClientDisconnect(object sender) + { + ConnectIcon = PackIconModernKind.Connect; + TextOnStatusConnectToolbar = cTextOnStatusConnectToolbarDisconnected; + } + + private void RaiseAdamTcpCientConnected(object sender) + { + ConnectIcon = PackIconModernKind.Disconnect; + TextOnStatusConnectToolbar = cTextOnStatusConnectToolbarConnected; + } + + #endregion + #region DelegateCommands methods private void OpenNotificationPanel() From 466b1f3bf74890d3e126c7633ef7676a085cf3bb Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Thu, 11 Apr 2024 10:23:23 +1000 Subject: [PATCH 073/181] Close #18 p1 --- .../Helpers/ComunicateHelper.cs | 68 +++++++++---------- .../AdamUdpClientService.cs | 38 +++++++++++ .../CommunicationProviderService.cs | 33 +++++++-- .../Interfaces/IAdamUdpClientService.cs | 33 +++++++++ .../ICommunicationProviderService.cs | 2 + AdamController/App.xaml.cs | 20 +++++- 6 files changed, 153 insertions(+), 41 deletions(-) create mode 100644 AdamController.Services/AdamUdpClientService.cs create mode 100644 AdamController.Services/Interfaces/IAdamUdpClientService.cs diff --git a/AdamController.Core/Helpers/ComunicateHelper.cs b/AdamController.Core/Helpers/ComunicateHelper.cs index 6607d4d..24c8564 100644 --- a/AdamController.Core/Helpers/ComunicateHelper.cs +++ b/AdamController.Core/Helpers/ComunicateHelper.cs @@ -57,11 +57,11 @@ private static void LazyInitializer() //mAdamTcpClient = new(Settings.Default.ServerIP, Settings.Default.TcpConnectStatePort, option); //} - mAdamUdpMessageClient ??= new(IPAddress.Any, int.Parse(Settings.Default.MessageDataExchangePort)) - { - OptionDualMode = true, - OptionReuseAddress = true - }; + //mAdamUdpMessageClient ??= new(IPAddress.Any, int.Parse(Settings.Default.MessageDataExchangePort)) + // { + // OptionDualMode = true, + // OptionReuseAddress = true + // }; mAdamUdpLogServer ??= new(IPAddress.Any, Settings.Default.LogServerPort) { @@ -86,7 +86,7 @@ private static void LazyInitializer() mAdamWebSocketClient.WebSocketClientReceivedEvent += WebSocketClientReceived; mAdamWebSocketClient.WebSocketClientDisconnectedEvent += WebSocketClientDisconnectedEvent; - mAdamUdpMessageClient.UdpClientReceived += MessageClientUdpReceived; + //mAdamUdpMessageClient.UdpClientReceived += MessageClientUdpReceived; mAdamUdpLogServer.UdpServerReceived += UdpServerReceived; } @@ -105,11 +105,11 @@ private static void WebSocketConnectedEvent() //throw new System.NotImplementedException(); } - private static void MessageClientUdpReceived(EndPoint endpoint, byte[] buffer, long offset, long size) - { - string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); - OnAdamMessageReceivedEvent?.Invoke(encodedMessage); - } + //private static void MessageClientUdpReceived(EndPoint endpoint, byte[] buffer, long offset, long size) + //{ + // string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); + // OnAdamMessageReceivedEvent?.Invoke(encodedMessage); + //} #endregion @@ -131,13 +131,13 @@ private static void TcpClientError(object sender, SocketError error) {} private static void TcpClientDisconnected(object sender) { - OnAdamTcpDisconnectedEvent?.Invoke(); + //OnAdamTcpDisconnectedEvent?.Invoke(); - if (mAdamUdpLogServer != null) - { - if (mAdamUdpLogServer.IsStarted) - mAdamUdpLogServer?.Stop(); - } + //if (mAdamUdpLogServer != null) + //{ + // if (mAdamUdpLogServer.IsStarted) + // mAdamUdpLogServer?.Stop(); + //} if(mAdamWebSocketClient != null) { @@ -148,19 +148,19 @@ private static void TcpClientDisconnected(object sender) private static void TcpCientConnected(object sender) { - OnAdamTcpConnectedEvent?.Invoke(); + //OnAdamTcpConnectedEvent?.Invoke(); - if(!mAdamUdpLogServer.IsStarted) - mAdamUdpLogServer?.Start(); + //if(!mAdamUdpLogServer.IsStarted) + // mAdamUdpLogServer?.Start(); //if (!mAdamWebSocketClient.IsStarted) mAdamWebSocketClient.ConnectAsync(); } - private static void TcpClientReconnected(object sender, int reconnectCount) - { - OnAdamTcpReconnected?.Invoke(reconnectCount); - } + //private static void TcpClientReconnected(object sender, int reconnectCount) + //{ + // OnAdamTcpReconnected?.Invoke(reconnectCount); + //} #endregion @@ -193,16 +193,16 @@ public static void DisconnectAllAndDestroy() { //DisconnectAll(); - if(mAdamTcpClient != null) - { - mAdamTcpClient.RaiseTcpCientConnected -= TcpCientConnected; - mAdamTcpClient.RaiseTcpClientDisconnected -= TcpClientDisconnected; - mAdamTcpClient.RaiseTcpClientError -= TcpClientError; - mAdamTcpClient.RaiseTcpClientReceived -= TcpClientReceived; - mAdamTcpClient.RaiseTcpClientReconnected -= TcpClientReconnected; + //if(mAdamTcpClient != null) + //{ + //mAdamTcpClient.RaiseTcpCientConnected -= TcpCientConnected; + //mAdamTcpClient.RaiseTcpClientDisconnected -= TcpClientDisconnected; + //mAdamTcpClient.RaiseTcpClientError -= TcpClientError; + //mAdamTcpClient.RaiseTcpClientReceived -= TcpClientReceived; + //mAdamTcpClient.RaiseTcpClientReconnected -= TcpClientReconnected; - mAdamTcpClient = null; - } + // mAdamTcpClient = null; + //} if(mAdamUdpLogServer != null) { @@ -212,7 +212,7 @@ public static void DisconnectAllAndDestroy() if(mAdamUdpMessageClient != null) { - mAdamUdpMessageClient.UdpClientReceived -= MessageClientUdpReceived; + //mAdamUdpMessageClient.UdpClientReceived -= MessageClientUdpReceived; mAdamUdpLogServer = null; } diff --git a/AdamController.Services/AdamUdpClientService.cs b/AdamController.Services/AdamUdpClientService.cs new file mode 100644 index 0000000..0c79f72 --- /dev/null +++ b/AdamController.Services/AdamUdpClientService.cs @@ -0,0 +1,38 @@ +using AdamController.Services.Interfaces; +using System.Net; + +namespace AdamController.Services +{ + public class AdamUdpClientService : NetCoreServer.UdpServer, IAdamUdpClientService + { + public event UdpClientReceived RaiseUdpClientReceived; + + public AdamUdpClientService(IPAddress address, int port) : base(address, port) { } + + protected override void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size) + { + OnRaiseUdpClientReceived(endpoint, buffer, offset, size); + ReceiveAsync(); + } + + protected override void OnSent(EndPoint endpoint, long sent) + { + ReceiveAsync(); + } + + protected override void OnStarted() + { + ReceiveAsync(); + } + + #region OnRaiseEvents + + protected virtual void OnRaiseUdpClientReceived(EndPoint endpoint, byte[] buffer, long offset, long size) + { + UdpClientReceived raiseEvent = RaiseUdpClientReceived; + raiseEvent?.Invoke(this, endpoint, buffer, offset, size); + } + + #endregion + } +} diff --git a/AdamController.Services/CommunicationProviderService.cs b/AdamController.Services/CommunicationProviderService.cs index e64bab8..8fd79be 100644 --- a/AdamController.Services/CommunicationProviderService.cs +++ b/AdamController.Services/CommunicationProviderService.cs @@ -1,4 +1,6 @@ using AdamController.Services.Interfaces; +using System.Net; +using System.Text; using System.Threading.Tasks; namespace AdamController.Services @@ -18,12 +20,14 @@ public class CommunicationProviderService : ICommunicationProviderService #region Services private readonly IAdamTcpClientService mAdamTcpClientService; + private readonly IAdamUdpClientService mAdamUdpClientService; #endregion - public CommunicationProviderService(IAdamTcpClientService adamTcpClientService) + public CommunicationProviderService(IAdamTcpClientService adamTcpClientService, IAdamUdpClientService adamUdpClientService) { mAdamTcpClientService = adamTcpClientService; + mAdamUdpClientService = adamUdpClientService; Subscribe(); } @@ -32,16 +36,16 @@ public CommunicationProviderService(IAdamTcpClientService adamTcpClientService) public void ConnectAllAsync() { - mAdamTcpClientService.ConnectAsync(); - //_ = Task.Run(); - //_ = Task.Run(() => mAdamUdpMessageClient?.Start()); + + _ = Task.Run(mAdamTcpClientService.ConnectAsync); + _ = Task.Run(mAdamUdpClientService.Start); //_ = Task.Run(() => mAdamWebSocketClient?.ConnectAsync()); } public void DisconnectAllAsync() { _ = Task.Run(mAdamTcpClientService.DisconnectAndStop); - //_ = Task.Run(() => mAdamUdpMessageClient?.Stop()); + _ = Task.Run(mAdamUdpClientService.Stop); //_ = Task.Run(() => mAdamWebSocketClient?.DisconnectAsync()); } @@ -51,6 +55,9 @@ public void Dispose() { DisconnectAllAsync(); Unsubscribe(); + + mAdamTcpClientService.Dispose(); + mAdamUdpClientService.Dispose(); } #endregion @@ -66,6 +73,8 @@ private void Subscribe() mAdamTcpClientService.RaiseTcpClientReconnected += RaiseTcpClientReconnected; mAdamTcpClientService.RaiseTcpCientConnected += RaiseTcpCientConnected; mAdamTcpClientService.RaiseTcpClientDisconnected += RaiseTcpClientDisconnected; + + mAdamUdpClientService.RaiseUdpClientReceived += RaiseUdpClientReceived; } private void Unsubscribe() @@ -73,6 +82,8 @@ private void Unsubscribe() mAdamTcpClientService.RaiseTcpClientReconnected -= RaiseTcpClientReconnected; mAdamTcpClientService.RaiseTcpCientConnected -= RaiseTcpCientConnected; mAdamTcpClientService.RaiseTcpClientDisconnected -= RaiseTcpClientDisconnected; + + mAdamUdpClientService.RaiseUdpClientReceived -= RaiseUdpClientReceived; } #endregion @@ -87,6 +98,9 @@ private void RaiseTcpCientConnected(object sender) //if (!mAdamUdpLogServer.IsStarted) // mAdamUdpLogServer?.Start(); + //if(!mAdamUdpClientService.IsStarted) + mAdamUdpClientService.Start(); + //if (!mAdamWebSocketClient.IsStarted) //mAdamWebSocketClient.ConnectAsync(); } @@ -102,6 +116,9 @@ private void RaiseTcpClientDisconnected(object sender) // mAdamUdpLogServer?.Stop(); //} + //if(mAdamUdpClientService.IsStarted) + mAdamUdpClientService.Stop(); + //if (mAdamWebSocketClient != null) //{ //if (mAdamWebSocketClient.IsRunning) @@ -115,6 +132,12 @@ private void RaiseTcpClientReconnected(object sender, int reconnectCount) OnRaiseAdamTcpClientReconnected(reconnectCount); } + private void RaiseUdpClientReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size) + { + string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); + OnRaiseAdamUdpMessageReceived(encodedMessage); + } + #endregion #region OnRaise events diff --git a/AdamController.Services/Interfaces/IAdamUdpClientService.cs b/AdamController.Services/Interfaces/IAdamUdpClientService.cs new file mode 100644 index 0000000..d550898 --- /dev/null +++ b/AdamController.Services/Interfaces/IAdamUdpClientService.cs @@ -0,0 +1,33 @@ +using System; +using System.Net; +using System.Net.Sockets; + +namespace AdamController.Services.Interfaces +{ + #region Delegate + + public delegate void UdpClientReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size); + + #endregion + + public interface IAdamUdpClientService : IDisposable + { + #region Events + + public event UdpClientReceived RaiseUdpClientReceived; + + #endregion + + public bool IsStarted { get; } + + public bool Stop(); + + public bool Start(); + + //public void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size); + + //public void OnSent(EndPoint endpoint, long sent); + + //public void OnError(SocketError error); + } +} diff --git a/AdamController.Services/Interfaces/ICommunicationProviderService.cs b/AdamController.Services/Interfaces/ICommunicationProviderService.cs index 613943d..a3b13ca 100644 --- a/AdamController.Services/Interfaces/ICommunicationProviderService.cs +++ b/AdamController.Services/Interfaces/ICommunicationProviderService.cs @@ -25,6 +25,8 @@ public interface ICommunicationProviderService : IDisposable public event AdamUdpServerReceived RaiseAdamUdpServerReceived; public event AdamUdpMessageReceived RaiseAdamUdpMessageReceived; + + #endregion #region Public methods diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 17682ef..ab9d12a 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -51,6 +51,7 @@ using AdamController.ViewModels; using AdamController.Core.Mvvm; using System.Windows.Navigation; +using System.Net; #endregion @@ -135,10 +136,25 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return client; }); + containerRegistry.RegisterSingleton(containerRegistry => + { + IPAddress ip = IPAddress.Any; + int port = int.Parse(Settings.Default.MessageDataExchangePort); + + AdamUdpClientService client = new(ip, port) + { + OptionDualMode = true, + OptionReuseAddress = true + }; + + return client; + }); + containerRegistry.RegisterSingleton(containerRegistry => { IAdamTcpClientService tcpClientService = containerRegistry.Resolve(); - CommunicationProviderService communicationProvider = new(tcpClientService); + IAdamUdpClientService udpClientService = containerRegistry.Resolve(); + CommunicationProviderService communicationProvider = new(tcpClientService, udpClientService); return communicationProvider; }); @@ -210,11 +226,11 @@ private void SaveSettiings() /// /// The priority of resource release is important! + /// FirstRun/LastStop /// private void DisposeServices() { Container.Resolve().Dispose(); - Container.Resolve().Dispose(); Container.Resolve().Dispose(); } From 4fac320bb9cf1a2b2023e27bc2384d5f308d2f46 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Thu, 11 Apr 2024 13:18:53 +1000 Subject: [PATCH 074/181] Close #18 p2 --- .../Helpers/ComunicateHelper.cs | 58 ++++----- .../Helpers/PythonScriptExecuteHelper.cs | 3 +- AdamController.Services/AdamUdpClient.cs | 4 +- AdamController.Services/AdamUdpServer.cs | 2 + .../AdamUdpServerService.cs | 51 ++++++++ .../CommunicationProviderService.cs | 47 +++++--- .../Interfaces/IAdamUdpClientService.cs | 12 +- .../Interfaces/IAdamUdpServerService.cs | 37 ++++++ .../ICommunicationProviderService.cs | 6 + AdamController/App.xaml.cs | 43 +++++-- .../ComputerVisionControlViewModel.cs | 21 ++-- .../ViewModels/ScratchControlViewModel.cs | 112 ++++++------------ .../ScriptEditorControlViewModel.cs | 43 ++----- .../ViewModels/NotificationViewModel.cs | 46 +++---- 14 files changed, 277 insertions(+), 208 deletions(-) create mode 100644 AdamController.Services/AdamUdpServerService.cs create mode 100644 AdamController.Services/Interfaces/IAdamUdpServerService.cs diff --git a/AdamController.Core/Helpers/ComunicateHelper.cs b/AdamController.Core/Helpers/ComunicateHelper.cs index 24c8564..6bf2078 100644 --- a/AdamController.Core/Helpers/ComunicateHelper.cs +++ b/AdamController.Core/Helpers/ComunicateHelper.cs @@ -13,14 +13,14 @@ public sealed class ComunicateHelper { #region Declaration delegates and events - public delegate void OnAdamTcpCientConnected(); - public static event OnAdamTcpCientConnected OnAdamTcpConnectedEvent; + //public delegate void OnAdamTcpCientConnected(); + //public static event OnAdamTcpCientConnected OnAdamTcpConnectedEvent; - public delegate void OnAdamTcpClientDisconnect(); - public static event OnAdamTcpClientDisconnect OnAdamTcpDisconnectedEvent; + //public delegate void OnAdamTcpClientDisconnect(); + //public static event OnAdamTcpClientDisconnect OnAdamTcpDisconnectedEvent; - public delegate void OnAdamTcpClientReconnected(int reconnectCount); - public static event OnAdamTcpClientReconnected OnAdamTcpReconnected; + //public delegate void OnAdamTcpClientReconnected(int reconnectCount); + //public static event OnAdamTcpClientReconnected OnAdamTcpReconnected; public delegate void OnAdamUdpServerReceived(string message); public static event OnAdamUdpServerReceived OnAdamLogServerUdpReceivedEvent; @@ -30,10 +30,10 @@ public sealed class ComunicateHelper #endregion - public static bool TcpClientIsConnected => mAdamTcpClient != null && mAdamTcpClient.IsConnected; + //public static bool TcpClientIsConnected => mAdamTcpClient != null && mAdamTcpClient.IsConnected; - private static AdamTcpClientService mAdamTcpClient; - private static AdamUdpClient mAdamUdpMessageClient; + //private static AdamTcpClientService mAdamTcpClient; + //private static AdamUdpClient mAdamUdpMessageClient; private static AdamUdpServer mAdamUdpLogServer; private static AdamWebSocketClient mAdamWebSocketClient; @@ -125,19 +125,19 @@ private static void UdpServerReceived(EndPoint endpoint, byte[] buffer, long off #region TCP Client events - private static void TcpClientReceived(object sender, byte[] buffer, long offset, long size) {} + //private static void TcpClientReceived(object sender, byte[] buffer, long offset, long size) {} - private static void TcpClientError(object sender, SocketError error) {} + //private static void TcpClientError(object sender, SocketError error) {} private static void TcpClientDisconnected(object sender) { //OnAdamTcpDisconnectedEvent?.Invoke(); - //if (mAdamUdpLogServer != null) - //{ - // if (mAdamUdpLogServer.IsStarted) - // mAdamUdpLogServer?.Stop(); - //} + if (mAdamUdpLogServer != null) + { + if (mAdamUdpLogServer.IsStarted) + mAdamUdpLogServer?.Stop(); + } if(mAdamWebSocketClient != null) { @@ -150,8 +150,8 @@ private static void TcpCientConnected(object sender) { //OnAdamTcpConnectedEvent?.Invoke(); - //if(!mAdamUdpLogServer.IsStarted) - // mAdamUdpLogServer?.Start(); + if(!mAdamUdpLogServer.IsStarted) + mAdamUdpLogServer?.Start(); //if (!mAdamWebSocketClient.IsStarted) mAdamWebSocketClient.ConnectAsync(); @@ -210,11 +210,11 @@ public static void DisconnectAllAndDestroy() mAdamUdpLogServer = null; } - if(mAdamUdpMessageClient != null) - { + //if(mAdamUdpMessageClient != null) + //{ //mAdamUdpMessageClient.UdpClientReceived -= MessageClientUdpReceived; mAdamUdpLogServer = null; - } + //} if(mAdamWebSocketClient != null) { @@ -229,15 +229,15 @@ public static void DisconnectAllAndDestroy() #region Tcp/Udp/WebSocket send message - public static void SendTcpMessage(string message) - { - mAdamTcpClient.Send(message); - } + //public static void SendTcpMessage(string message) + //{ + // mAdamTcpClient.Send(message); + //} - public static void SendTcpMessageAsync(string message) - { - _ = Task.Run(() => SendTcpMessage(message)); - } + //public static void SendTcpMessageAsync(string message) + //{ + // _ = Task.Run(() => SendTcpMessage(message)); + //} public static void WebSocketSendTextMessage(string message) { diff --git a/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs b/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs index b5bd01a..fa57b3a 100644 --- a/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs +++ b/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs @@ -1,5 +1,4 @@ -using AdamController.Core.Helpers; -using AdamController.WebApi.Client.Common; +using AdamController.WebApi.Client.Common; using AdamController.WebApi.Client.v1.ResponseModel; namespace AdamController.Core.Helpers diff --git a/AdamController.Services/AdamUdpClient.cs b/AdamController.Services/AdamUdpClient.cs index c8b68a1..730796c 100644 --- a/AdamController.Services/AdamUdpClient.cs +++ b/AdamController.Services/AdamUdpClient.cs @@ -1,8 +1,10 @@ -using System.Net; +using System; +using System.Net; using System.Net.Sockets; namespace AdamController.Services { + [Obsolete] public class AdamUdpClient : NetCoreServer.UdpServer { #region DelegateAndEvent diff --git a/AdamController.Services/AdamUdpServer.cs b/AdamController.Services/AdamUdpServer.cs index f15d9b2..07b531e 100644 --- a/AdamController.Services/AdamUdpServer.cs +++ b/AdamController.Services/AdamUdpServer.cs @@ -1,9 +1,11 @@ using NetCoreServer; +using System; using System.Net; using System.Net.Sockets; namespace AdamController.Services { + [Obsolete] public class AdamUdpServer : UdpServer { public delegate void OnUdpServerReceived(EndPoint endpoint, byte[] buffer, long offset, long size); diff --git a/AdamController.Services/AdamUdpServerService.cs b/AdamController.Services/AdamUdpServerService.cs new file mode 100644 index 0000000..279182c --- /dev/null +++ b/AdamController.Services/AdamUdpServerService.cs @@ -0,0 +1,51 @@ +using AdamController.Services.Interfaces; +using NetCoreServer; +using System.Net; + +namespace AdamController.Services +{ + public class AdamUdpServerService : UdpServer, IAdamUdpServerService + { + #region Events + + public event UdpServerReceived RaiseUdpServerReceived; + + #endregion + + #region ~ + + public AdamUdpServerService(IPAddress address, int port) : base(address, port){} + + #endregion + + #region Private methods + + protected override void OnStarted() + { + ReceiveAsync(); + } + + protected override void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size) + { + OnRaiseUdpServerReceived(endpoint, buffer, offset, size); + ReceiveAsync(); + } + + protected override void OnSent(EndPoint endpoint, long sent) + { + ReceiveAsync(); + } + + #endregion + + #region OnRaiseEvents + + protected virtual void OnRaiseUdpServerReceived(EndPoint endpoint, byte[] buffer, long offset, long size) + { + UdpServerReceived raiseEvent = RaiseUdpServerReceived; + raiseEvent?.Invoke(this, endpoint, buffer, offset, size); + } + + #endregion + } +} diff --git a/AdamController.Services/CommunicationProviderService.cs b/AdamController.Services/CommunicationProviderService.cs index 8fd79be..2e19e94 100644 --- a/AdamController.Services/CommunicationProviderService.cs +++ b/AdamController.Services/CommunicationProviderService.cs @@ -21,17 +21,21 @@ public class CommunicationProviderService : ICommunicationProviderService private readonly IAdamTcpClientService mAdamTcpClientService; private readonly IAdamUdpClientService mAdamUdpClientService; + private readonly IAdamUdpServerService mAadamUdpServerService; #endregion - public CommunicationProviderService(IAdamTcpClientService adamTcpClientService, IAdamUdpClientService adamUdpClientService) + public CommunicationProviderService(IAdamTcpClientService adamTcpClientService, IAdamUdpClientService adamUdpClientService, IAdamUdpServerService adamUdpServerService) { mAdamTcpClientService = adamTcpClientService; mAdamUdpClientService = adamUdpClientService; + mAadamUdpServerService = adamUdpServerService; Subscribe(); } + public bool IsTcpClientConnected { get; private set; } + #region Public methods public void ConnectAllAsync() @@ -39,6 +43,7 @@ public void ConnectAllAsync() _ = Task.Run(mAdamTcpClientService.ConnectAsync); _ = Task.Run(mAdamUdpClientService.Start); + _ = Task.Run(mAadamUdpServerService.Start); //_ = Task.Run(() => mAdamWebSocketClient?.ConnectAsync()); } @@ -46,6 +51,7 @@ public void DisconnectAllAsync() { _ = Task.Run(mAdamTcpClientService.DisconnectAndStop); _ = Task.Run(mAdamUdpClientService.Stop); + _ = Task.Run(mAadamUdpServerService.Stop); //_ = Task.Run(() => mAdamWebSocketClient?.DisconnectAsync()); } @@ -58,6 +64,7 @@ public void Dispose() mAdamTcpClientService.Dispose(); mAdamUdpClientService.Dispose(); + mAadamUdpServerService.Dispose(); } #endregion @@ -75,6 +82,8 @@ private void Subscribe() mAdamTcpClientService.RaiseTcpClientDisconnected += RaiseTcpClientDisconnected; mAdamUdpClientService.RaiseUdpClientReceived += RaiseUdpClientReceived; + + mAadamUdpServerService.RaiseUdpServerReceived += RaiseUdpServerReceived; } private void Unsubscribe() @@ -84,6 +93,8 @@ private void Unsubscribe() mAdamTcpClientService.RaiseTcpClientDisconnected -= RaiseTcpClientDisconnected; mAdamUdpClientService.RaiseUdpClientReceived -= RaiseUdpClientReceived; + + mAadamUdpServerService.RaiseUdpServerReceived -= RaiseUdpServerReceived; } #endregion @@ -92,14 +103,12 @@ private void Unsubscribe() private void RaiseTcpCientConnected(object sender) { - //OnAdamTcpConnectedEvent?.Invoke(); - OnRaiseAdamTcpCientConnected(); + IsTcpClientConnected = true; - //if (!mAdamUdpLogServer.IsStarted) - // mAdamUdpLogServer?.Start(); + OnRaiseAdamTcpCientConnected(); - //if(!mAdamUdpClientService.IsStarted) mAdamUdpClientService.Start(); + mAadamUdpServerService.Start(); //if (!mAdamWebSocketClient.IsStarted) //mAdamWebSocketClient.ConnectAsync(); @@ -107,17 +116,12 @@ private void RaiseTcpCientConnected(object sender) private void RaiseTcpClientDisconnected(object sender) { - //OnAdamTcpDisconnectedEvent?.Invoke(); - OnRaiseAdamTcpClientDisconnect(); + IsTcpClientConnected = false; - //if (mAdamUdpLogServer != null) - //{ - // if (mAdamUdpLogServer.IsStarted) - // mAdamUdpLogServer?.Stop(); - //} + OnRaiseAdamTcpClientDisconnect(); - //if(mAdamUdpClientService.IsStarted) mAdamUdpClientService.Stop(); + mAadamUdpServerService.Stop(); //if (mAdamWebSocketClient != null) //{ @@ -134,10 +138,19 @@ private void RaiseTcpClientReconnected(object sender, int reconnectCount) private void RaiseUdpClientReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size) { - string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); + string encodedMessage = Encoding.UTF8.GetString(buffer); + //string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); OnRaiseAdamUdpMessageReceived(encodedMessage); } + + private void RaiseUdpServerReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size) + { + string encodedMessage = Encoding.UTF8.GetString(buffer); + //string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); + OnRaiseAdamUdpServerReceived(encodedMessage); + } + #endregion #region OnRaise events @@ -160,10 +173,10 @@ public virtual void OnRaiseAdamTcpClientReconnected(int reconnectCounter) raiseEvent?.Invoke(this, reconnectCounter); } - protected virtual void OnRaiseAdamUdpServerReceived() + protected virtual void OnRaiseAdamUdpServerReceived(string message) { AdamUdpServerReceived raiseEvent = RaiseAdamUdpServerReceived; - raiseEvent?.Equals(this); + raiseEvent?.Invoke(this, message); } protected virtual void OnRaiseAdamUdpMessageReceived(string message) diff --git a/AdamController.Services/Interfaces/IAdamUdpClientService.cs b/AdamController.Services/Interfaces/IAdamUdpClientService.cs index d550898..b8f0af6 100644 --- a/AdamController.Services/Interfaces/IAdamUdpClientService.cs +++ b/AdamController.Services/Interfaces/IAdamUdpClientService.cs @@ -18,16 +18,18 @@ public interface IAdamUdpClientService : IDisposable #endregion + #region Public fields + public bool IsStarted { get; } - public bool Stop(); + #endregion - public bool Start(); + #region Public methods - //public void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size); + public bool Stop(); - //public void OnSent(EndPoint endpoint, long sent); + public bool Start(); - //public void OnError(SocketError error); + #endregion } } diff --git a/AdamController.Services/Interfaces/IAdamUdpServerService.cs b/AdamController.Services/Interfaces/IAdamUdpServerService.cs new file mode 100644 index 0000000..dbff113 --- /dev/null +++ b/AdamController.Services/Interfaces/IAdamUdpServerService.cs @@ -0,0 +1,37 @@ + +using System; +using System.Net; + +namespace AdamController.Services.Interfaces +{ + + #region Delegate + + public delegate void UdpServerReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size); + + #endregion + + public interface IAdamUdpServerService : IDisposable + { + #region Events + + public event UdpServerReceived RaiseUdpServerReceived; + + #endregion + + #region Public fields + + public bool IsStarted { get; } + + #endregion + + #region Public methods + + public bool Start(); + + public bool Stop(); + + #endregion + + } +} diff --git a/AdamController.Services/Interfaces/ICommunicationProviderService.cs b/AdamController.Services/Interfaces/ICommunicationProviderService.cs index a3b13ca..90ffbe7 100644 --- a/AdamController.Services/Interfaces/ICommunicationProviderService.cs +++ b/AdamController.Services/Interfaces/ICommunicationProviderService.cs @@ -27,6 +27,12 @@ public interface ICommunicationProviderService : IDisposable + #endregion + + #region Public fields + + public bool IsTcpClientConnected { get; } + #endregion #region Public methods diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index ab9d12a..332f72b 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -86,17 +86,6 @@ protected override void OnStartup(StartupEventArgs e) //TODO check theme before ChangeTheme _ = ThemeManager.Current.ChangeTheme(this, $"{Settings.Default.BaseTheme}.{Settings.Default.ThemeColorScheme}", false); - - string ip = Settings.Default.ServerIP; - int port = Settings.Default.ApiPort; - - Uri DefaultUri = new($"http://{ip}:{port}"); - WebApi.Client.v1.BaseApi.SetApiClientUri(DefaultUri); - - string login = Settings.Default.ApiLogin; - string password = Settings.Default.ApiPassword; - - WebApi.Client.v1.BaseApi.SetAuthenticationHeader(login, password); } protected override void OnInitialized() @@ -104,6 +93,7 @@ protected override void OnInitialized() base.OnInitialized(); StartServices(); + StartWebApi(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) @@ -150,11 +140,26 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return client; }); + containerRegistry.RegisterSingleton(containerRegistry => + { + IPAddress ip = IPAddress.Any; + int port = Settings.Default.LogServerPort; + + AdamUdpServerService server = new(ip, port) + { + OptionDualMode = true, + OptionReuseAddress = true + }; + + return server; + }); + containerRegistry.RegisterSingleton(containerRegistry => { IAdamTcpClientService tcpClientService = containerRegistry.Resolve(); IAdamUdpClientService udpClientService = containerRegistry.Resolve(); - CommunicationProviderService communicationProvider = new(tcpClientService, udpClientService); + IAdamUdpServerService udpServerService = containerRegistry.Resolve(); + CommunicationProviderService communicationProvider = new(tcpClientService, udpClientService, udpServerService); return communicationProvider; }); @@ -167,6 +172,20 @@ private void StartServices() Container.Resolve().ConnectAllAsync(); } + private void StartWebApi() + { + string ip = Settings.Default.ServerIP; + int port = Settings.Default.ApiPort; + + Uri DefaultUri = new($"http://{ip}:{port}"); + WebApi.Client.v1.BaseApi.SetApiClientUri(DefaultUri); + + string login = Settings.Default.ApiLogin; + string password = Settings.Default.ApiPassword; + + WebApi.Client.v1.BaseApi.SetAuthenticationHeader(login, password); + } + private static void RegisterDialogs(IContainerRegistry containerRegistry) { containerRegistry.RegisterDialog(); diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs index 8e958ec..089a2ac 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs @@ -13,23 +13,24 @@ namespace AdamController.Modules.ContentRegion.ViewModels { public class ComputerVisionControlViewModel : RegionViewModelBase { - #region private var + #region Services - private DelegateCommand directionButtonCommandDown; - private DelegateCommand directionButtonCommandUp; + private readonly ICommunicationProviderService mCommunicationProvider; #endregion - #region services + #region private var + + private DelegateCommand directionButtonCommandDown; + private DelegateCommand directionButtonCommandUp; - IFlyoutManager FlyoutManager { get; } #endregion #region ~ - public ComputerVisionControlViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager) : base(regionManager, dialogService) + public ComputerVisionControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider) : base(regionManager, dialogService) { - FlyoutManager = flyoutManager; + mCommunicationProvider = communicationProvider; } #endregion @@ -73,7 +74,7 @@ public ComputerVisionControlViewModel(IRegionManager regionManager, IDialogServi var json = JsonConvert.SerializeObject(vectorSource); ComunicateHelper.WebSocketSendTextMessage(json); - }, canExecute => ComunicateHelper.TcpClientIsConnected); + }, canExecute => mCommunicationProvider.IsTcpClientConnected); /// /// Comamand execute when button up @@ -93,7 +94,7 @@ public ComputerVisionControlViewModel(IRegionManager regionManager, IDialogServi var json = JsonConvert.SerializeObject(vector); ComunicateHelper.WebSocketSendTextMessage(json); - }, canExecute => ComunicateHelper.TcpClientIsConnected); + }, canExecute => mCommunicationProvider.IsTcpClientConnected); private DelegateCommand toZeroPositionCommand; public DelegateCommand ToZeroPositionCommand => toZeroPositionCommand ??= new DelegateCommand(async () => @@ -107,7 +108,7 @@ public ComputerVisionControlViewModel(IRegionManager regionManager, IDialogServi { } - }, () => ComunicateHelper.TcpClientIsConnected); + }, () => mCommunicationProvider.IsTcpClientConnected); private float sliderValue; diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index be192a8..a0b2d46 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -25,6 +25,13 @@ namespace AdamController.Modules.ContentRegion.ViewModels { public class ScratchControlViewModel : RegionViewModelBase { + + #region Services + + private readonly ICommunicationProviderService mCommunicationProvider; + + #endregion + #region Action field public static Action SendSourceToScriptEditor { get; set; } @@ -39,37 +46,21 @@ public class ScratchControlViewModel : RegionViewModelBase private readonly IMessageDialogManager IDialogManager; private bool mIsWarningStackOwerflowAlreadyShow; - public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) + public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider) : base(regionManager, dialogService) { + mCommunicationProvider = communicationProvider; IDialogManager = new MessageDialogManagerMahapps(Application.Current); InitAction(); PythonExecuteEvent(); - - ComunicateHelper.OnAdamTcpConnectedEvent += OnAdamTcpConnectedEvent; - ComunicateHelper.OnAdamTcpDisconnectedEvent += OnAdamTcpDisconnectedEvent; - } - - #region Navigation - - public override void OnNavigatedFrom(NavigationContext navigationContext) - { - - } - - public override void OnNavigatedTo(NavigationContext navigationContext) - { - } - #endregion - - private void OnAdamTcpDisconnectedEvent() + private void RaiseAdamTcpClientDisconnect(object sender) { UpdatePythonInfo(); } - private async void OnAdamTcpConnectedEvent() + private async void RaiseAdamTcpCientConnected(object sender) { var pythonVersionResult = await BaseApi.GetPythonVersion(); var pythonBinPathResult = await BaseApi.GetPythonBinDir(); @@ -82,6 +73,23 @@ private async void OnAdamTcpConnectedEvent() UpdatePythonInfo(pythonVersion, pythonBinPath, pythonWorkDir); } + #region Navigation + + public override void OnNavigatedFrom(NavigationContext navigationContext) + { + mCommunicationProvider.RaiseAdamTcpCientConnected -= RaiseAdamTcpCientConnected; + mCommunicationProvider.RaiseAdamTcpClientDisconnect -= RaiseAdamTcpClientDisconnect; + } + + public override void OnNavigatedTo(NavigationContext navigationContext) + { + mCommunicationProvider.RaiseAdamTcpCientConnected += RaiseAdamTcpCientConnected; + mCommunicationProvider.RaiseAdamTcpClientDisconnect += RaiseAdamTcpClientDisconnect; + } + + #endregion + + private void UpdatePythonInfo(string pythonVersion = "", string pythonBinPath = "", string pythonWorkDir = "") { if (string.IsNullOrEmpty(pythonVersion)) @@ -210,26 +218,14 @@ private void WebMessageReceived(WebMessageJsonReceived results) public bool IsEnabledStopExecuteButton { get => isEnabledStopExecuteButton; - set - { - if (value == isEnabledStopExecuteButton) return; - isEnabledStopExecuteButton = value; - - SetProperty(ref isEnabledStopExecuteButton, value); - } + set => SetProperty(ref isEnabledStopExecuteButton, value); } private bool isEnabledShowOpenDialogButton = true; public bool IsEnabledShowOpenDialogButton { get => isEnabledShowOpenDialogButton; - set - { - if (value == isEnabledShowOpenDialogButton) return; - isEnabledShowOpenDialogButton = value; - - SetProperty(ref isEnabledShowOpenDialogButton, value); - } + set => SetProperty(ref isEnabledShowOpenDialogButton, value); } #endregion @@ -487,13 +483,7 @@ public string ResultTextEditor public int ResultTextEditorLength { get => resultTextEditorLength; - set - { - if (value == resultTextEditorLength) return; - resultTextEditorLength = value; - - SetProperty(ref resultTextEditorLength, value); - } + set => SetProperty(ref resultTextEditorLength, value); } #endregion @@ -522,39 +512,21 @@ public string ResultTextEditorError public string PythonVersion { get => pythonVersion; - set - { - if (value == pythonVersion) return; - pythonVersion = value; - - SetProperty(ref pythonVersion, value); - } + set => SetProperty(ref pythonVersion, value); } private string pythonBinPath; public string PythonBinPath { get => pythonBinPath; - set - { - if (value == pythonBinPath) return; - pythonBinPath = value; - - SetProperty(ref pythonBinPath, value); - } + set => SetProperty(ref pythonBinPath, value); } private string pythonWorkDir; public string PythonWorkDir { get => pythonWorkDir; - set - { - if (value == pythonWorkDir) return; - pythonWorkDir = value; - - SetProperty(ref pythonWorkDir, value); - } + set => SetProperty(ref pythonWorkDir, value); } #endregion @@ -565,13 +537,7 @@ public string PythonWorkDir public string SourceTextEditor { get => sourceTextEditor; - set - { - if (value == sourceTextEditor) return; - sourceTextEditor = value; - - SetProperty(ref sourceTextEditor, value); - } + set => SetProperty(ref sourceTextEditor, value); } #endregion @@ -599,7 +565,7 @@ public string SourceTextEditor string workspace = await ScratchControlView.ExecuteScript("getSavedWorkspace()"); string xmlWorkspace = JsonConvert.DeserializeObject(workspace); - if (IDialogManager.ShowSaveFileDialog("Сохранить рабочую область", Core.Properties.Settings.Default.SavedUserWorkspaceFolderPath, "workspace", ".xml", "XML documents (.xml)|*.xml")) + if (IDialogManager.ShowSaveFileDialog("Сохранить рабочую область", Settings.Default.SavedUserWorkspaceFolderPath, "workspace", ".xml", "XML documents (.xml)|*.xml")) { string path = IDialogManager.FilePathToSave; await FileHelper.WriteAsync(path, xmlWorkspace); @@ -667,12 +633,12 @@ public string SourceTextEditor ResultTextEditor += $"Ошибка: {executeResult.StandardError}" + "\n======================"; - }, () => !string.IsNullOrEmpty(SourceTextEditor) && ComunicateHelper.TcpClientIsConnected); + }, () => !string.IsNullOrEmpty(SourceTextEditor) && mCommunicationProvider.IsTcpClientConnected); private DelegateCommand stopExecute; public DelegateCommand StopExecute => stopExecute ??= new DelegateCommand( async () => { - if (ComunicateHelper.TcpClientIsConnected) + if (mCommunicationProvider.IsTcpClientConnected) { try { @@ -697,7 +663,7 @@ public string SourceTextEditor ResultTextEditorError = ex.Message.ToString(); } - }, () => ComunicateHelper.TcpClientIsConnected); + }, () => mCommunicationProvider.IsTcpClientConnected); private DelegateCommand cleanExecuteEditor; public DelegateCommand CleanExecuteEditor => cleanExecuteEditor ??= new DelegateCommand(async () => diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs index 2dcff7f..9405810 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs @@ -15,13 +15,20 @@ namespace AdamController.Modules.ContentRegion.ViewModels { public class ScriptEditorControlViewModel : RegionViewModelBase { + #region Services + + private readonly ICommunicationProviderService mCommunicationProvider; + + #endregion public static Action AppLogStatusBarAction { get; set; } private bool mIsWarningStackOwerflowAlreadyShow; private readonly IMessageDialogManager IDialogManager; - public ScriptEditorControlViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) + public ScriptEditorControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider) : base(regionManager, dialogService) { + mCommunicationProvider = communicationProvider; + IDialogManager = new MessageDialogManagerMahapps(Application.Current); InitAction(); PythonExecuteEvent(); @@ -82,26 +89,14 @@ private void PythonExecuteEvent() public string SourceTextEditor { get => sourceTextEditor; - set - { - if (value == sourceTextEditor) return; - - sourceTextEditor = value; - SetProperty(ref sourceTextEditor, value); - } + set => SetProperty(ref sourceTextEditor, value); } private string selectedText; public string SelectedText { get => selectedText; - set - { - if (value == selectedText) return; - - selectedText = value; - SetProperty(ref selectedText, value); - } + set => SetProperty(ref selectedText, value); } #endregion @@ -143,13 +138,7 @@ public string ResultTextEditor public int ResultTextEditorLength { get => resultTextEditorLength; - set - { - if (value == resultTextEditorLength) return; - - resultTextEditorLength = value; - SetProperty (ref resultTextEditorLength, value); - } + set => SetProperty(ref resultTextEditorLength, value); } #endregion @@ -160,13 +149,7 @@ public int ResultTextEditorLength public bool IsCodeExecuted { get => isCodeExecuted; - set - { - if (value == isCodeExecuted) return; - isCodeExecuted = value; - - SetProperty(ref isCodeExecuted, value); - } + set => SetProperty(ref isCodeExecuted, value); } #endregion @@ -204,7 +187,7 @@ public string ResultTextEditorError try { - if(ComunicateHelper.TcpClientIsConnected) + if(mCommunicationProvider.IsTcpClientConnected) { var command = new WebApi.Client.v1.RequestModel.PythonCommand { diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index ffcaa35..11d2267 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -1,6 +1,7 @@ using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; using AdamController.Core.Helpers; using AdamController.Core.Properties; +using AdamController.Services.Interfaces; using MahApps.Metro.IconPacks; using Prism.Commands; using System.Windows; @@ -10,6 +11,12 @@ namespace AdamController.Modules.FlayoutsRegion.ViewModels { public class NotificationViewModel : FlyoutBase { + #region Services + + private readonly ICommunicationProviderService mCommunicationProvider; + + #endregion + #region Const private const string cConnectButtonStatusDisconnected = "Подключить"; @@ -20,8 +27,10 @@ public class NotificationViewModel : FlyoutBase #region ~ - public NotificationViewModel() + public NotificationViewModel(ICommunicationProviderService communicationProvider) { + mCommunicationProvider = communicationProvider; + Theme = FlyoutTheme.Inverse; Header= "Центр уведомлений"; IsModal = false; @@ -35,14 +44,7 @@ public NotificationViewModel() public Visibility NoNewNotificationMessageVisibility { get => noNewNotificationMessageVisibility; - set - { - if (value == noNewNotificationMessageVisibility) return; - - noNewNotificationMessageVisibility = value; - SetProperty(ref noNewNotificationMessageVisibility, value); - - } + set => SetProperty(ref noNewNotificationMessageVisibility, value); } private Visibility failConnectMessageVisibility = Visibility.Collapsed; @@ -71,19 +73,11 @@ public Visibility FailConnectMessageVisibility public double NotificationOpacity { get => notificationOpacity; - set - { - if (value == notificationOpacity) return; - - notificationOpacity = value; - - SetProperty(ref notificationOpacity, value); - } + set => SetProperty(ref notificationOpacity, value); } #endregion - #region NotificationBadge /* #16 */ private void ClearNotification() @@ -100,13 +94,7 @@ private void ClearNotification() public string TextOnConnectFlayotButton { get => textOnConnectFlayotButton; - set - { - if (value == textOnConnectFlayotButton) return; - - textOnConnectFlayotButton = value; - SetProperty(ref textOnConnectFlayotButton, value); - } + set => SetProperty(ref textOnConnectFlayotButton, value); } private PackIconMaterialKind iconOnConnectFlayoutButton; @@ -140,15 +128,15 @@ public PackIconMaterialKind IconOnConnectFlayoutButton await Dispatcher.Yield(DispatcherPriority.Normal); - if (ComunicateHelper.TcpClientIsConnected) + if (mCommunicationProvider.IsTcpClientConnected) { - //ComunicateHelper.DisconnectAll(); + mCommunicationProvider.DisconnectAllAsync(); return; } - if (!ComunicateHelper.TcpClientIsConnected) + if (!mCommunicationProvider.IsTcpClientConnected) { - //ComunicateHelper.ConnectAllAsync(); + mCommunicationProvider.ConnectAllAsync(); return; } }); From b7a32580468edf31842e9da2341654db5ca9ed49 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Thu, 11 Apr 2024 15:04:58 +1000 Subject: [PATCH 075/181] Fix #18 p3 --- .../Helpers/ComunicateHelper.cs | 103 ++++++++------- .../Helpers/PythonScriptExecuteHelper.cs | 3 +- .../AdamWebSocketClient.cs | 1 + .../AdamWebSocketClientService.cs | 124 ++++++++++++++++++ .../CommunicationProviderService.cs | 35 +++-- .../Interfaces/IAdamWebSocketClientService.cs | 43 ++++++ .../ICommunicationProviderService.cs | 2 + AdamController/App.xaml.cs | 21 ++- .../ComputerVisionControlViewModel.cs | 4 +- .../Views/ComputerVisionControlView.xaml.cs | 3 +- 10 files changed, 270 insertions(+), 69 deletions(-) create mode 100644 AdamController.Services/AdamWebSocketClientService.cs create mode 100644 AdamController.Services/Interfaces/IAdamWebSocketClientService.cs diff --git a/AdamController.Core/Helpers/ComunicateHelper.cs b/AdamController.Core/Helpers/ComunicateHelper.cs index 6bf2078..fcbb8f1 100644 --- a/AdamController.Core/Helpers/ComunicateHelper.cs +++ b/AdamController.Core/Helpers/ComunicateHelper.cs @@ -9,6 +9,7 @@ namespace AdamController.Core.Helpers { + [Obsolete] public sealed class ComunicateHelper { #region Declaration delegates and events @@ -22,11 +23,11 @@ public sealed class ComunicateHelper //public delegate void OnAdamTcpClientReconnected(int reconnectCount); //public static event OnAdamTcpClientReconnected OnAdamTcpReconnected; - public delegate void OnAdamUdpServerReceived(string message); - public static event OnAdamUdpServerReceived OnAdamLogServerUdpReceivedEvent; + //public delegate void OnAdamUdpServerReceived(string message); + //public static event OnAdamUdpServerReceived OnAdamLogServerUdpReceivedEvent; - public delegate void OnAdamUdpMessageReceived(string message); - public static event OnAdamUdpMessageReceived OnAdamMessageReceivedEvent; + //public delegate void OnAdamUdpMessageReceived(string message); + //public static event OnAdamUdpMessageReceived OnAdamMessageReceivedEvent; #endregion @@ -34,14 +35,14 @@ public sealed class ComunicateHelper //private static AdamTcpClientService mAdamTcpClient; //private static AdamUdpClient mAdamUdpMessageClient; - private static AdamUdpServer mAdamUdpLogServer; - private static AdamWebSocketClient mAdamWebSocketClient; + //private static AdamUdpServer mAdamUdpLogServer; + //private static AdamWebSocketClient mAdamWebSocketClient; #region ~ static ComunicateHelper() { - LazyInitializer(); + //LazyInitializer(); } private static void LazyInitializer() @@ -63,16 +64,16 @@ private static void LazyInitializer() // OptionReuseAddress = true // }; - mAdamUdpLogServer ??= new(IPAddress.Any, Settings.Default.LogServerPort) - { - OptionDualMode = true, - OptionReuseAddress = true - }; + //mAdamUdpLogServer ??= new(IPAddress.Any, Settings.Default.LogServerPort) + // { + // OptionDualMode = true, + // OptionReuseAddress = true + // }; #if DEBUG - mAdamWebSocketClient ??= new AdamWebSocketClient(new Uri($"ws://{Settings.Default.ServerIP}:9001/adam-2.7/movement")); + //mAdamWebSocketClient ??= new AdamWebSocketClient(new Uri($"ws://{Settings.Default.ServerIP}:9001/adam-2.7/movement")); #else - mAdamWebSocketClient ??= new AdamWebSocketClient(new Uri($"ws://{Settings.Default.ServerIP}:{Settings.Default.SoketServerPort}/adam-2.7/movement")); + //mAdamWebSocketClient ??= new AdamWebSocketClient(new Uri($"ws://{Settings.Default.ServerIP}:{Settings.Default.SoketServerPort}/adam-2.7/movement")); #endif @@ -82,12 +83,12 @@ private static void LazyInitializer() //mAdamTcpClient.RaiseTcpClientReceived += TcpClientReceived; //mAdamTcpClient.RaiseTcpClientReconnected += TcpClientReconnected; - mAdamWebSocketClient.WebSocketConnectedEvent += WebSocketConnectedEvent; - mAdamWebSocketClient.WebSocketClientReceivedEvent += WebSocketClientReceived; - mAdamWebSocketClient.WebSocketClientDisconnectedEvent += WebSocketClientDisconnectedEvent; + //mAdamWebSocketClient.WebSocketConnectedEvent += WebSocketConnectedEvent; + //mAdamWebSocketClient.WebSocketClientReceivedEvent += WebSocketClientReceived; + //mAdamWebSocketClient.WebSocketClientDisconnectedEvent += WebSocketClientDisconnectedEvent; //mAdamUdpMessageClient.UdpClientReceived += MessageClientUdpReceived; - mAdamUdpLogServer.UdpServerReceived += UdpServerReceived; + //mAdamUdpLogServer.UdpServerReceived += UdpServerReceived; } private static void WebSocketClientDisconnectedEvent() @@ -115,11 +116,11 @@ private static void WebSocketConnectedEvent() #region Udp Server events - private static void UdpServerReceived(EndPoint endpoint, byte[] buffer, long offset, long size) - { - string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); - OnAdamLogServerUdpReceivedEvent?.Invoke(encodedMessage); - } + //private static void UdpServerReceived(EndPoint endpoint, byte[] buffer, long offset, long size) + //{ + // string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); + // OnAdamLogServerUdpReceivedEvent?.Invoke(encodedMessage); + //} #endregion @@ -133,28 +134,28 @@ private static void TcpClientDisconnected(object sender) { //OnAdamTcpDisconnectedEvent?.Invoke(); - if (mAdamUdpLogServer != null) - { - if (mAdamUdpLogServer.IsStarted) - mAdamUdpLogServer?.Stop(); - } + //if (mAdamUdpLogServer != null) + //{ + // if (mAdamUdpLogServer.IsStarted) + // mAdamUdpLogServer?.Stop(); + //} - if(mAdamWebSocketClient != null) - { + //if(mAdamWebSocketClient != null) + //{ //if (mAdamWebSocketClient.IsRunning) - mAdamWebSocketClient.DisconnectAsync(); - } + // mAdamWebSocketClient.DisconnectAsync(); + //} } private static void TcpCientConnected(object sender) { //OnAdamTcpConnectedEvent?.Invoke(); - if(!mAdamUdpLogServer.IsStarted) - mAdamUdpLogServer?.Start(); + //if(!mAdamUdpLogServer.IsStarted) + // mAdamUdpLogServer?.Start(); //if (!mAdamWebSocketClient.IsStarted) - mAdamWebSocketClient.ConnectAsync(); + //mAdamWebSocketClient.ConnectAsync(); } //private static void TcpClientReconnected(object sender, int reconnectCount) @@ -204,25 +205,25 @@ public static void DisconnectAllAndDestroy() // mAdamTcpClient = null; //} - if(mAdamUdpLogServer != null) - { - mAdamUdpLogServer.UdpServerReceived -= UdpServerReceived; - mAdamUdpLogServer = null; - } + //if(mAdamUdpLogServer != null) + //{ + // mAdamUdpLogServer.UdpServerReceived -= UdpServerReceived; + // mAdamUdpLogServer = null; + //} //if(mAdamUdpMessageClient != null) //{ //mAdamUdpMessageClient.UdpClientReceived -= MessageClientUdpReceived; - mAdamUdpLogServer = null; + //mAdamUdpLogServer = null; //} - if(mAdamWebSocketClient != null) - { - mAdamWebSocketClient.WebSocketConnectedEvent -= WebSocketConnectedEvent; - mAdamWebSocketClient.WebSocketClientReceivedEvent -= WebSocketClientReceived; - mAdamWebSocketClient.WebSocketClientDisconnectedEvent -= WebSocketClientDisconnectedEvent; + //if(mAdamWebSocketClient != null) + //{ + // mAdamWebSocketClient.WebSocketConnectedEvent -= WebSocketConnectedEvent; + // mAdamWebSocketClient.WebSocketClientReceivedEvent -= WebSocketClientReceived; + // mAdamWebSocketClient.WebSocketClientDisconnectedEvent -= WebSocketClientDisconnectedEvent; //mAdamWebSocketClient.Dispose(); - } + //} } #endregion @@ -239,10 +240,10 @@ public static void DisconnectAllAndDestroy() // _ = Task.Run(() => SendTcpMessage(message)); //} - public static void WebSocketSendTextMessage(string message) - { - Task.Run(() => mAdamWebSocketClient.SendTextAsync(message)); - } + //public static void WebSocketSendTextMessage(string message) + //{ + //Task.Run(() => mAdamWebSocketClient.SendTextAsync(message)); + //} #endregion } diff --git a/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs b/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs index fa57b3a..52f6e95 100644 --- a/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs +++ b/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs @@ -20,7 +20,8 @@ public class PythonScriptExecuteHelper static PythonScriptExecuteHelper() { - ComunicateHelper.OnAdamMessageReceivedEvent += OnAdamMessageReceivedAsync; + //Change on comunication provider + //ComunicateHelper.OnAdamMessageReceivedEvent += OnAdamMessageReceivedAsync; } private static void OnAdamMessageReceivedAsync(string message) diff --git a/AdamController.Services/AdamWebSocketClient.cs b/AdamController.Services/AdamWebSocketClient.cs index 2c6b06f..5afb829 100644 --- a/AdamController.Services/AdamWebSocketClient.cs +++ b/AdamController.Services/AdamWebSocketClient.cs @@ -4,6 +4,7 @@ namespace AdamController.Services { + [Obsolete] public class AdamWebSocketClient : IDisposable { diff --git a/AdamController.Services/AdamWebSocketClientService.cs b/AdamController.Services/AdamWebSocketClientService.cs new file mode 100644 index 0000000..89d1f0e --- /dev/null +++ b/AdamController.Services/AdamWebSocketClientService.cs @@ -0,0 +1,124 @@ +using AdamController.Services.Interfaces; +using System; +using System.Threading.Tasks; +using Websocket.Client; + +namespace AdamController.Services +{ + public class AdamWebSocketClientService : IAdamWebSocketClientService + { + #region Events + + public event WebSocketClientReceived RaiseWebSocketClientReceived; + public event WebSocketConnected RaiseWebSocketConnected; + public event WebSocketClientDisconnect RaiseWebSocketClientDisconnect; + + #endregion + + #region var + + private readonly WebsocketClient mWebsocketClient; + + #endregion + + #region ~ + + public AdamWebSocketClientService(Uri url) + { + mWebsocketClient = new(url) + { + ReconnectTimeout = null + }; + + Subscribe(); + } + + #endregion + + #region Public field + + public bool IsStarted => mWebsocketClient.IsStarted; + + public bool IsRunning => mWebsocketClient.IsRunning; + + #endregion + + #region Public method + + public Task ConnectAsync() + { + return mWebsocketClient.StartOrFail(); + } + + public Task DisconnectAsync() + { + return mWebsocketClient.StopOrFail(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, "Nomal close"); + } + + public Task SendTextAsync(string text) + { + if(!string.IsNullOrEmpty(text)) + { + Task task = mWebsocketClient.SendInstant(text); + return task; + } + + return Task.CompletedTask; + } + + public void Dispose() + { + mWebsocketClient.Dispose(); + } + + #endregion + + #region Subscriptions + + private void Subscribe() + { + mWebsocketClient.MessageReceived.Subscribe(message => + { + OnRaiseWebSocketClientReceived(message.Text); + }); + + mWebsocketClient.DisconnectionHappened.Subscribe(eventHappened => + { + OnRaiseWebSocketClientDisconnect(); + }); + + mWebsocketClient.ReconnectionHappened.Subscribe(eventHappened => + { + OnRaiseWebSocketConnected(); + }); + } + + #endregion + + #region OnRaiseEvents + + protected virtual void OnRaiseWebSocketClientReceived(string text) + { + WebSocketClientReceived raiseEvent = RaiseWebSocketClientReceived; + raiseEvent?.Invoke(this, text); + } + + protected virtual void OnRaiseWebSocketConnected() + { + WebSocketConnected raiseEvent = RaiseWebSocketConnected; + raiseEvent?.Invoke(this); + } + + protected virtual void OnRaiseWebSocketClientDisconnect() + { + WebSocketClientDisconnect raiseEvent = RaiseWebSocketClientDisconnect; + raiseEvent?.Invoke(this); + } + + #endregion + } +} + + + + diff --git a/AdamController.Services/CommunicationProviderService.cs b/AdamController.Services/CommunicationProviderService.cs index 2e19e94..3328c32 100644 --- a/AdamController.Services/CommunicationProviderService.cs +++ b/AdamController.Services/CommunicationProviderService.cs @@ -22,20 +22,31 @@ public class CommunicationProviderService : ICommunicationProviderService private readonly IAdamTcpClientService mAdamTcpClientService; private readonly IAdamUdpClientService mAdamUdpClientService; private readonly IAdamUdpServerService mAadamUdpServerService; + private readonly IAdamWebSocketClientService mAdamWebSocketClientService; #endregion - public CommunicationProviderService(IAdamTcpClientService adamTcpClientService, IAdamUdpClientService adamUdpClientService, IAdamUdpServerService adamUdpServerService) + #region ~ + + public CommunicationProviderService(IAdamTcpClientService adamTcpClientService, IAdamUdpClientService adamUdpClientService, + IAdamUdpServerService adamUdpServerService, IAdamWebSocketClientService adamWebSocketClientService) { mAdamTcpClientService = adamTcpClientService; mAdamUdpClientService = adamUdpClientService; mAadamUdpServerService = adamUdpServerService; + mAdamWebSocketClientService = adamWebSocketClientService; Subscribe(); } + #endregion + + #region Public fields + public bool IsTcpClientConnected { get; private set; } + #endregion + #region Public methods public void ConnectAllAsync() @@ -44,7 +55,7 @@ public void ConnectAllAsync() _ = Task.Run(mAdamTcpClientService.ConnectAsync); _ = Task.Run(mAdamUdpClientService.Start); _ = Task.Run(mAadamUdpServerService.Start); - //_ = Task.Run(() => mAdamWebSocketClient?.ConnectAsync()); + _ = Task.Run(mAdamWebSocketClientService.ConnectAsync); } public void DisconnectAllAsync() @@ -52,11 +63,16 @@ public void DisconnectAllAsync() _ = Task.Run(mAdamTcpClientService.DisconnectAndStop); _ = Task.Run(mAdamUdpClientService.Stop); _ = Task.Run(mAadamUdpServerService.Stop); - //_ = Task.Run(() => mAdamWebSocketClient?.DisconnectAsync()); + _ = Task.Run(mAdamWebSocketClientService.DisconnectAsync); } public void DisconnectAllAndDestroy() {} + public void WebSocketSendTextMessage(string message) + { + Task.Run(() => mAdamWebSocketClientService.SendTextAsync(message)); + } + public void Dispose() { DisconnectAllAsync(); @@ -65,6 +81,7 @@ public void Dispose() mAdamTcpClientService.Dispose(); mAdamUdpClientService.Dispose(); mAadamUdpServerService.Dispose(); + mAdamWebSocketClientService.Dispose(); } #endregion @@ -109,9 +126,7 @@ private void RaiseTcpCientConnected(object sender) mAdamUdpClientService.Start(); mAadamUdpServerService.Start(); - - //if (!mAdamWebSocketClient.IsStarted) - //mAdamWebSocketClient.ConnectAsync(); + mAdamWebSocketClientService.ConnectAsync(); } private void RaiseTcpClientDisconnected(object sender) @@ -122,17 +137,11 @@ private void RaiseTcpClientDisconnected(object sender) mAdamUdpClientService.Stop(); mAadamUdpServerService.Stop(); - - //if (mAdamWebSocketClient != null) - //{ - //if (mAdamWebSocketClient.IsRunning) - // mAdamWebSocketClient.DisconnectAsync(); - //} + mAdamWebSocketClientService.DisconnectAsync(); } private void RaiseTcpClientReconnected(object sender, int reconnectCount) { - //OnAdamTcpReconnected?.Invoke(reconnectCount); OnRaiseAdamTcpClientReconnected(reconnectCount); } diff --git a/AdamController.Services/Interfaces/IAdamWebSocketClientService.cs b/AdamController.Services/Interfaces/IAdamWebSocketClientService.cs new file mode 100644 index 0000000..546b466 --- /dev/null +++ b/AdamController.Services/Interfaces/IAdamWebSocketClientService.cs @@ -0,0 +1,43 @@ +using System; +using System.Threading.Tasks; + +namespace AdamController.Services.Interfaces +{ + + #region Delegate + + public delegate void WebSocketClientReceived(object sender, string text); + public delegate void WebSocketConnected(object sender); + public delegate void WebSocketClientDisconnect(object sender); + + #endregion + + public interface IAdamWebSocketClientService : IDisposable + { + #region Events + + public event WebSocketClientReceived RaiseWebSocketClientReceived; + public event WebSocketConnected RaiseWebSocketConnected; + public event WebSocketClientDisconnect RaiseWebSocketClientDisconnect; + + #endregion + + #region Public field + + public bool IsStarted { get; } + + public bool IsRunning { get; } + + #endregion + + #region Public method + + public Task ConnectAsync(); + + public Task DisconnectAsync(); + + public Task SendTextAsync(string text); + + #endregion + } +} diff --git a/AdamController.Services/Interfaces/ICommunicationProviderService.cs b/AdamController.Services/Interfaces/ICommunicationProviderService.cs index 90ffbe7..a20e872 100644 --- a/AdamController.Services/Interfaces/ICommunicationProviderService.cs +++ b/AdamController.Services/Interfaces/ICommunicationProviderService.cs @@ -49,6 +49,8 @@ public interface ICommunicationProviderService : IDisposable /// public void DisconnectAllAndDestroy(); + public void WebSocketSendTextMessage(string message); + #endregion } } diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 332f72b..7bb10a7 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -154,12 +154,31 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return server; }); + containerRegistry.RegisterSingleton(containerRegistry => + { + string ip = Settings.Default.ServerIP; + int port = Settings.Default.SoketServerPort; + + // debug + Uri uri = new($"ws://{Settings.Default.ServerIP}:9001/adam-2.7/movement"); + + //work + //Uri uri = new($"ws://{ip}:{port}/adam-2.7/movement"); + + AdamWebSocketClientService client = new(uri); + return client; + + }); + containerRegistry.RegisterSingleton(containerRegistry => { IAdamTcpClientService tcpClientService = containerRegistry.Resolve(); IAdamUdpClientService udpClientService = containerRegistry.Resolve(); IAdamUdpServerService udpServerService = containerRegistry.Resolve(); - CommunicationProviderService communicationProvider = new(tcpClientService, udpClientService, udpServerService); + IAdamWebSocketClientService socketClientService = containerRegistry.Resolve(); + + CommunicationProviderService communicationProvider = new(tcpClientService, udpClientService, udpServerService, socketClientService); + return communicationProvider; }); diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs index 089a2ac..24e1d25 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs @@ -73,7 +73,7 @@ public ComputerVisionControlViewModel(IRegionManager regionManager, IDialogServi var json = JsonConvert.SerializeObject(vectorSource); - ComunicateHelper.WebSocketSendTextMessage(json); + mCommunicationProvider.WebSocketSendTextMessage(json); }, canExecute => mCommunicationProvider.IsTcpClientConnected); /// @@ -92,7 +92,7 @@ public ComputerVisionControlViewModel(IRegionManager regionManager, IDialogServi }; var json = JsonConvert.SerializeObject(vector); - ComunicateHelper.WebSocketSendTextMessage(json); + mCommunicationProvider.WebSocketSendTextMessage(json); }, canExecute => mCommunicationProvider.IsTcpClientConnected); diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs b/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs index 7b1f1d4..75f7dbc 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs +++ b/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs @@ -78,7 +78,8 @@ public void Dispose() private void Button_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { - ComunicateHelper.WebSocketSendTextMessage(DownRightDirection); + //There is no solution for this situation + //ComunicateHelper.WebSocketSendTextMessage(DownRightDirection); } } } From 4b41a07ad420ae9d0cde0afee237f29ee6d52060 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Thu, 11 Apr 2024 15:49:04 +1000 Subject: [PATCH 076/181] Fix #18 p 4/5 Remove all everything that applies network test --- .../Dialog.ViewModels/NetworkTestViewModel.cs | 1303 --------------- .../Dialog.Views/NetworkTestView.xaml | 1443 ----------------- .../Dialog.Views/NetworkTestView.xaml.cs | 12 - AdamController.Core/DialogNames.cs | 1 - .../Extensions/DialogServiceExtension.cs | 5 - .../Helpers/ComunicateBenchmarkHelper.cs | 132 -- .../Helpers/ComunicateHelper.cs | 250 --- .../Helpers/TcpTestRunHelper.cs | 123 -- .../Helpers/UdpTestRunHelper.cs | 121 -- AdamController.Core/Model/AppLanguageModel.cs | 24 +- .../Model/BlocklyLanguageModel.cs | 28 +- AdamController.Core/Model/EditorModel.cs | 7 +- AdamController.Services/AdamTestTcpClient.cs | 54 - AdamController.Services/AdamUdpClient.cs | 40 - AdamController.Services/AdamUdpServer.cs | 37 - AdamController.Services/AdamUdpTestClient.cs | 50 - .../AdamWebSocketClient.cs | 78 - .../CommunicationProviderService.cs | 25 +- .../ICommunicationProviderService.cs | 4 +- ...pClientService.cs => ITcpClientService.cs} | 2 +- ...pClientService.cs => IUdpClientService.cs} | 2 +- ...pServerService.cs => IUdpServerService.cs} | 2 +- ...tService.cs => IWebSocketClientService.cs} | 2 +- .../TcpClientOption.cs} | 4 +- ...cpClientService.cs => TcpClientService.cs} | 8 +- ...dpClientService.cs => UdpClientService.cs} | 4 +- ...dpServerService.cs => UdpServerService.cs} | 4 +- ...ntService.cs => WebSocketClientService.cs} | 4 +- AdamController/App.xaml.cs | 38 +- .../ComputerVisionControlViewModel.cs | 4 +- .../VisualSettingsControlViewModel.cs | 3 - .../ViewModels/MenuRegionViewModel.cs | 5 - .../Views/MenuRegionView.xaml | 4 - 33 files changed, 54 insertions(+), 3769 deletions(-) delete mode 100644 AdamController.Core/Dialog.ViewModels/NetworkTestViewModel.cs delete mode 100644 AdamController.Core/Dialog.Views/NetworkTestView.xaml delete mode 100644 AdamController.Core/Dialog.Views/NetworkTestView.xaml.cs delete mode 100644 AdamController.Core/Helpers/ComunicateBenchmarkHelper.cs delete mode 100644 AdamController.Core/Helpers/ComunicateHelper.cs delete mode 100644 AdamController.Core/Helpers/TcpTestRunHelper.cs delete mode 100644 AdamController.Core/Helpers/UdpTestRunHelper.cs delete mode 100644 AdamController.Services/AdamTestTcpClient.cs delete mode 100644 AdamController.Services/AdamUdpClient.cs delete mode 100644 AdamController.Services/AdamUdpServer.cs delete mode 100644 AdamController.Services/AdamUdpTestClient.cs delete mode 100644 AdamController.Services/AdamWebSocketClient.cs rename AdamController.Services/Interfaces/{IAdamTcpClientService.cs => ITcpClientService.cs} (96%) rename AdamController.Services/Interfaces/{IAdamUdpClientService.cs => IUdpClientService.cs} (91%) rename AdamController.Services/Interfaces/{IAdamUdpServerService.cs => IUdpServerService.cs} (90%) rename AdamController.Services/Interfaces/{IAdamWebSocketClientService.cs => IWebSocketClientService.cs} (93%) rename AdamController.Services/{AdamTcpClientDependency/AdamTcpClientOption.cs => TcpClientDependency/TcpClientOption.cs} (75%) rename AdamController.Services/{AdamTcpClientService.cs => TcpClientService.cs} (95%) rename AdamController.Services/{AdamUdpClientService.cs => UdpClientService.cs} (83%) rename AdamController.Services/{AdamUdpServerService.cs => UdpServerService.cs} (87%) rename AdamController.Services/{AdamWebSocketClientService.cs => WebSocketClientService.cs} (95%) diff --git a/AdamController.Core/Dialog.ViewModels/NetworkTestViewModel.cs b/AdamController.Core/Dialog.ViewModels/NetworkTestViewModel.cs deleted file mode 100644 index 865f900..0000000 --- a/AdamController.Core/Dialog.ViewModels/NetworkTestViewModel.cs +++ /dev/null @@ -1,1303 +0,0 @@ -using AdamController.Core.Helpers; -using AdamController.Core.Mvvm; -using AdamController.WebApi.Client.v1; -using AdamController.WebApi.Client.v1.RequestModel; -using MahApps.Metro.IconPacks; -using MessageDialogManagerLib; -using NetCoreServer; -using Prism.Commands; -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Threading; - -namespace AdamController.Core.Dialog.ViewModels -{ - public class NetworkTestViewModel : DialogViewModelBase - { - #region Const - - private const string mClientDisconnected = "Статус тестового сервера: отключен"; - private const string mClientConnected = "Статус тестового сервера: подключен"; - private const string mClientReconnected = "Статус тестового сервера: переподключение"; - - private const string mTcpTestClientStatusNotRunning = "TCP Round-Trip тест: не запущен"; - private const string mTcpTestClientStatusRunning = "TCP Round-Trip тест: запущен"; - private const string mUdpTestClientStatusNotRunning = "UDP Round-Trip тест: не запущен"; - private const string mUdpTestClientStatusRunning = "UDP Round-Trip тест: запущен"; - - #endregion - - private readonly ComunicateBenchmarkHelper mComunicateTestHelper; - private readonly IMessageDialogManager IDialogManager; - - #region ~ - - public NetworkTestViewModel() - { - Title = "Тест сети"; - - //SendApiComunicateCommand(ServerCommand.Start); - - //mComunicateTestHelper = ComunicateBenchmarkHelper.Instance; - IDialogManager = new MessageDialogManagerMahapps(Application.Current); - - //ComunicateBenchmarkHelper.OnTcpConnected += OnTcpConnected; - //ComunicateBenchmarkHelper.OnTcpDisconnected += OnTcpDisconnected; - //ComunicateBenchmarkHelper.OnTcpReconnected += OnTcpReconnected; - - ClearTcpResultField(); - TcpStatusBarManager(false); - - ClearUdpResultField(); - UdpStatusBarManager(false); - - if (Properties.Settings.Default.AutoStartTestTcpConnect) - { - //ConnectButtonComand.Execute(); - } - else - { - //init fields if autorun off - //OnTcpDisconnected(); - } - } - - #endregion - - #region Navigation - - #endregion - - #region UI behavior - - //added to activate the reset button, after publishing the results, but does not work - //activates the window when disconnect, reconnect, connect - //if you fix the background of the connect button when the window is out of focus, you can delete it - //can be removed during refactoring - private bool networkWindowActivated; - public bool NetworkWindowActivated - { - get => networkWindowActivated; - set - { - if (value == networkWindowActivated) return; - networkWindowActivated = value; - - SetProperty(ref networkWindowActivated, value); - } - } - - #endregion - - #region Tcp/ip event test client method - - private void OnTcpDisconnected() - { - IsTcpClientConnected = false; - TextOnStatusConnectButton = mClientDisconnected; - ReconnectProgressRing = false; - ConnectIcon = PackIconModernKind.Connect; - NetworkWindowActivated = true; - } - - private void OnTcpConnected() - { - IsTcpClientConnected = true; - TextOnStatusConnectButton = mClientConnected; - ReconnectProgressRing = false; - ConnectIcon = PackIconModernKind.Disconnect; - NetworkWindowActivated = true; - } - - private void OnTcpReconnected(int reconnectCount) - { - IsTcpClientConnected = null; - TextOnStatusConnectButton = $"{mClientReconnected} {reconnectCount}"; - ReconnectProgressRing = true; - ConnectIcon = PackIconModernKind.TransitConnectionDeparture; - NetworkWindowActivated = true; - } - - #endregion - - #region IsTcpClientConnected - - private bool? isTcpClientConnected; - /// - /// The field determines the existence of a connection to the test server - /// null - the state of the reconnect - /// true - connection - /// false - disconnection - /// - public bool? IsTcpClientConnected - { - get => isTcpClientConnected; - set - { - if (value == isTcpClientConnected) return; - - isTcpClientConnected = value; - - SetProperty(ref isTcpClientConnected, value); - } - } - - #endregion - - #region Publish result counter - - #region TCP - - private int publishTcpResultCount; - public int PublishTcpResultCount - { - get => publishTcpResultCount; - set - { - if (value == publishTcpResultCount) return; - publishTcpResultCount = value; - - SetProperty(ref publishTcpResultCount, value); - } - } - - #endregion - - #region UDP - - private int publishUdpResultCount; - public int PublishUdpResultCount - { - get => publishUdpResultCount; - set - { - if (value == publishUdpResultCount) return; - publishUdpResultCount = value; - - SetProperty(ref publishTcpResultCount, value); - } - } - - #endregion - - #endregion - - #region Start test time field - - #region TCP - - private string startTcpTestTime; - public string StartTcpTestTime - { - get => startTcpTestTime; - set - { - if (value == startTcpTestTime) return; - - startTcpTestTime = value; - - SetProperty(ref startTcpTestTime, value); - } - } - - #endregion - - #region UDP - - private string startUdpTestTime; - public string StartUdpTestTime - { - get => startUdpTestTime; - set - { - if (value == startUdpTestTime) return; - - startUdpTestTime = value; - - SetProperty (ref startUdpTestTime, value); - } - } - - #endregion - - #endregion - - #region Finish test time field - - #region TCP - - private string finishTcpTestTime; - public string FinishTcpTestTime - { - get => finishTcpTestTime; - set - { - if (value == finishTcpTestTime) return; - - finishTcpTestTime = value; - - SetProperty(ref finishTcpTestTime, value); - } - } - - #endregion - - #region UDP - - private string finishUdpTestTime; - public string FinishUdpTestTime - { - get => finishUdpTestTime; - set - { - if (value == finishUdpTestTime) return; - - finishUdpTestTime = value; - - SetProperty(ref finishUdpTestTime, value); - } - } - - #endregion - - #region TotalTimeTest field - - #region TCP - - private string totalTimeTcpTest; - public string TotalTimeTcpTest - { - get => totalTimeTcpTest; - private set - { - if (value == totalTimeTcpTest) return; - - totalTimeTcpTest = value; - - SetProperty(ref totalTimeTcpTest, value); - } - } - - #endregion - - #region UDP - - private string totalTimeUdpTest; - public string TotalTimeUdpTest - { - get => totalTimeUdpTest; - private set - { - if (value == totalTimeUdpTest) return; - - totalTimeUdpTest = value; - - SetProperty (ref totalTimeUdpTest, value); - } - } - - #endregion - - #endregion - - #endregion - - #region DataCounter field - - #region TCP - - private string dataTcpCounter; - public string DataTcpCounter - { - get => dataTcpCounter; - set - { - if (value == dataTcpCounter) return; - dataTcpCounter = value; - - SetProperty(ref dataTcpCounter, value); - } - } - - #endregion - - #region UDP - - private string dataUdpCounter; - public string DataUdpCounter - { - get => dataUdpCounter; - set - { - if (value == dataUdpCounter) return; - - dataUdpCounter = value; - - SetProperty(ref dataUdpCounter, value); - } - } - - #endregion - - #endregion - - #region MessageCounter field - - #region TCP - - private string messageTcpCounter; - public string MessageTcpCounter - { - get => messageTcpCounter; - set - { - if (value == messageTcpCounter) return; - - messageTcpCounter = value; - - SetProperty(ref messageTcpCounter, value); - } - } - - #endregion - - #region UDP - - private string messageUdpCounter; - public string MessageUdpCounter - { - get => messageUdpCounter; - set - { - if (value == messageUdpCounter) return; - - messageUdpCounter = value; - - SetProperty(ref messageUdpCounter, value); - } - } - - #endregion - - #endregion - - #region DataThroughput field - - #region TCP - - private string dataTcpThroughput; - public string DataTcpThroughput - { - get => dataTcpThroughput; - private set - { - if (value == dataTcpThroughput) return; - dataTcpThroughput = value; - - SetProperty (ref dataTcpThroughput, value); - } - } - - #endregion - - #region UDP - - private string dataUdpThroughput; - public string DataUdpThroughput - { - get => dataUdpThroughput; - private set - { - if (value == dataUdpThroughput) return; - dataUdpThroughput = value; - - SetProperty(ref dataUdpThroughput, value); - } - } - - #endregion - - #endregion - - #region MessageLatency field - - #region TCP - - private string messageTcpLatency; - public string MessageTcpLatency - { - get => messageTcpLatency; - private set - { - if (value == messageTcpLatency) return; - messageTcpLatency = value; - - SetProperty(ref messageTcpLatency, value); - } - } - - #endregion - - #region UDP - - private string messageUdpLatency; - public string MessageUdpLatency - { - get => messageUdpLatency; - private set - { - if (value == messageUdpLatency) return; - messageUdpLatency = value; - - SetProperty(ref messageUdpLatency, value); - } - } - - #endregion - - #endregion - - #region MessageThroughput field - - #region TCP - - private string messageTcpThroughput; - public string MessageTcpThroughput - { - get => messageTcpThroughput; - private set - { - if (value == messageTcpThroughput) return; - messageTcpThroughput = value; - - SetProperty(ref messageTcpThroughput, value); - } - } - - #endregion - - #region UDP - - private string messageUdpThroughput; - public string MessageUdpThroughput - { - get => messageUdpThroughput; - private set - { - if (value == messageUdpThroughput) return; - messageUdpThroughput = value; - - SetProperty(ref messageUdpThroughput, value); - } - } - - #endregion - - #endregion - - #region Error counter field - - #region TCP - - private string errorTcpCounter; - public string ErrorTcpCounter - { - get => errorTcpCounter; - set - { - if (value == errorTcpCounter) return; - errorTcpCounter = value; - - SetProperty(ref errorTcpCounter, value); - } - } - - #endregion - - #region UDP - - private string errorUdpCounter; - public string ErrorUdpCounter - { - get => errorUdpCounter; - set - { - if (value == errorUdpCounter) return; - errorUdpCounter = value; - - SetProperty(ref errorUdpCounter, value); - } - } - - #endregion - - #endregion - - #region Error message - - #region TCP - - private string errorTcpMessage; - public string ErrorTcpMessage - { - get => errorTcpMessage; - set - { - if (value == errorTcpMessage) return; - errorTcpMessage = value; - - SetProperty(ref errorTcpMessage, value); - } - } - - #endregion - - #region UDP - - private string errorUdpMessage; - public string ErrorUdpMessage - { - get => errorUdpMessage; - set - { - if (value == errorUdpMessage) return; - errorUdpMessage = value; - - SetProperty(ref errorUdpMessage, value); - } - } - - #endregion - - #endregion - - #region ProgressRing field - - #region TCP - - private bool progressRingTcp = false; - public bool ProgressRingTcp - { - get => progressRingTcp; - set - { - if (value == progressRingTcp) return; - - progressRingTcp = value; - - SetProperty(ref progressRingTcp, value); - } - } - - #endregion - - #region UDP - - private bool progressRingUdp = false; - public bool ProgressRingUdp - { - get => progressRingUdp; - set - { - if (value == progressRingUdp) return; - - progressRingUdp = value; - - SetProperty(ref progressRingUdp, value); - } - } - - #endregion - - #region ReconnectProgressRing - - private bool reconnectProgressRing; - public bool ReconnectProgressRing - { - get => reconnectProgressRing; - set - { - if (value == reconnectProgressRing) return; - - reconnectProgressRing = value; - - SetProperty (ref reconnectProgressRing, value); - } - } - - #endregion - - #endregion - - #region SelectedTabIndex - - private int selectedTabIndex; - public int SelectedTabIndex - { - get => selectedTabIndex; - set - { - if (value == selectedTabIndex) - return; - - selectedTabIndex = value; - - SetProperty(ref selectedTabIndex, value); - } - } - - #endregion - - #region Environment tabs fields - - public int ProcessorCount { get; } = Environment.ProcessorCount; - public bool Is64BitOperatingSystem { get; } = Environment.Is64BitOperatingSystem; - public bool Is64BitProcess { get; } = Environment.Is64BitProcess; - public string MachineName { get; } = Environment.MachineName; - public string OSVersion { get; } = Environment.OSVersion.ToString(); - public string OSDescription { get; } = RuntimeInformation.OSDescription; - public string UserName { get; } = Environment.UserName; - public int TickCount { get; } = Environment.TickCount; - public long WorkingSet { get; } = Environment.WorkingSet; - - - #endregion - - #region Main Connect/Disconnect client toolbar - - private string textOnStatusConnectButton = mClientDisconnected; - public string TextOnStatusConnectButton - { - get => textOnStatusConnectButton; - set - { - if (value == textOnStatusConnectButton) return; - - textOnStatusConnectButton = value; - SetProperty(ref textOnStatusConnectButton, value); - } - } - - private PackIconModernKind connectIcon = PackIconModernKind.Connect; - public PackIconModernKind ConnectIcon - { - get => connectIcon; - set - { - if (value == connectIcon) return; - - connectIcon = value; - SetProperty(ref connectIcon, value); - } - } - - #endregion - - #region Status TCP test toolbar - - private string textOnTcpStatusTest = mTcpTestClientStatusRunning; - public string TextOnTcpStatusTest - { - get => textOnTcpStatusTest; - set - { - if (value == textOnTcpStatusTest) return; - - textOnTcpStatusTest = value; - - SetProperty(ref textOnTcpStatusTest, value); - } - } - - private PackIconMaterialKind tcpTestIcon = PackIconMaterialKind.TestTubeOff; - public PackIconMaterialKind TcpTestIcon - { - get => tcpTestIcon; - set - { - if (value == tcpTestIcon) return; - - tcpTestIcon = value; - - SetProperty(ref tcpTestIcon, value); - } - } - - #endregion - - #region Status UDP test toolbar - - private string textOnUdpStatusTest = mUdpTestClientStatusNotRunning; - public string TextOnUdpStatusTest - { - get => textOnUdpStatusTest; - set - { - if (value == textOnUdpStatusTest) return; - - textOnUdpStatusTest = value; - - SetProperty(ref textOnUdpStatusTest, value); - } - } - - private PackIconMaterialKind udpTestIcon = PackIconMaterialKind.TestTubeOff; - public PackIconMaterialKind UdpTestIcon - { - get => udpTestIcon; - set - { - if (value == udpTestIcon) return; - - udpTestIcon = value; - - SetProperty(ref udpTestIcon, value); - } - } - - #endregion - - #region Param managment - - #region TCP - - private bool serverIpTcpBoxIsEnabled; - /// - /// The state of this element (on/off) depends on the state of other input fields (linked via Binding ElementName) - /// If true, then the test is running, false otherwise - /// - public bool ServerIpTcpBoxIsEnabled - { - get => serverIpTcpBoxIsEnabled; - set - { - if (value == serverIpTcpBoxIsEnabled) return; - serverIpTcpBoxIsEnabled = value; - - SetProperty (ref serverIpTcpBoxIsEnabled, value); - } - } - #endregion - - #region UDP - - private bool serverIpUdpBoxIsEnabled; - /// - /// The state of this element (on/off) depends on the state of other input fields (linked via Binding ElementName) - /// If true, then the test is running, false otherwise - /// - public bool ServerIpUdpBoxIsEnabled - { - get => serverIpUdpBoxIsEnabled; - set - { - if (value == serverIpUdpBoxIsEnabled) return; - serverIpUdpBoxIsEnabled = value; - - SetProperty(ref serverIpUdpBoxIsEnabled, value); - } - } - - #endregion - - #endregion - - #region StatusBar Icons and Text manage - - #region TCP - - private void TcpStatusBarManager(bool isTestRun) - { - if (isTestRun) - { - ServerIpTcpBoxIsEnabled = false; - ProgressRingTcp = true; - TextOnTcpStatusTest = mTcpTestClientStatusRunning; - TcpTestIcon = PackIconMaterialKind.TestTube; - return; - } - - ServerIpTcpBoxIsEnabled = true; - ProgressRingTcp = false; - TextOnTcpStatusTest = mTcpTestClientStatusNotRunning; - TcpTestIcon = PackIconMaterialKind.TestTubeOff; - } - - #endregion - - #region UDP - - private void UdpStatusBarManager(bool isTestRun) - { - if (isTestRun) - { - ServerIpUdpBoxIsEnabled = false; - ProgressRingUdp = true; - TextOnUdpStatusTest = mUdpTestClientStatusRunning; - UdpTestIcon = PackIconMaterialKind.TestTube; - return; - } - - ServerIpUdpBoxIsEnabled = true; - ProgressRingUdp = false; - TextOnUdpStatusTest = mUdpTestClientStatusNotRunning; - UdpTestIcon = PackIconMaterialKind.TestTubeOff; - } - - #endregion - - #endregion - - #region TCP methods - - private void ClearTcpResultField() - { - PublishTcpResultCount = 0; - - //time result - TotalTimeTcpTest = "--:--:--"; - StartTcpTestTime = "--:--:--"; - FinishTcpTestTime = "--:--:--"; - - //data result - DataTcpCounter = "------"; - DataTcpThroughput = "------"; - - //message result - MessageTcpCounter = "------"; - MessageTcpLatency = "------"; - MessageTcpThroughput = "------"; - - //error result - ErrorTcpCounter = "------"; - ErrorTcpMessage = "------"; - } - - private void PublishTcpResults() - { - PublishTcpResultCount++; - - //time result - TotalTimeTcpTest = Utilities.GenerateTimePeriod((TcpTestRunHelper.TimestampStop - TcpTestRunHelper.TimestampStart).TotalMilliseconds); - StartTcpTestTime = TcpTestRunHelper.TimestampStart.ToLocalTime().ToLongTimeString(); - FinishTcpTestTime = TcpTestRunHelper.TimestampStop.ToLocalTime().ToLongTimeString(); - - if (TcpTestRunHelper.TotalBytes == 0) return; - - //data result - DataTcpCounter = Utilities.GenerateDataSize(TcpTestRunHelper.TotalBytes); - DataTcpThroughput = $"{Utilities.GenerateDataSize(TcpTestRunHelper.TotalBytes / (TcpTestRunHelper.TimestampStop - TcpTestRunHelper.TimestampStart).TotalSeconds)}/s"; - - //message result - MessageTcpCounter = TcpTestRunHelper.TotalMessages.ToString(); - MessageTcpLatency = $"{Utilities.GenerateTimePeriod((TcpTestRunHelper.TimestampStop - TcpTestRunHelper.TimestampStart).TotalMilliseconds / TcpTestRunHelper.TotalMessages)}"; - MessageTcpThroughput = $"{(long)(TcpTestRunHelper.TotalMessages / (TcpTestRunHelper.TimestampStop - TcpTestRunHelper.TimestampStart).TotalSeconds)} msg/s"; - - //error result - ErrorTcpCounter = TcpTestRunHelper.TotalErrors.ToString(); - ErrorTcpMessage = TcpTestRunHelper.LastErrorMessage; - - if (string.IsNullOrEmpty(TcpTestRunHelper.LastErrorMessage)) - { - ErrorTcpMessage = "Нет ошибок"; - } - - TcpStatusBarManager(false); - NetworkWindowActivated = true; - } - - private List SaveTcpResultsToList() - { - List tcpResults = new() - { - $"Time results", - $"StartTcpTestTime {StartTcpTestTime}", - $"FinishTcpTestTime {FinishTcpTestTime}", - $"FactTotalTimeTcpTest {TotalTimeTcpTest}", - $"", - $"Data results", - $"DataTcpCounter {DataTcpCounter}", - $"MessageTcpCounter {MessageTcpCounter}", - $"DataTcpThroughput {DataTcpThroughput}", - $"MessageTcpLatency {MessageTcpLatency}", - $"MessageTcpThroughput {MessageTcpThroughput}", - $"ErrorTcpCounter {ErrorTcpCounter}", - $"LastErrorTcpMessage {ErrorTcpMessage}", - $"", - $"Test parameters", - $"BenchmarkTestServerIp {Properties.Settings.Default.BenchmarkTestServerIp}", - $"BenchmarkTcpTestPort {Properties.Settings.Default.BenchmarkTcpTestPort}", - $"BenchmarkTcpSizeByteArray {Properties.Settings.Default.BenchmarkTcpSizeByteArray}", - $"BenchmarkTestTcpTime {Properties.Settings.Default.BenchmarkTestTcpTime}", - $"BenchmarkTestTcpMessageQty {Properties.Settings.Default.BenchmarkTestTcpMessageQty}", - $"BenchmarkTestTcpClientsQty {Properties.Settings.Default.BenchmarkTestTcpClientsQty}" - }; - - return tcpResults; - } - - #endregion - - #region UDP methods - - private void ClearUdpResultField() - { - PublishUdpResultCount = 0; - //time result - TotalTimeUdpTest = "--:--:--"; - StartUdpTestTime = "--:--:--"; - FinishUdpTestTime = "--:--:--"; - - //data result - DataUdpCounter = "------"; - DataUdpThroughput = "------"; - - //message result - MessageUdpCounter = "------"; - MessageUdpLatency = "------"; - MessageUdpThroughput = "------"; - - //error result - ErrorUdpCounter = "------"; - ErrorUdpMessage = "------"; - } - - private void PublishUdpResults() - { - PublishUdpResultCount++; - - //time result - TotalTimeUdpTest = Utilities.GenerateTimePeriod((UdpTestRunHelper.TimestampStop - UdpTestRunHelper.TimestampStart).TotalMilliseconds); - StartUdpTestTime = UdpTestRunHelper.TimestampStart.ToLocalTime().ToLongTimeString(); - FinishUdpTestTime = UdpTestRunHelper.TimestampStop.ToLocalTime().ToLongTimeString(); - - if (UdpTestRunHelper.TotalBytes == 0) return; - - //data result - DataUdpCounter = Utilities.GenerateDataSize(UdpTestRunHelper.TotalBytes); - DataUdpThroughput = $"{Utilities.GenerateDataSize(UdpTestRunHelper.TotalBytes / (UdpTestRunHelper.TimestampStop - UdpTestRunHelper.TimestampStart).TotalSeconds)}/s"; - - //message result - MessageUdpCounter = UdpTestRunHelper.TotalMessages.ToString(); - MessageUdpLatency = $"{Utilities.GenerateTimePeriod((UdpTestRunHelper.TimestampStop - UdpTestRunHelper.TimestampStart).TotalMilliseconds / UdpTestRunHelper.TotalMessages)}"; - MessageUdpThroughput = $"{(long)(UdpTestRunHelper.TotalMessages / (UdpTestRunHelper.TimestampStop - UdpTestRunHelper.TimestampStart).TotalSeconds)} msg/s"; - - //error result - ErrorUdpCounter = UdpTestRunHelper.TotalErrors.ToString(); - ErrorUdpMessage = UdpTestRunHelper.LastErrorMessage; - - if (string.IsNullOrEmpty(UdpTestRunHelper.LastErrorMessage)) - { - ErrorUdpMessage = "Нет ошибок"; - } - - UdpStatusBarManager(false); - - NetworkWindowActivated = true; - } - - private List SaveUdpResultsToList() - { - List tcpResults = new() - { - $"Time results", - $"StartUdpTestTime {StartUdpTestTime}", - $"FinishTcpTestTime {FinishUdpTestTime}", - $"FactTotalTimeTcpTest {TotalTimeUdpTest}", - $"", - $"Data results", - $"DataTcpCounter {DataUdpCounter}", - $"MessageTcpCounter {MessageUdpCounter}", - $"DataTcpThroughput {DataUdpThroughput}", - $"MessageTcpLatency {MessageUdpLatency}", - $"MessageTcpThroughput {MessageUdpThroughput}", - $"ErrorTcpCounter {ErrorUdpCounter}", - $"LastErrorTcpMessage {ErrorUdpMessage}", - $"", - $"Test parameters", - $"BenchmarkTestServerIp {Properties.Settings.Default.BenchmarkTestServerIp}", - $"BenchmarkTcpTestPort {Properties.Settings.Default.BenchmarkUdpTestPort}", - $"BenchmarkTcpTestPort {Properties.Settings.Default.BenchmarkUdpSizeByteArray}", - $"BenchmarkTcpSizeByteArray {Properties.Settings.Default.BenchmarkUdpSizeByteArray}", - $"BenchmarkTestTcpTime {Properties.Settings.Default.BenchmarkTestUdpTime}", - $"BenchmarkTestTcpMessageQty {Properties.Settings.Default.BenchmarkTestUdpMessageQty}", - $"BenchmarkTestTcpClientsQty {Properties.Settings.Default.BenchmarkTestUdpClientsQty}" - }; - - return tcpResults; - } - - #endregion - - #region Common methods - - private static string ConvertListToString(IList results = null, IList envParams = null) - { - string tempResults = string.Empty; - - if(envParams != null) - { - foreach (string @string in envParams) - { - tempResults += $"{@string}\n"; - } - } - - if(results != null) - { - foreach (string @string in results) - { - tempResults += $"{@string}\n"; - } - } - - return tempResults; - } - - /// - /// Writes environment parameters to a string array - /// - /// Use the short format when you need to get basic information about the environment - private IList SaveEnvironmentParametersToList(bool shortFormat) - { - List envParams = shortFormat - ? (new() - { - $"Environment parameters", - $"MachineName {MachineName}", - $"OSVersion {OSVersion}", - $"OSDescription {OSDescription}", - $"" - }) - : (new() - { - $"ProcessorCount {ProcessorCount}", - $"Is64BitOperatingSystem {Is64BitOperatingSystem}", - $"Is64BitProcess {Is64BitProcess}", - $"MachineName {MachineName}", - $"OSVersion {OSVersion}", - $"OSDescription {OSDescription}", - $"UserName {UserName}", - $"TickCount {TickCount}", - $"WorkingSet {WorkingSet}", - $"" - }); - - return envParams; - } - - private void OnCloseWindow() - { - if (TcpTestRunHelper.IsTestRun) - { - TcpTestRunHelper.AbortTest(); - } - - if (UdpTestRunHelper.IsTestRun) - { - UdpTestRunHelper.AbortTest(); - } - - mComunicateTestHelper.DisconnectAndDestroy(); - - SendApiComunicateCommand(ServerCommand.Stop); - Properties.Settings.Default.Save(); - } - - #endregion - - #region Api Calls - - private void SendApiComunicateCommand(ServerCommand command) - { - BaseApi.SendCommand(command, "BenchmarkStateTcpServer"); - BaseApi.SendCommand(command, "BenchmarkTcpServer"); - BaseApi.SendCommand(command, "BenchmarkUdpServer"); - } - - #endregion - - #region Commands - - #region TCP commands - - private DelegateCommand stopTcpBenchmarkTest; - public DelegateCommand StopTcpBenchmarkTest => stopTcpBenchmarkTest ??= new DelegateCommand(() => - { - TcpTestRunHelper.AbortTest(); - }); - - private DelegateCommand clearTcpTestResult; - public DelegateCommand ClearTcpTestResult => clearTcpTestResult ??= new DelegateCommand(() => - { - ClearTcpResultField(); - }, () => PublishTcpResultCount > 0); - - private DelegateCommand startTcpBenchmarkTest; - public DelegateCommand StartTcpBenchmarkTest => startTcpBenchmarkTest ??= new DelegateCommand(async () => - { - TcpStatusBarManager(true); - - await Dispatcher.Yield(DispatcherPriority.Normal); - await Task.Run (() => TcpTestRunHelper.Run()); - - PublishTcpResults(); - }, () => IsTcpClientConnected == true); - - #endregion - - #region UDP commands - - private DelegateCommand stopUdpBenchmarkTest; - public DelegateCommand StopUdpBenchmarkTest => stopUdpBenchmarkTest ??= new DelegateCommand(() => - { - UdpTestRunHelper.AbortTest(); - }); - - private DelegateCommand clearUdpTestResult; - public DelegateCommand ClearUdpTestResult => clearUdpTestResult ??= new DelegateCommand(() => - { - ClearUdpResultField(); - }, () => PublishUdpResultCount > 0); - - private DelegateCommand startUdpBenchmarkTest; - public DelegateCommand StartUdpBenchmarkTest => startUdpBenchmarkTest ??= new DelegateCommand(async () => - { - UdpStatusBarManager(true); - - await Dispatcher.Yield(DispatcherPriority.Normal); - await Task.Run(() => UdpTestRunHelper.Run()); - - PublishUdpResults(); - }, () => IsTcpClientConnected == true); - - - #endregion - - #region Test client connect commands - - private DelegateCommand connectButtonComand; - public DelegateCommand ConnectButtonComand => connectButtonComand ??= new DelegateCommand(async () => - { - await Dispatcher.Yield(DispatcherPriority.Normal); - - if (mComunicateTestHelper.TcpClientIsConnected) - { - await Task.Run(() => mComunicateTestHelper.Disconnect()); - return; - } - - if (!mComunicateTestHelper.TcpClientIsConnected) - { - await Task.Run(() => mComunicateTestHelper.Connect()); - return; - } - }); - - #endregion - - #region Saved/Copy buttons commands - - private DelegateCommand copyResults; - public DelegateCommand CopyResults => copyResults ??= new DelegateCommand(() => - { - IList envParamsShort = null; - - if (Properties.Settings.Default.BenchmarkAddEnvironmentParametersToResult) - { - envParamsShort = SaveEnvironmentParametersToList(true); - } - - switch (SelectedTabIndex) - { - case 0: - { - IList envParamsFull = SaveEnvironmentParametersToList(false); - string results = ConvertListToString(envParams: envParamsFull); - Clipboard.SetText(results); - break; - } - case 1: - { - IList tcpResults = SaveTcpResultsToList(); - string results = ConvertListToString(tcpResults, envParamsShort); - Clipboard.SetText(results); - break; - } - case 2: - { - IList udpResults = SaveUdpResultsToList(); - string results = ConvertListToString(udpResults, envParamsShort); - Clipboard.SetText(results); - break; - } - - default: - break; - } - }); - - private DelegateCommand saveResults; - - public DelegateCommand SaveResults => saveResults ??= new DelegateCommand(() => - { - IList envParamsShort = null; - - if (Properties.Settings.Default.BenchmarkAddEnvironmentParametersToResult) - { - envParamsShort = SaveEnvironmentParametersToList(true); - } - - switch (SelectedTabIndex) - { - case 0: - { - IList envParamsFull = SaveEnvironmentParametersToList(false); - string results = ConvertListToString(envParams: envParamsFull); - FileSaveDialog(results, "Сохранить параметры окружения", "EnvironmentParameters"); - break; - } - case 1: - { - IList tcpResults = SaveTcpResultsToList(); - string results = ConvertListToString(tcpResults, envParamsShort); - FileSaveDialog(results, "Сохранить результаты TCP RoundTrip теста", $"TCP benchmark results {DateTime.Now:HH-mm-ss.ff}"); - break; - } - case 2: - { - IList udpResults = SaveUdpResultsToList(); - string results = ConvertListToString(udpResults, envParamsShort); - FileSaveDialog(results, "Сохранить результаты UDP RoundTrip теста", $"UDP benchmark results {DateTime.Now:HH-mm-ss.ff}"); - break; - } - - default: - break; - } - - }); - - private async void FileSaveDialog(string file, string title, string fileName) - { - - if (IDialogManager.ShowSaveFileDialog(title, Properties.Settings.Default.SavedResultsNetworkTestsFolderPath, fileName, ".txt", "TXT documents (.txt)|*.txt")) - { - string path = IDialogManager.FilePathToSave; - await FileHelper.WriteAsync(path, file); - } - else - { - //AppLogStatusBarAction("Файл не сохранен"); - } - } - - #endregion - - #endregion - - } -} diff --git a/AdamController.Core/Dialog.Views/NetworkTestView.xaml b/AdamController.Core/Dialog.Views/NetworkTestView.xaml deleted file mode 100644 index e31de7e..0000000 --- a/AdamController.Core/Dialog.Views/NetworkTestView.xaml +++ /dev/null @@ -1,1443 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/AdamController.Core/Dialog.Views/NetworkTestView.xaml.cs b/AdamController.Core/Dialog.Views/NetworkTestView.xaml.cs deleted file mode 100644 index 6d7d1d2..0000000 --- a/AdamController.Core/Dialog.Views/NetworkTestView.xaml.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Windows.Controls; - -namespace AdamController.Core.Dialog.Views -{ - public partial class NetworkTestView : UserControl - { - public NetworkTestView() - { - InitializeComponent(); - } - } -} diff --git a/AdamController.Core/DialogNames.cs b/AdamController.Core/DialogNames.cs index c52764a..468627e 100644 --- a/AdamController.Core/DialogNames.cs +++ b/AdamController.Core/DialogNames.cs @@ -5,6 +5,5 @@ namespace AdamController.Core public class DialogNames { public const string SettingsDialog = nameof(SettingsView); - public const string NetworkTestDialog = nameof(NetworkTestView); } } diff --git a/AdamController.Core/Extensions/DialogServiceExtension.cs b/AdamController.Core/Extensions/DialogServiceExtension.cs index 0ff2baf..71f72b3 100644 --- a/AdamController.Core/Extensions/DialogServiceExtension.cs +++ b/AdamController.Core/Extensions/DialogServiceExtension.cs @@ -9,10 +9,5 @@ public static void ShowSettingsDialog(this IDialogService dialogService) { dialogService.ShowDialog(nameof(SettingsView)); } - - public static void ShowNetworkTestDialog(this IDialogService dialogService) - { - dialogService.ShowDialog(nameof(NetworkTestView)); - } } } diff --git a/AdamController.Core/Helpers/ComunicateBenchmarkHelper.cs b/AdamController.Core/Helpers/ComunicateBenchmarkHelper.cs deleted file mode 100644 index 2820cfb..0000000 --- a/AdamController.Core/Helpers/ComunicateBenchmarkHelper.cs +++ /dev/null @@ -1,132 +0,0 @@ - -using AdamController.Core.Properties; -using AdamController.Services; -using AdamController.Services.AdamTcpClientDependency; -using System.Threading; - -namespace AdamController.Core.Helpers -{ - - public sealed class ComunicateBenchmarkHelper - { - #region Singelton - - private static readonly object @lock = new(); - private static ComunicateBenchmarkHelper instance = null; - - public static ComunicateBenchmarkHelper Instance - { - get - { - if (instance != null) - { - LazyInitializer(); - return instance; - } - - Monitor.Enter(@lock); - ComunicateBenchmarkHelper temp = new(); - - _ = Interlocked.Exchange(ref instance, temp); - Monitor.Exit(@lock); - return instance; - } - } - - #endregion - - #region Declaration delegates and events - - public delegate void OnTcpCientConnected(); - public static event OnTcpCientConnected OnTcpConnected; - - public delegate void OnTcpClientDisconnect(); - public static event OnTcpClientDisconnect OnTcpDisconnected; - - public delegate void OnTcpClientReconnected(int reconnectCount); - public static event OnTcpClientReconnected OnTcpReconnected; - - #endregion - - public bool TcpClientIsConnected => mAdamTcpClient != null && mAdamTcpClient.IsConnected; - - private static AdamTcpClientService mAdamTcpClient; - - #region ~ - - static ComunicateBenchmarkHelper() - { - LazyInitializer(); - } - - private static void LazyInitializer() - { - if(mAdamTcpClient == null) - { - AdamTcpClientOption option = new() - { - ReconnectCount = Settings.Default.ReconnectQtyBenchmarkComunicateTcpClient, - ReconnectTimeout = Settings.Default.ReconnectTimeoutBenchmarkComunicateTcpClient - }; - - mAdamTcpClient = new(Settings.Default.BenchmarkTestServerIp, Settings.Default.BenchmarkTcpConnectStatePort, option); - } - - mAdamTcpClient.RaiseTcpCientConnected += TcpCientConnected; - mAdamTcpClient.RaiseTcpClientDisconnected += TcpClientDisconnected; - mAdamTcpClient.RaiseTcpClientReconnected += TcpClientReconnected; - } - - #endregion - - #region Client events - - private static void TcpClientDisconnected(object sender) - { - OnTcpDisconnected?.Invoke(); - } - - private static void TcpCientConnected(object sender) - { - OnTcpConnected?.Invoke(); - } - - private static void TcpClientReconnected(object sender, int reconnectCount) - { - OnTcpReconnected?.Invoke(reconnectCount); - } - - #endregion - - #region Tcp connect - - public void Connect() - { - _ = mAdamTcpClient?.ConnectAsync(); - } - - #endregion - - # region Tcp disconnect - - public void Disconnect() - { - mAdamTcpClient?.DisconnectAndStop(); - } - - public void DisconnectAndDestroy() - { - Disconnect(); - - if(mAdamTcpClient != null) - { - mAdamTcpClient.RaiseTcpCientConnected -= TcpCientConnected; - mAdamTcpClient.RaiseTcpClientDisconnected -= TcpClientDisconnected; - mAdamTcpClient.RaiseTcpClientReconnected -= TcpClientReconnected; - mAdamTcpClient = null; - } - } - - #endregion - } -} diff --git a/AdamController.Core/Helpers/ComunicateHelper.cs b/AdamController.Core/Helpers/ComunicateHelper.cs deleted file mode 100644 index fcbb8f1..0000000 --- a/AdamController.Core/Helpers/ComunicateHelper.cs +++ /dev/null @@ -1,250 +0,0 @@ -using AdamController.Core.Properties; -using AdamController.Services; -using AdamController.Services.AdamTcpClientDependency; -using System; -using System.Net; -using System.Net.Sockets; -using System.Text; -using System.Threading.Tasks; - -namespace AdamController.Core.Helpers -{ - [Obsolete] - public sealed class ComunicateHelper - { - #region Declaration delegates and events - - //public delegate void OnAdamTcpCientConnected(); - //public static event OnAdamTcpCientConnected OnAdamTcpConnectedEvent; - - //public delegate void OnAdamTcpClientDisconnect(); - //public static event OnAdamTcpClientDisconnect OnAdamTcpDisconnectedEvent; - - //public delegate void OnAdamTcpClientReconnected(int reconnectCount); - //public static event OnAdamTcpClientReconnected OnAdamTcpReconnected; - - //public delegate void OnAdamUdpServerReceived(string message); - //public static event OnAdamUdpServerReceived OnAdamLogServerUdpReceivedEvent; - - //public delegate void OnAdamUdpMessageReceived(string message); - //public static event OnAdamUdpMessageReceived OnAdamMessageReceivedEvent; - - #endregion - - //public static bool TcpClientIsConnected => mAdamTcpClient != null && mAdamTcpClient.IsConnected; - - //private static AdamTcpClientService mAdamTcpClient; - //private static AdamUdpClient mAdamUdpMessageClient; - //private static AdamUdpServer mAdamUdpLogServer; - //private static AdamWebSocketClient mAdamWebSocketClient; - - #region ~ - - static ComunicateHelper() - { - //LazyInitializer(); - } - - private static void LazyInitializer() - { - //if(mAdamTcpClient == null) - //{ - //AdamTcpClientOption option = new() - //{ - // ReconnectCount = Settings.Default.ReconnectQtyComunicateTcpClient, - // ReconnectTimeout = Settings.Default.ReconnectTimeoutComunicateTcpClient - //}; - - //mAdamTcpClient = new(Settings.Default.ServerIP, Settings.Default.TcpConnectStatePort, option); - //} - - //mAdamUdpMessageClient ??= new(IPAddress.Any, int.Parse(Settings.Default.MessageDataExchangePort)) - // { - // OptionDualMode = true, - // OptionReuseAddress = true - // }; - - //mAdamUdpLogServer ??= new(IPAddress.Any, Settings.Default.LogServerPort) - // { - // OptionDualMode = true, - // OptionReuseAddress = true - // }; - -#if DEBUG - //mAdamWebSocketClient ??= new AdamWebSocketClient(new Uri($"ws://{Settings.Default.ServerIP}:9001/adam-2.7/movement")); -#else - //mAdamWebSocketClient ??= new AdamWebSocketClient(new Uri($"ws://{Settings.Default.ServerIP}:{Settings.Default.SoketServerPort}/adam-2.7/movement")); -#endif - - - //mAdamTcpClient.RaiseTcpCientConnected += TcpCientConnected; - //mAdamTcpClient.RaiseTcpClientDisconnected += TcpClientDisconnected; - //mAdamTcpClient.RaiseTcpClientError += TcpClientError; - //mAdamTcpClient.RaiseTcpClientReceived += TcpClientReceived; - //mAdamTcpClient.RaiseTcpClientReconnected += TcpClientReconnected; - - //mAdamWebSocketClient.WebSocketConnectedEvent += WebSocketConnectedEvent; - //mAdamWebSocketClient.WebSocketClientReceivedEvent += WebSocketClientReceived; - //mAdamWebSocketClient.WebSocketClientDisconnectedEvent += WebSocketClientDisconnectedEvent; - - //mAdamUdpMessageClient.UdpClientReceived += MessageClientUdpReceived; - //mAdamUdpLogServer.UdpServerReceived += UdpServerReceived; - } - - private static void WebSocketClientDisconnectedEvent() - { - //throw new System.NotImplementedException(); - } - - private static void WebSocketClientReceived(string text) - { - //throw new System.NotImplementedException(); - } - - private static void WebSocketConnectedEvent() - { - //throw new System.NotImplementedException(); - } - - //private static void MessageClientUdpReceived(EndPoint endpoint, byte[] buffer, long offset, long size) - //{ - // string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); - // OnAdamMessageReceivedEvent?.Invoke(encodedMessage); - //} - - #endregion - - #region Udp Server events - - //private static void UdpServerReceived(EndPoint endpoint, byte[] buffer, long offset, long size) - //{ - // string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); - // OnAdamLogServerUdpReceivedEvent?.Invoke(encodedMessage); - //} - - #endregion - - #region TCP Client events - - //private static void TcpClientReceived(object sender, byte[] buffer, long offset, long size) {} - - //private static void TcpClientError(object sender, SocketError error) {} - - private static void TcpClientDisconnected(object sender) - { - //OnAdamTcpDisconnectedEvent?.Invoke(); - - //if (mAdamUdpLogServer != null) - //{ - // if (mAdamUdpLogServer.IsStarted) - // mAdamUdpLogServer?.Stop(); - //} - - //if(mAdamWebSocketClient != null) - //{ - //if (mAdamWebSocketClient.IsRunning) - // mAdamWebSocketClient.DisconnectAsync(); - //} - } - - private static void TcpCientConnected(object sender) - { - //OnAdamTcpConnectedEvent?.Invoke(); - - //if(!mAdamUdpLogServer.IsStarted) - // mAdamUdpLogServer?.Start(); - - //if (!mAdamWebSocketClient.IsStarted) - //mAdamWebSocketClient.ConnectAsync(); - } - - //private static void TcpClientReconnected(object sender, int reconnectCount) - //{ - // OnAdamTcpReconnected?.Invoke(reconnectCount); - //} - - #endregion - - #region Tcp/Udp connect - - //private static void Connect() - //{ - //_ = Task.Run(() => mAdamTcpClient?.ConnectAsync()); - //_ = Task.Run(() => mAdamUdpMessageClient?.Start()); - //_ = Task.Run(() => mAdamWebSocketClient?.ConnectAsync()); - //} - - //public static void ConnectAllAsync() - //{ - //_ = Task.Run(() => Connect()); - //} - - #endregion - - # region Tcp/Upd disconnect - - //public static void DisconnectAll() - //{ - //_ = Task.Run(()=> mAdamTcpClient?.DisconnectAndStop()); - //_ = Task.Run(() => mAdamUdpMessageClient?.Stop()); - //_ = Task.Run(() => mAdamWebSocketClient?.DisconnectAsync()); - //} - - public static void DisconnectAllAndDestroy() - { - //DisconnectAll(); - - //if(mAdamTcpClient != null) - //{ - //mAdamTcpClient.RaiseTcpCientConnected -= TcpCientConnected; - //mAdamTcpClient.RaiseTcpClientDisconnected -= TcpClientDisconnected; - //mAdamTcpClient.RaiseTcpClientError -= TcpClientError; - //mAdamTcpClient.RaiseTcpClientReceived -= TcpClientReceived; - //mAdamTcpClient.RaiseTcpClientReconnected -= TcpClientReconnected; - - // mAdamTcpClient = null; - //} - - //if(mAdamUdpLogServer != null) - //{ - // mAdamUdpLogServer.UdpServerReceived -= UdpServerReceived; - // mAdamUdpLogServer = null; - //} - - //if(mAdamUdpMessageClient != null) - //{ - //mAdamUdpMessageClient.UdpClientReceived -= MessageClientUdpReceived; - //mAdamUdpLogServer = null; - //} - - //if(mAdamWebSocketClient != null) - //{ - // mAdamWebSocketClient.WebSocketConnectedEvent -= WebSocketConnectedEvent; - // mAdamWebSocketClient.WebSocketClientReceivedEvent -= WebSocketClientReceived; - // mAdamWebSocketClient.WebSocketClientDisconnectedEvent -= WebSocketClientDisconnectedEvent; - //mAdamWebSocketClient.Dispose(); - //} - } - - #endregion - - #region Tcp/Udp/WebSocket send message - - //public static void SendTcpMessage(string message) - //{ - // mAdamTcpClient.Send(message); - //} - - //public static void SendTcpMessageAsync(string message) - //{ - // _ = Task.Run(() => SendTcpMessage(message)); - //} - - //public static void WebSocketSendTextMessage(string message) - //{ - //Task.Run(() => mAdamWebSocketClient.SendTextAsync(message)); - //} - - #endregion - } -} diff --git a/AdamController.Core/Helpers/TcpTestRunHelper.cs b/AdamController.Core/Helpers/TcpTestRunHelper.cs deleted file mode 100644 index 3508bbb..0000000 --- a/AdamController.Core/Helpers/TcpTestRunHelper.cs +++ /dev/null @@ -1,123 +0,0 @@ - -using AdamController.Services; -using System; -using System.Collections.Generic; -using System.Threading; - -namespace AdamController.Core.Helpers -{ - public class TcpTestRunHelper - { - public static string LastErrorMessage { get; internal set; } = string.Empty; - public static long TotalErrors { get; internal set; } = 0; - public static long TotalBytes { get; internal set; } = 0; - public static DateTime TimestampStop { get; internal set; } = DateTime.UtcNow; - public static DateTime TimestampStart { get; private set; } = DateTime.UtcNow; - public static long TotalMessages { get; private set; } = 0; - public static bool IsTestRun { get; private set; } - - private static byte[] mMessageToSend; - private static string mAddress; - private static int mPort; - private static int mClientsQty; - private static int mMessagesQty; - private static int mSize; - private static int mTestTime; - private static List mAdamClients; - - private static CancellationTokenSource mTokenSource; - - public static void Run() - { - IsTestRun = true; - mTokenSource = new CancellationTokenSource(); - - ClearResultField(); - InitTestParam(); - - mAdamClients = new(); - mMessageToSend = new byte[mSize]; - - for (int i = 0; i < mClientsQty; ++i) - { - AdamTestTcpClient client = new(mAddress, mPort, mMessagesQty, mMessageToSend); - - mAdamClients.Add(client); - } - - TimestampStart = DateTime.UtcNow; - - foreach (AdamTestTcpClient client in mAdamClients) - { - _ = client.ConnectAsync(); - } - - foreach (AdamTestTcpClient client in mAdamClients) - { - while (!client.IsConnected) - { - _ = Thread.Yield(); - } - } - - _ = mTokenSource.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(mTestTime)); - - Stop(); - } - - private static void Stop() - { - IsTestRun = false; - - if (mAdamClients == null) return; - - TimestampStop = DateTime.UtcNow; - - foreach (AdamTestTcpClient client in mAdamClients) - { - TotalBytes += client.TotalBytes; - LastErrorMessage += client.LastErrorMessage; - TotalErrors += client.TotalErrors; - - _ = client.DisconnectAsync(); - } - - foreach (AdamTestTcpClient client in mAdamClients) - { - while (client.IsConnected) - { - _ = Thread.Yield(); - } - } - - mTokenSource.Dispose(); - - TotalMessages = TotalBytes / mSize; - } - - public static void AbortTest() - { - mTokenSource.Cancel(); - } - - private static void InitTestParam() - { - mAddress = Properties.Settings.Default.BenchmarkTestServerIp; - mPort = Properties.Settings.Default.BenchmarkTcpTestPort; - mClientsQty = Properties.Settings.Default.BenchmarkTestTcpClientsQty; - mMessagesQty = Properties.Settings.Default.BenchmarkTestTcpMessageQty; - mSize = Properties.Settings.Default.BenchmarkTcpSizeByteArray; - mTestTime = Properties.Settings.Default.BenchmarkTestTcpTime; - } - - private static void ClearResultField() - { - LastErrorMessage = string.Empty; - TotalErrors = 0; - TotalBytes = 0; - TimestampStart = DateTime.UtcNow; - TimestampStop = DateTime.UtcNow; - TotalMessages = 0; - } - } -} diff --git a/AdamController.Core/Helpers/UdpTestRunHelper.cs b/AdamController.Core/Helpers/UdpTestRunHelper.cs deleted file mode 100644 index 934f8ac..0000000 --- a/AdamController.Core/Helpers/UdpTestRunHelper.cs +++ /dev/null @@ -1,121 +0,0 @@ -using AdamController.Services; -using System; -using System.Collections.Generic; -using System.Threading; - -namespace AdamController.Core.Helpers -{ - public class UdpTestRunHelper - { - public static string LastErrorMessage { get; internal set; } = string.Empty; - public static long TotalErrors { get; internal set; } = 0; - public static long TotalBytes { get; internal set; } = 0; - public static DateTime TimestampStop { get; internal set; } = DateTime.UtcNow; - public static DateTime TimestampStart { get; private set; } = DateTime.UtcNow; - public static long TotalMessages { get; set; } = 0; - public static bool IsTestRun { get; private set; } - - private static byte[] mMessageToSend; - private static string mAddress; - private static int mPort; - private static int mClientsQty; - private static int mMessagesQty; - private static int mSize; - private static int mSeconds; - private static List mAdamClients; - - private static CancellationTokenSource mTokenSource; - - public static void Run() - { - IsTestRun = true; - mTokenSource = new CancellationTokenSource(); - - ClearResultField(); - InitTestParam(); - - mAdamClients = new(); - mMessageToSend = new byte[mSize]; - - for (int i = 0; i < mClientsQty; ++i) - { - AdamUdpTestClient client = new (mAddress, mPort, mMessagesQty, mMessageToSend); - mAdamClients.Add(client); - } - - TimestampStart = DateTime.UtcNow; - - foreach (AdamUdpTestClient client in mAdamClients) - { - _ = client.Connect(); - } - - foreach (AdamUdpTestClient client in mAdamClients) - { - while (!client.IsConnected) - { - _ = Thread.Yield(); - } - } - - _ = mTokenSource.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(mSeconds)); - - Stop(); - } - - private static void Stop() - { - IsTestRun = false; - if (mAdamClients == null) return; - - TimestampStop = DateTime.UtcNow; - - foreach (AdamUdpTestClient client in mAdamClients) - { - TotalBytes += client.TotalBytes; - LastErrorMessage += client.LastErrorMessage; - TotalErrors += client.TotalErrors; - - _ = client.Disconnect(); - } - - foreach (AdamUdpTestClient client in mAdamClients) - { - while (client.IsConnected) - { - _ = Thread.Yield(); - } - } - - mTokenSource.Dispose(); - - //? - TotalMessages = TotalBytes / mSize; - } - - public static void AbortTest() - { - mTokenSource.Cancel(); - } - - private static void InitTestParam() - { - mAddress = Properties.Settings.Default.BenchmarkTestServerIp; - mPort = Properties.Settings.Default.BenchmarkUdpTestPort; - mClientsQty = Properties.Settings.Default.BenchmarkTestUdpClientsQty; - mMessagesQty = Properties.Settings.Default.BenchmarkTestUdpMessageQty; - mSize = Properties.Settings.Default.BenchmarkUdpSizeByteArray; - mSeconds = Properties.Settings.Default.BenchmarkTestUdpTime; - } - - private static void ClearResultField() - { - LastErrorMessage = string.Empty; - TotalErrors = 0; - TotalBytes = 0; - TimestampStart = DateTime.UtcNow; - TimestampStop = DateTime.UtcNow; - TotalMessages = 0; - } - } -} diff --git a/AdamController.Core/Model/AppLanguageModel.cs b/AdamController.Core/Model/AppLanguageModel.cs index a6c516e..9e70b40 100644 --- a/AdamController.Core/Model/AppLanguageModel.cs +++ b/AdamController.Core/Model/AppLanguageModel.cs @@ -8,34 +8,14 @@ public class AppLanguageModel : BindableBase public string AppLanguage { get => appLanguage; - set - { - if (value == appLanguage) - { - return; - } - - appLanguage = value; - - SetProperty(ref appLanguage, value); - } + set => SetProperty(ref appLanguage, value); } private string languageName; public string LanguageName { get => languageName; - set - { - if (value == languageName) - { - return; - } - - languageName = value; - - SetProperty (ref languageName, value); - } + set => SetProperty(ref languageName, value); } } } diff --git a/AdamController.Core/Model/BlocklyLanguageModel.cs b/AdamController.Core/Model/BlocklyLanguageModel.cs index 23121c7..f063f56 100644 --- a/AdamController.Core/Model/BlocklyLanguageModel.cs +++ b/AdamController.Core/Model/BlocklyLanguageModel.cs @@ -8,33 +8,15 @@ public class BlocklyLanguageModel : BindableBase private BlocklyLanguage blocklyLanguage; public BlocklyLanguage BlocklyLanguage { - get { return blocklyLanguage; } - set - { - if (value == blocklyLanguage) - { - return; - } - - blocklyLanguage = value; - //OnPropertyChanged(nameof(BlocklyLanguage)); - } + get => blocklyLanguage; + set => SetProperty(ref blocklyLanguage, value); } private string languageName; public string LanguageName - { - get { return languageName; } - set - { - if (value == languageName) - { - return; - } - - languageName = value; - //OnPropertyChanged(nameof(LanguageName)); - } + { + get => languageName; + set => SetProperty(ref languageName, value); } } } diff --git a/AdamController.Core/Model/EditorModel.cs b/AdamController.Core/Model/EditorModel.cs index 86b9fed..529ae80 100644 --- a/AdamController.Core/Model/EditorModel.cs +++ b/AdamController.Core/Model/EditorModel.cs @@ -1,9 +1,4 @@ -using ICSharpCode.AvalonEdit.CodeCompletion; -using ICSharpCode.AvalonEdit.Document; -using ICSharpCode.AvalonEdit.Editing; -using System; - -namespace AdamController.Core.Model +namespace AdamController.Core.Model { //TODO Rename this (as Autocomplete or etc) /*public class EditorModel : ICompletionData diff --git a/AdamController.Services/AdamTestTcpClient.cs b/AdamController.Services/AdamTestTcpClient.cs deleted file mode 100644 index c4e61b5..0000000 --- a/AdamController.Services/AdamTestTcpClient.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Net.Sockets; - -namespace AdamController.Services -{ - public class AdamTestTcpClient : NetCoreServer.TcpClient - { - public long TotalBytes { get; private set; } - public long TotalErrors { get; private set; } - public string LastErrorMessage { get; private set; } = string.Empty; - - private long mReceived = 0; - private readonly long mMessageQty; - private readonly byte[] mSendMessage; - - public AdamTestTcpClient(string address, int port, int messageQty, byte[] sendMessage) : base(address, port) - { - mMessageQty = messageQty; - mSendMessage = sendMessage; - } - - protected override void OnConnected() - { - for (long i = mMessageQty; i > 0; --i) - { - SendMessage(); - } - } - - protected override void OnReceived(byte[] buffer, long offset, long size) - { - mReceived += size; - while (mReceived >= mSendMessage.Length) - { - SendMessage(); - mReceived -= mSendMessage.Length; - } - - TotalBytes += size; - } - - protected override void OnError(SocketError error) - { - LastErrorMessage = error.ToString(); - ++TotalErrors; - } - - private void SendMessage() - { - _ = SendAsync(mSendMessage); - } - } - - -} diff --git a/AdamController.Services/AdamUdpClient.cs b/AdamController.Services/AdamUdpClient.cs deleted file mode 100644 index 730796c..0000000 --- a/AdamController.Services/AdamUdpClient.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; - -namespace AdamController.Services -{ - [Obsolete] - public class AdamUdpClient : NetCoreServer.UdpServer - { - #region DelegateAndEvent - - public delegate void OnUdpClientReceived(EndPoint endpoint, byte[] buffer, long offset, long size); - public event OnUdpClientReceived UdpClientReceived; - - #endregion - - public AdamUdpClient(IPAddress address, int port) : base(address, port) { } - - protected override void OnStarted() - { - ReceiveAsync(); - } - - protected override void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size) - { - UdpClientReceived?.Invoke(endpoint, buffer, offset, size); - ReceiveAsync(); - } - - protected override void OnSent(EndPoint endpoint, long sent) - { - ReceiveAsync(); - } - - protected override void OnError(SocketError error) - { - base.OnError(error); - } - } -} diff --git a/AdamController.Services/AdamUdpServer.cs b/AdamController.Services/AdamUdpServer.cs deleted file mode 100644 index 07b531e..0000000 --- a/AdamController.Services/AdamUdpServer.cs +++ /dev/null @@ -1,37 +0,0 @@ -using NetCoreServer; -using System; -using System.Net; -using System.Net.Sockets; - -namespace AdamController.Services -{ - [Obsolete] - public class AdamUdpServer : UdpServer - { - public delegate void OnUdpServerReceived(EndPoint endpoint, byte[] buffer, long offset, long size); - public event OnUdpServerReceived UdpServerReceived; - - public AdamUdpServer(IPAddress address, int port) : base(address, port){} - - protected override void OnStarted() - { - ReceiveAsync(); - } - - protected override void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size) - { - UdpServerReceived?.Invoke(endpoint, buffer, offset, size); - ReceiveAsync(); - } - - protected override void OnSent(EndPoint endpoint, long sent) - { - ReceiveAsync(); - } - - protected override void OnError(SocketError error) - { - base.OnError(error); - } - } -} diff --git a/AdamController.Services/AdamUdpTestClient.cs b/AdamController.Services/AdamUdpTestClient.cs deleted file mode 100644 index 86adbe7..0000000 --- a/AdamController.Services/AdamUdpTestClient.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.Net; -using System.Net.Sockets; - -namespace AdamController.Services -{ - public class AdamUdpTestClient : NetCoreServer.UdpClient - { - public long TotalBytes { get; private set; } - public long TotalErrors { get; private set; } - public string LastErrorMessage { get; private set; } = string.Empty; - public byte[] mSendMessage; - - private readonly long mMessages; - - public AdamUdpTestClient(string address, int port, int messageQty, byte[] sendMessage) : base(address, port) - { - mMessages = messageQty; - mSendMessage = sendMessage; - } - - protected override void OnConnected() - { - ReceiveAsync(); - - for (long i = mMessages; i > 0; --i) - { - SendMessage(); - } - } - - protected override void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size) - { - TotalBytes += size; - - ReceiveAsync(); - SendMessage(); - } - - protected override void OnError(SocketError error) - { - LastErrorMessage = error.ToString(); - ++TotalErrors; - } - - private void SendMessage() - { - Send(mSendMessage); - } - } -} diff --git a/AdamController.Services/AdamWebSocketClient.cs b/AdamController.Services/AdamWebSocketClient.cs deleted file mode 100644 index 5afb829..0000000 --- a/AdamController.Services/AdamWebSocketClient.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Threading.Tasks; -using Websocket.Client; - -namespace AdamController.Services -{ - [Obsolete] - public class AdamWebSocketClient : IDisposable - { - - public delegate void OnWebSocketClientReceived(string text); - public event OnWebSocketClientReceived WebSocketClientReceivedEvent; - - public delegate void OnWebSocketConnected(); - public event OnWebSocketConnected WebSocketConnectedEvent; - - public delegate void OnWebSocketClientDisconnect(); - public event OnWebSocketClientDisconnect WebSocketClientDisconnectedEvent; - - private readonly WebsocketClient mWebsocketClient; - public AdamWebSocketClient(Uri url) - { - mWebsocketClient = new(url) - { - ReconnectTimeout = null - }; - - mWebsocketClient.MessageReceived.Subscribe(message => - { - WebSocketClientReceivedEvent?.Invoke(message.Text); - }); - - mWebsocketClient.DisconnectionHappened.Subscribe(eventHappened => - { - WebSocketClientDisconnectedEvent?.Invoke(); - }); - - mWebsocketClient.ReconnectionHappened.Subscribe(eventHappened => - { - WebSocketConnectedEvent?.Invoke(); - }); - } - - public bool IsStarted => mWebsocketClient.IsStarted; - - public bool IsRunning => mWebsocketClient.IsRunning; - - public Task ConnectAsync() - { - return mWebsocketClient.StartOrFail(); - } - - public Task DisconnectAsync() - { - return mWebsocketClient.StopOrFail(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, "Nomal close"); - } - - public Task SendTextAsync(string text) - { - if(!string.IsNullOrEmpty(text)) - { - Task task = mWebsocketClient.SendInstant(text); - return task; - } - - return Task.CompletedTask; - } - - public void Dispose() - { - mWebsocketClient.Dispose(); - } - } -} - - - - diff --git a/AdamController.Services/CommunicationProviderService.cs b/AdamController.Services/CommunicationProviderService.cs index 3328c32..7134dd1 100644 --- a/AdamController.Services/CommunicationProviderService.cs +++ b/AdamController.Services/CommunicationProviderService.cs @@ -13,23 +13,23 @@ public class CommunicationProviderService : ICommunicationProviderService public event AdamTcpClientDisconnect RaiseAdamTcpClientDisconnect; public event AdamTcpClientReconnected RaiseAdamTcpClientReconnected; public event AdamUdpServerReceived RaiseAdamUdpServerReceived; - public event AdamUdpMessageReceived RaiseAdamUdpMessageReceived; + public event AdamUdpClientReceived RaiseAdamUdpClientReceived; #endregion #region Services - private readonly IAdamTcpClientService mAdamTcpClientService; - private readonly IAdamUdpClientService mAdamUdpClientService; - private readonly IAdamUdpServerService mAadamUdpServerService; - private readonly IAdamWebSocketClientService mAdamWebSocketClientService; + private readonly ITcpClientService mAdamTcpClientService; + private readonly IUdpClientService mAdamUdpClientService; + private readonly IUdpServerService mAadamUdpServerService; + private readonly IWebSocketClientService mAdamWebSocketClientService; #endregion #region ~ - public CommunicationProviderService(IAdamTcpClientService adamTcpClientService, IAdamUdpClientService adamUdpClientService, - IAdamUdpServerService adamUdpServerService, IAdamWebSocketClientService adamWebSocketClientService) + public CommunicationProviderService(ITcpClientService adamTcpClientService, IUdpClientService adamUdpClientService, + IUdpServerService adamUdpServerService, IWebSocketClientService adamWebSocketClientService) { mAdamTcpClientService = adamTcpClientService; mAdamUdpClientService = adamUdpClientService; @@ -51,7 +51,6 @@ public CommunicationProviderService(IAdamTcpClientService adamTcpClientService, public void ConnectAllAsync() { - _ = Task.Run(mAdamTcpClientService.ConnectAsync); _ = Task.Run(mAdamUdpClientService.Start); _ = Task.Run(mAadamUdpServerService.Start); @@ -97,9 +96,7 @@ private void Subscribe() mAdamTcpClientService.RaiseTcpClientReconnected += RaiseTcpClientReconnected; mAdamTcpClientService.RaiseTcpCientConnected += RaiseTcpCientConnected; mAdamTcpClientService.RaiseTcpClientDisconnected += RaiseTcpClientDisconnected; - mAdamUdpClientService.RaiseUdpClientReceived += RaiseUdpClientReceived; - mAadamUdpServerService.RaiseUdpServerReceived += RaiseUdpServerReceived; } @@ -108,9 +105,7 @@ private void Unsubscribe() mAdamTcpClientService.RaiseTcpClientReconnected -= RaiseTcpClientReconnected; mAdamTcpClientService.RaiseTcpCientConnected -= RaiseTcpCientConnected; mAdamTcpClientService.RaiseTcpClientDisconnected -= RaiseTcpClientDisconnected; - mAdamUdpClientService.RaiseUdpClientReceived -= RaiseUdpClientReceived; - mAadamUdpServerService.RaiseUdpServerReceived -= RaiseUdpServerReceived; } @@ -149,7 +144,7 @@ private void RaiseUdpClientReceived(object sender, EndPoint endpoint, byte[] buf { string encodedMessage = Encoding.UTF8.GetString(buffer); //string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); - OnRaiseAdamUdpMessageReceived(encodedMessage); + OnRaiseAdamUdpClientReceived(encodedMessage); } @@ -188,9 +183,9 @@ protected virtual void OnRaiseAdamUdpServerReceived(string message) raiseEvent?.Invoke(this, message); } - protected virtual void OnRaiseAdamUdpMessageReceived(string message) + protected virtual void OnRaiseAdamUdpClientReceived(string message) { - AdamUdpMessageReceived raiseEvent = RaiseAdamUdpMessageReceived; + AdamUdpClientReceived raiseEvent = RaiseAdamUdpClientReceived; raiseEvent?.Invoke(this, message); } diff --git a/AdamController.Services/Interfaces/ICommunicationProviderService.cs b/AdamController.Services/Interfaces/ICommunicationProviderService.cs index a20e872..4678d1f 100644 --- a/AdamController.Services/Interfaces/ICommunicationProviderService.cs +++ b/AdamController.Services/Interfaces/ICommunicationProviderService.cs @@ -8,7 +8,7 @@ namespace AdamController.Services.Interfaces public delegate void AdamTcpClientDisconnect(object sender); public delegate void AdamTcpClientReconnected(object sender, int reconnectCounter); public delegate void AdamUdpServerReceived(object sender, string message); - public delegate void AdamUdpMessageReceived(object sender, string message); + public delegate void AdamUdpClientReceived(object sender, string message); #endregion @@ -23,7 +23,7 @@ public interface ICommunicationProviderService : IDisposable public event AdamTcpClientDisconnect RaiseAdamTcpClientDisconnect; public event AdamTcpClientReconnected RaiseAdamTcpClientReconnected; public event AdamUdpServerReceived RaiseAdamUdpServerReceived; - public event AdamUdpMessageReceived RaiseAdamUdpMessageReceived; + public event AdamUdpClientReceived RaiseAdamUdpClientReceived; diff --git a/AdamController.Services/Interfaces/IAdamTcpClientService.cs b/AdamController.Services/Interfaces/ITcpClientService.cs similarity index 96% rename from AdamController.Services/Interfaces/IAdamTcpClientService.cs rename to AdamController.Services/Interfaces/ITcpClientService.cs index 951eb57..21ee9e3 100644 --- a/AdamController.Services/Interfaces/IAdamTcpClientService.cs +++ b/AdamController.Services/Interfaces/ITcpClientService.cs @@ -14,7 +14,7 @@ namespace AdamController.Services.Interfaces #endregion - public interface IAdamTcpClientService : IDisposable + public interface ITcpClientService : IDisposable { #region Events diff --git a/AdamController.Services/Interfaces/IAdamUdpClientService.cs b/AdamController.Services/Interfaces/IUdpClientService.cs similarity index 91% rename from AdamController.Services/Interfaces/IAdamUdpClientService.cs rename to AdamController.Services/Interfaces/IUdpClientService.cs index b8f0af6..d7dd47b 100644 --- a/AdamController.Services/Interfaces/IAdamUdpClientService.cs +++ b/AdamController.Services/Interfaces/IUdpClientService.cs @@ -10,7 +10,7 @@ namespace AdamController.Services.Interfaces #endregion - public interface IAdamUdpClientService : IDisposable + public interface IUdpClientService : IDisposable { #region Events diff --git a/AdamController.Services/Interfaces/IAdamUdpServerService.cs b/AdamController.Services/Interfaces/IUdpServerService.cs similarity index 90% rename from AdamController.Services/Interfaces/IAdamUdpServerService.cs rename to AdamController.Services/Interfaces/IUdpServerService.cs index dbff113..1519547 100644 --- a/AdamController.Services/Interfaces/IAdamUdpServerService.cs +++ b/AdamController.Services/Interfaces/IUdpServerService.cs @@ -11,7 +11,7 @@ namespace AdamController.Services.Interfaces #endregion - public interface IAdamUdpServerService : IDisposable + public interface IUdpServerService : IDisposable { #region Events diff --git a/AdamController.Services/Interfaces/IAdamWebSocketClientService.cs b/AdamController.Services/Interfaces/IWebSocketClientService.cs similarity index 93% rename from AdamController.Services/Interfaces/IAdamWebSocketClientService.cs rename to AdamController.Services/Interfaces/IWebSocketClientService.cs index 546b466..8758dcb 100644 --- a/AdamController.Services/Interfaces/IAdamWebSocketClientService.cs +++ b/AdamController.Services/Interfaces/IWebSocketClientService.cs @@ -12,7 +12,7 @@ namespace AdamController.Services.Interfaces #endregion - public interface IAdamWebSocketClientService : IDisposable + public interface IWebSocketClientService : IDisposable { #region Events diff --git a/AdamController.Services/AdamTcpClientDependency/AdamTcpClientOption.cs b/AdamController.Services/TcpClientDependency/TcpClientOption.cs similarity index 75% rename from AdamController.Services/AdamTcpClientDependency/AdamTcpClientOption.cs rename to AdamController.Services/TcpClientDependency/TcpClientOption.cs index bb08bfb..04d1199 100644 --- a/AdamController.Services/AdamTcpClientDependency/AdamTcpClientOption.cs +++ b/AdamController.Services/TcpClientDependency/TcpClientOption.cs @@ -1,6 +1,6 @@ -namespace AdamController.Services.AdamTcpClientDependency +namespace AdamController.Services.TcpClientDependency { - public class AdamTcpClientOption + public class TcpClientOption { /// /// The number of reconnections when the connection is lost diff --git a/AdamController.Services/AdamTcpClientService.cs b/AdamController.Services/TcpClientService.cs similarity index 95% rename from AdamController.Services/AdamTcpClientService.cs rename to AdamController.Services/TcpClientService.cs index 5deed36..b93cb0c 100644 --- a/AdamController.Services/AdamTcpClientService.cs +++ b/AdamController.Services/TcpClientService.cs @@ -1,5 +1,5 @@ -using AdamController.Services.AdamTcpClientDependency; -using AdamController.Services.Interfaces; +using AdamController.Services.Interfaces; +using AdamController.Services.TcpClientDependency; using System; using System.Net.Sockets; using System.Threading; @@ -7,7 +7,7 @@ namespace AdamController.Services { - public class AdamTcpClientService : NetCoreServer.TcpClient, IAdamTcpClientService + public class TcpClientService : NetCoreServer.TcpClient, ITcpClientService { #region Events @@ -32,7 +32,7 @@ public class AdamTcpClientService : NetCoreServer.TcpClient, IAdamTcpClientServi #region ~ - public AdamTcpClientService(string address, int port, AdamTcpClientOption option) : base(address, port) + public TcpClientService(string address, int port, TcpClientOption option) : base(address, port) { ReconnectCount = option.ReconnectCount; ReconnectTimeout = option.ReconnectTimeout; diff --git a/AdamController.Services/AdamUdpClientService.cs b/AdamController.Services/UdpClientService.cs similarity index 83% rename from AdamController.Services/AdamUdpClientService.cs rename to AdamController.Services/UdpClientService.cs index 0c79f72..de10725 100644 --- a/AdamController.Services/AdamUdpClientService.cs +++ b/AdamController.Services/UdpClientService.cs @@ -3,11 +3,11 @@ namespace AdamController.Services { - public class AdamUdpClientService : NetCoreServer.UdpServer, IAdamUdpClientService + public class UdpClientService : NetCoreServer.UdpServer, IUdpClientService { public event UdpClientReceived RaiseUdpClientReceived; - public AdamUdpClientService(IPAddress address, int port) : base(address, port) { } + public UdpClientService(IPAddress address, int port) : base(address, port) { } protected override void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size) { diff --git a/AdamController.Services/AdamUdpServerService.cs b/AdamController.Services/UdpServerService.cs similarity index 87% rename from AdamController.Services/AdamUdpServerService.cs rename to AdamController.Services/UdpServerService.cs index 279182c..62a9e9f 100644 --- a/AdamController.Services/AdamUdpServerService.cs +++ b/AdamController.Services/UdpServerService.cs @@ -4,7 +4,7 @@ namespace AdamController.Services { - public class AdamUdpServerService : UdpServer, IAdamUdpServerService + public class UdpServerService : UdpServer, IUdpServerService { #region Events @@ -14,7 +14,7 @@ public class AdamUdpServerService : UdpServer, IAdamUdpServerService #region ~ - public AdamUdpServerService(IPAddress address, int port) : base(address, port){} + public UdpServerService(IPAddress address, int port) : base(address, port){} #endregion diff --git a/AdamController.Services/AdamWebSocketClientService.cs b/AdamController.Services/WebSocketClientService.cs similarity index 95% rename from AdamController.Services/AdamWebSocketClientService.cs rename to AdamController.Services/WebSocketClientService.cs index 89d1f0e..9ae22bf 100644 --- a/AdamController.Services/AdamWebSocketClientService.cs +++ b/AdamController.Services/WebSocketClientService.cs @@ -5,7 +5,7 @@ namespace AdamController.Services { - public class AdamWebSocketClientService : IAdamWebSocketClientService + public class WebSocketClientService : IWebSocketClientService { #region Events @@ -23,7 +23,7 @@ public class AdamWebSocketClientService : IAdamWebSocketClientService #region ~ - public AdamWebSocketClientService(Uri url) + public WebSocketClientService(Uri url) { mWebsocketClient = new(url) { diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 7bb10a7..ddd3229 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -44,14 +44,11 @@ using ControlzEx.Theming; using ICSharpCode.AvalonEdit.Highlighting; -using AdamController.Services.AdamTcpClientDependency; using AdamController.Core.Properties; using System.Diagnostics; using System.Threading.Tasks; -using AdamController.ViewModels; -using AdamController.Core.Mvvm; -using System.Windows.Navigation; using System.Net; +using AdamController.Services.TcpClientDependency; #endregion @@ -111,9 +108,9 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return new FlyoutManager(container, regionManager); }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(containerRegistry => { - AdamTcpClientOption option = new() + TcpClientOption option = new() { ReconnectCount = Settings.Default.ReconnectQtyComunicateTcpClient, ReconnectTimeout = Settings.Default.ReconnectTimeoutComunicateTcpClient @@ -122,16 +119,16 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) string ip = Settings.Default.ServerIP; int port = Settings.Default.TcpConnectStatePort; - AdamTcpClientService client = new(ip, port, option); + TcpClientService client = new(ip, port, option); return client; }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(containerRegistry => { IPAddress ip = IPAddress.Any; int port = int.Parse(Settings.Default.MessageDataExchangePort); - AdamUdpClientService client = new(ip, port) + UdpClientService client = new(ip, port) { OptionDualMode = true, OptionReuseAddress = true @@ -140,12 +137,12 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return client; }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(containerRegistry => { IPAddress ip = IPAddress.Any; int port = Settings.Default.LogServerPort; - AdamUdpServerService server = new(ip, port) + UdpServerService server = new(ip, port) { OptionDualMode = true, OptionReuseAddress = true @@ -154,28 +151,28 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return server; }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(containerRegistry => { string ip = Settings.Default.ServerIP; int port = Settings.Default.SoketServerPort; - // debug + // debug, use only with debug server, which runs separately, not as a service Uri uri = new($"ws://{Settings.Default.ServerIP}:9001/adam-2.7/movement"); - //work - //Uri uri = new($"ws://{ip}:{port}/adam-2.7/movement"); + // work in production, connect to socket-server run as service + // Uri uri = new($"ws://{ip}:{port}/adam-2.7/movement"); - AdamWebSocketClientService client = new(uri); + WebSocketClientService client = new(uri); return client; }); containerRegistry.RegisterSingleton(containerRegistry => { - IAdamTcpClientService tcpClientService = containerRegistry.Resolve(); - IAdamUdpClientService udpClientService = containerRegistry.Resolve(); - IAdamUdpServerService udpServerService = containerRegistry.Resolve(); - IAdamWebSocketClientService socketClientService = containerRegistry.Resolve(); + ITcpClientService tcpClientService = containerRegistry.Resolve(); + IUdpClientService udpClientService = containerRegistry.Resolve(); + IUdpServerService udpServerService = containerRegistry.Resolve(); + IWebSocketClientService socketClientService = containerRegistry.Resolve(); CommunicationProviderService communicationProvider = new(tcpClientService, udpClientService, udpServerService, socketClientService); @@ -208,7 +205,6 @@ private void StartWebApi() private static void RegisterDialogs(IContainerRegistry containerRegistry) { containerRegistry.RegisterDialog(); - containerRegistry.RegisterDialog(); } protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs index 24e1d25..ef44dc4 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs @@ -1,6 +1,4 @@ -using AdamController.Controls.CustomControls.Services; -using AdamController.Core.Helpers; -using AdamController.Core.Model; +using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Services.Interfaces; using AdamController.WebApi.Client.v1; diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index 14ce19f..c9fc546 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -33,9 +33,6 @@ public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogServi #endregion - - - #region Navigation public override void OnNavigatedFrom(NavigationContext navigationContext) diff --git a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs index cde4d57..d5b371c 100644 --- a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs +++ b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs @@ -5,7 +5,6 @@ using Prism.Regions; using Prism.Services.Dialogs; using System.Windows; -using AdamController.Services.Interfaces; namespace AdamController.Modules.MenuRegion.ViewModels { @@ -32,10 +31,6 @@ private void ShowDialog(string dialogNames) case DialogNames.SettingsDialog: DialogService.ShowSettingsDialog(); break; - - case DialogNames.NetworkTestDialog: - DialogService.ShowNetworkTestDialog(); - break; } } diff --git a/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml b/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml index 2ce6006..dc6874f 100644 --- a/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml +++ b/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml @@ -77,10 +77,6 @@ Command="{Binding ShowDialogCommand}" CommandParameter="{x:Static core:DialogNames.SettingsDialog}"/> - - From 3435e7b4d956c551839ee11dd1de235075eb777e Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Thu, 11 Apr 2024 22:48:02 +1000 Subject: [PATCH 077/181] Added: python execute parser service --- .../CommunicationProviderService.cs | 124 +++++++-------- .../ICommunicationProviderService.cs | 22 +-- .../Interfaces/IPythonRemoteRunnerService.cs | 23 +++ .../PythonRemoteRunnerService.cs | 145 ++++++++++++++++++ .../ViewModels/StatusBarViewModel.cs | 4 +- 5 files changed, 243 insertions(+), 75 deletions(-) create mode 100644 AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs create mode 100644 AdamController.Services/PythonRemoteRunnerService.cs diff --git a/AdamController.Services/CommunicationProviderService.cs b/AdamController.Services/CommunicationProviderService.cs index 7134dd1..64ba5fa 100644 --- a/AdamController.Services/CommunicationProviderService.cs +++ b/AdamController.Services/CommunicationProviderService.cs @@ -9,20 +9,20 @@ public class CommunicationProviderService : ICommunicationProviderService { #region Events - public event AdamTcpCientConnected RaiseAdamTcpCientConnected; - public event AdamTcpClientDisconnect RaiseAdamTcpClientDisconnect; - public event AdamTcpClientReconnected RaiseAdamTcpClientReconnected; - public event AdamUdpServerReceived RaiseAdamUdpServerReceived; - public event AdamUdpClientReceived RaiseAdamUdpClientReceived; + public event TcpCientConnected RaiseTcpCientConnected; + public event TcpClientDisconnect RaiseTcpClientDisconnect; + public event TcpClientReconnected RaiseTcpClientReconnected; + public event UdpServerReceived RaiseUdpServerReceived; + public event UdpClientReceived RaiseUdpClientReceived; #endregion #region Services - private readonly ITcpClientService mAdamTcpClientService; - private readonly IUdpClientService mAdamUdpClientService; - private readonly IUdpServerService mAadamUdpServerService; - private readonly IWebSocketClientService mAdamWebSocketClientService; + private readonly ITcpClientService mTcpClientService; + private readonly IUdpClientService mUdpClientService; + private readonly IUdpServerService mUdpServerService; + private readonly IWebSocketClientService mWebSocketClientService; #endregion @@ -31,10 +31,10 @@ public class CommunicationProviderService : ICommunicationProviderService public CommunicationProviderService(ITcpClientService adamTcpClientService, IUdpClientService adamUdpClientService, IUdpServerService adamUdpServerService, IWebSocketClientService adamWebSocketClientService) { - mAdamTcpClientService = adamTcpClientService; - mAdamUdpClientService = adamUdpClientService; - mAadamUdpServerService = adamUdpServerService; - mAdamWebSocketClientService = adamWebSocketClientService; + mTcpClientService = adamTcpClientService; + mUdpClientService = adamUdpClientService; + mUdpServerService = adamUdpServerService; + mWebSocketClientService = adamWebSocketClientService; Subscribe(); } @@ -51,25 +51,25 @@ public CommunicationProviderService(ITcpClientService adamTcpClientService, IUdp public void ConnectAllAsync() { - _ = Task.Run(mAdamTcpClientService.ConnectAsync); - _ = Task.Run(mAdamUdpClientService.Start); - _ = Task.Run(mAadamUdpServerService.Start); - _ = Task.Run(mAdamWebSocketClientService.ConnectAsync); + _ = Task.Run(mTcpClientService.ConnectAsync); + _ = Task.Run(mUdpClientService.Start); + _ = Task.Run(mUdpServerService.Start); + _ = Task.Run(mWebSocketClientService.ConnectAsync); } public void DisconnectAllAsync() { - _ = Task.Run(mAdamTcpClientService.DisconnectAndStop); - _ = Task.Run(mAdamUdpClientService.Stop); - _ = Task.Run(mAadamUdpServerService.Stop); - _ = Task.Run(mAdamWebSocketClientService.DisconnectAsync); + _ = Task.Run(mTcpClientService.DisconnectAndStop); + _ = Task.Run(mUdpClientService.Stop); + _ = Task.Run(mUdpServerService.Stop); + _ = Task.Run(mWebSocketClientService.DisconnectAsync); } - public void DisconnectAllAndDestroy() {} + //public void DisconnectAllAndDestroy() {} public void WebSocketSendTextMessage(string message) { - Task.Run(() => mAdamWebSocketClientService.SendTextAsync(message)); + Task.Run(() => mWebSocketClientService.SendTextAsync(message)); } public void Dispose() @@ -77,10 +77,10 @@ public void Dispose() DisconnectAllAsync(); Unsubscribe(); - mAdamTcpClientService.Dispose(); - mAdamUdpClientService.Dispose(); - mAadamUdpServerService.Dispose(); - mAdamWebSocketClientService.Dispose(); + mTcpClientService.Dispose(); + mUdpClientService.Dispose(); + mUdpServerService.Dispose(); + mWebSocketClientService.Dispose(); } #endregion @@ -93,99 +93,99 @@ public void Dispose() private void Subscribe() { - mAdamTcpClientService.RaiseTcpClientReconnected += RaiseTcpClientReconnected; - mAdamTcpClientService.RaiseTcpCientConnected += RaiseTcpCientConnected; - mAdamTcpClientService.RaiseTcpClientDisconnected += RaiseTcpClientDisconnected; - mAdamUdpClientService.RaiseUdpClientReceived += RaiseUdpClientReceived; - mAadamUdpServerService.RaiseUdpServerReceived += RaiseUdpServerReceived; + mTcpClientService.RaiseTcpClientReconnected += RaiseTcpClientReconnected; + mTcpClientService.RaiseTcpCientConnected += RaiseTcpCientConnected; + mTcpClientService.RaiseTcpClientDisconnected += RaiseTcpClientDisconnected; + mUdpClientService.RaiseUdpClientReceived += RaiseUdpClientReceived; + mUdpServerService.RaiseUdpServerReceived += RaiseUdpServerReceived; } private void Unsubscribe() { - mAdamTcpClientService.RaiseTcpClientReconnected -= RaiseTcpClientReconnected; - mAdamTcpClientService.RaiseTcpCientConnected -= RaiseTcpCientConnected; - mAdamTcpClientService.RaiseTcpClientDisconnected -= RaiseTcpClientDisconnected; - mAdamUdpClientService.RaiseUdpClientReceived -= RaiseUdpClientReceived; - mAadamUdpServerService.RaiseUdpServerReceived -= RaiseUdpServerReceived; + mTcpClientService.RaiseTcpClientReconnected -= RaiseServiceTcpClientReconnected; + mTcpClientService.RaiseTcpCientConnected -= RaiseServiceTcpCientConnected; + mTcpClientService.RaiseTcpClientDisconnected -= RaiseTcpClientDisconnected; + mUdpClientService.RaiseUdpClientReceived -= RaiseServiceUdpClientReceived; + mUdpServerService.RaiseUdpServerReceived -= RaiseServiceUdpServerReceived; } #endregion #region Event methods - private void RaiseTcpCientConnected(object sender) + private void RaiseServiceTcpCientConnected(object sender) { IsTcpClientConnected = true; - OnRaiseAdamTcpCientConnected(); + OnRaiseTcpCientConnected(); - mAdamUdpClientService.Start(); - mAadamUdpServerService.Start(); - mAdamWebSocketClientService.ConnectAsync(); + mUdpClientService.Start(); + mUdpServerService.Start(); + mWebSocketClientService.ConnectAsync(); } private void RaiseTcpClientDisconnected(object sender) { IsTcpClientConnected = false; - OnRaiseAdamTcpClientDisconnect(); + OnRaiseTcpClientDisconnect(); - mAdamUdpClientService.Stop(); - mAadamUdpServerService.Stop(); - mAdamWebSocketClientService.DisconnectAsync(); + mUdpClientService.Stop(); + mUdpServerService.Stop(); + mWebSocketClientService.DisconnectAsync(); } - private void RaiseTcpClientReconnected(object sender, int reconnectCount) + private void RaiseServiceTcpClientReconnected(object sender, int reconnectCount) { - OnRaiseAdamTcpClientReconnected(reconnectCount); + OnRaiseTcpClientReconnected(reconnectCount); } - private void RaiseUdpClientReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size) + private void RaiseServiceUdpClientReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size) { string encodedMessage = Encoding.UTF8.GetString(buffer); //string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); - OnRaiseAdamUdpClientReceived(encodedMessage); + OnRaiseUdpClientReceived(encodedMessage); } - private void RaiseUdpServerReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size) + private void RaiseServiceUdpServerReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size) { string encodedMessage = Encoding.UTF8.GetString(buffer); //string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); - OnRaiseAdamUdpServerReceived(encodedMessage); + OnRaiseUdpServerReceived(encodedMessage); } #endregion #region OnRaise events - protected virtual void OnRaiseAdamTcpCientConnected() + protected virtual void OnRaiseTcpCientConnected() { - AdamTcpCientConnected raiseEvent = RaiseAdamTcpCientConnected; + TcpCientConnected raiseEvent = RaiseTcpCientConnected; raiseEvent?.Invoke(this); } - protected virtual void OnRaiseAdamTcpClientDisconnect() + protected virtual void OnRaiseTcpClientDisconnect() { - AdamTcpClientDisconnect raiseEvent = RaiseAdamTcpClientDisconnect; + TcpClientDisconnect raiseEvent = RaiseTcpClientDisconnect; raiseEvent?.Invoke(this); } - public virtual void OnRaiseAdamTcpClientReconnected(int reconnectCounter) + public virtual void OnRaiseTcpClientReconnected(int reconnectCounter) { - AdamTcpClientReconnected raiseEvent = RaiseAdamTcpClientReconnected; + TcpClientReconnected raiseEvent = RaiseTcpClientReconnected; raiseEvent?.Invoke(this, reconnectCounter); } - protected virtual void OnRaiseAdamUdpServerReceived(string message) + protected virtual void OnRaiseUdpServerReceived(string message) { - AdamUdpServerReceived raiseEvent = RaiseAdamUdpServerReceived; + UdpServerReceived raiseEvent = RaiseUdpServerReceived; raiseEvent?.Invoke(this, message); } - protected virtual void OnRaiseAdamUdpClientReceived(string message) + protected virtual void OnRaiseUdpClientReceived(string message) { - AdamUdpClientReceived raiseEvent = RaiseAdamUdpClientReceived; + UdpClientReceived raiseEvent = RaiseUdpClientReceived; raiseEvent?.Invoke(this, message); } diff --git a/AdamController.Services/Interfaces/ICommunicationProviderService.cs b/AdamController.Services/Interfaces/ICommunicationProviderService.cs index 4678d1f..48cea7e 100644 --- a/AdamController.Services/Interfaces/ICommunicationProviderService.cs +++ b/AdamController.Services/Interfaces/ICommunicationProviderService.cs @@ -4,11 +4,11 @@ namespace AdamController.Services.Interfaces { #region Delegate - public delegate void AdamTcpCientConnected(object sender); - public delegate void AdamTcpClientDisconnect(object sender); - public delegate void AdamTcpClientReconnected(object sender, int reconnectCounter); - public delegate void AdamUdpServerReceived(object sender, string message); - public delegate void AdamUdpClientReceived(object sender, string message); + public delegate void TcpCientConnected(object sender); + public delegate void TcpClientDisconnect(object sender); + public delegate void TcpClientReconnected(object sender, int reconnectCounter); + public delegate void UdpServerReceived(object sender, string message); + public delegate void UdpClientReceived(object sender, string message); #endregion @@ -19,11 +19,11 @@ public interface ICommunicationProviderService : IDisposable { #region Events - public event AdamTcpCientConnected RaiseAdamTcpCientConnected; - public event AdamTcpClientDisconnect RaiseAdamTcpClientDisconnect; - public event AdamTcpClientReconnected RaiseAdamTcpClientReconnected; - public event AdamUdpServerReceived RaiseAdamUdpServerReceived; - public event AdamUdpClientReceived RaiseAdamUdpClientReceived; + public event TcpCientConnected RaiseTcpCientConnected; + public event TcpClientDisconnect RaiseTcpClientDisconnect; + public event TcpClientReconnected RaiseTcpClientReconnected; + public event UdpServerReceived RaiseUdpServerReceived; + public event UdpClientReceived RaiseUdpClientReceived; @@ -47,7 +47,7 @@ public interface ICommunicationProviderService : IDisposable /// This is now implemented in Dispose services /// All calls to this method should be replaced with calls to DisconnectAllAsync() /// - public void DisconnectAllAndDestroy(); + //public void DisconnectAllAndDestroy(); public void WebSocketSendTextMessage(string message); diff --git a/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs b/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs new file mode 100644 index 0000000..2e96cc0 --- /dev/null +++ b/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs @@ -0,0 +1,23 @@ +using System; + +namespace AdamController.Services.Interfaces +{ + #region Delegate + + public delegate void PythonStandartOutput(object sender, string message); + public delegate void PythonScriptExecuteStart(object sender, string message); + public delegate void PythonScriptExecuteFinish(object sender, string message); + + #endregion + + public interface IPythonRemoteRunnerService : IDisposable + { + #region Events + + public event PythonStandartOutput RaisePythonStandartOutput; + public event PythonScriptExecuteStart RaisePythonScriptExecuteStart; + public event PythonScriptExecuteFinish RaisePythonScriptExecuteFinish; + + #endregion + } +} diff --git a/AdamController.Services/PythonRemoteRunnerService.cs b/AdamController.Services/PythonRemoteRunnerService.cs new file mode 100644 index 0000000..60d5ab1 --- /dev/null +++ b/AdamController.Services/PythonRemoteRunnerService.cs @@ -0,0 +1,145 @@ +using AdamController.Services.Interfaces; + +namespace AdamController.Services +{ + public class PythonRemoteRunnerService : IPythonRemoteRunnerService + { + #region Events + + public event PythonStandartOutput RaisePythonStandartOutput; + public event PythonScriptExecuteStart RaisePythonScriptExecuteStart; + public event PythonScriptExecuteFinish RaisePythonScriptExecuteFinish; + + #endregion + + #region Services + + private readonly ICommunicationProviderService mCommunicationProvider; + + #endregion + + #region Const + + private const string cStartMessage = "start"; + private const string cErrorMessage = "error"; + private const string cFinishMessage = "finish"; + + #endregion + + public PythonRemoteRunnerService(ICommunicationProviderService communicationProvider) + { + mCommunicationProvider = communicationProvider; + } + + #region Public method + + public void Dispose() + { + Unsubscribe(); + } + + #endregion + + #region Private methods + + private void MessageParser(string message) + { + switch (message) + { + case cStartMessage: + //OnExecuteStartEvent.Invoke(string.Empty); + OnRaisePythonScriptExecuteStart(); + break; + + case cErrorMessage: + break; + + case string result when result.StartsWith(cFinishMessage): + //OnExecuteFinishEvent.Invoke(FinishExecuteMessage(message.Remove(0, 6))); + break; + + default: + var messagen = $"{message}"; + OnRaisePythonStandartOutput(messagen); + //OnStandartOutputEvent.Invoke($"{message}\n"); + break; + } + } + + private static string FinishExecuteMessage(string resultJson = null) + { + string message = "\n======================\n<<Выполнение программы завершено>>"; + + if (string.IsNullOrEmpty(resultJson)) + return message; + + //CommandExecuteResult executeResult = resultJson.ToCommandResult(); + + /*string messageWithResult = $"{message}\n" + + $"\n" + + $"Отчет о выполнении\n" + + $"======================\n" + + $"Начало выполнения: {executeResult.StartTime}\n" + + $"Завершение выполнения: {executeResult.EndTime}\n" + + $"Общее время выполнения: {executeResult.RunTime}\n" + + $"Код выхода: {executeResult.ExitCode}\n" + + $"Статус успешности завершения: {executeResult.Succeeded}" + + $"\n======================\n"; + + if (!string.IsNullOrEmpty(executeResult.StandardError)) + messageWithResult += $"Ошибка: {executeResult.StandardError}" + + $"\n======================\n";*/ + + return null; //messageWithResult; + + } + #endregion + + #region Subscribses + + private void Subscribe() + { + mCommunicationProvider.RaiseUdpClientReceived += RaiseUdpClientReceived; + } + + + private void Unsubscribe() + { + mCommunicationProvider.RaiseUdpClientReceived -= RaiseUdpClientReceived; + } + + + #endregion + + #region Event methods + + private void RaiseUdpClientReceived(object sender, string message) + { + MessageParser(message); + } + + #endregion + + #region OnRaise events + + protected virtual void OnRaisePythonStandartOutput(string message) + { + PythonStandartOutput raiseEvent = RaisePythonStandartOutput; + raiseEvent?.Invoke(this, message); + } + + protected virtual void OnRaisePythonScriptExecuteStart(string message = "") + { + PythonScriptExecuteStart raiseEvent = RaisePythonScriptExecuteStart; + raiseEvent?.Invoke(this, message); + } + + protected virtual void OnRaisePythonScriptExecuteFinish(string message) + { + PythonScriptExecuteFinish raiseEvent = RaisePythonScriptExecuteFinish; + raiseEvent?.Invoke(this, message); + } + + #endregion + } +} diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index acfdd08..27bb27d 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -48,8 +48,8 @@ public StatusBarViewModel(IRegionManager regionManager, IDialogService dialogSer //ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; //ComunicateHelper.OnAdamTcpReconnected += OnTcpReconnected; - mCommunicationProviderService.RaiseAdamTcpCientConnected += RaiseAdamTcpCientConnected; - mCommunicationProviderService.RaiseAdamTcpClientDisconnect += RaiseAdamTcpClientDisconnect; + mCommunicationProviderService.RaiseTcpCientConnected += RaiseAdamTcpCientConnected; + mCommunicationProviderService.RaiseTcpClientDisconnect += RaiseAdamTcpClientDisconnect; } #endregion From a3c9fe6285279ac72088ae91619b4665ab41817a Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Fri, 12 Apr 2024 08:09:58 +1000 Subject: [PATCH 078/181] Fix service naming --- .../CommunicationProviderService.cs | 50 +++++++++---------- .../ICommunicationProviderService.cs | 30 ++++------- .../PythonRemoteRunnerService.cs | 4 +- .../ViewModels/ScratchControlViewModel.cs | 12 ++--- .../ViewModels/StatusBarViewModel.cs | 4 +- 5 files changed, 44 insertions(+), 56 deletions(-) diff --git a/AdamController.Services/CommunicationProviderService.cs b/AdamController.Services/CommunicationProviderService.cs index 64ba5fa..96c5e74 100644 --- a/AdamController.Services/CommunicationProviderService.cs +++ b/AdamController.Services/CommunicationProviderService.cs @@ -9,11 +9,11 @@ public class CommunicationProviderService : ICommunicationProviderService { #region Events - public event TcpCientConnected RaiseTcpCientConnected; - public event TcpClientDisconnect RaiseTcpClientDisconnect; - public event TcpClientReconnected RaiseTcpClientReconnected; - public event UdpServerReceived RaiseUdpServerReceived; - public event UdpClientReceived RaiseUdpClientReceived; + public event TcpServiceCientConnected RaiseTcpServiceCientConnected; + public event TcpServiceClientDisconnect RaiseTcpServiceClientDisconnect; + public event TcpServiceClientReconnected RaiseTcpServiceClientReconnected; + public event UdpServiceServerReceived RaiseUdpServiceServerReceived; + public event UdpServiceClientReceived RaiseUdpServiceClientReceived; #endregion @@ -65,8 +65,6 @@ public void DisconnectAllAsync() _ = Task.Run(mWebSocketClientService.DisconnectAsync); } - //public void DisconnectAllAndDestroy() {} - public void WebSocketSendTextMessage(string message) { Task.Run(() => mWebSocketClientService.SendTextAsync(message)); @@ -93,11 +91,11 @@ public void Dispose() private void Subscribe() { - mTcpClientService.RaiseTcpClientReconnected += RaiseTcpClientReconnected; - mTcpClientService.RaiseTcpCientConnected += RaiseTcpCientConnected; + mTcpClientService.RaiseTcpClientReconnected += RaiseServiceTcpClientReconnected; + mTcpClientService.RaiseTcpCientConnected += RaiseServiceTcpCientConnected; mTcpClientService.RaiseTcpClientDisconnected += RaiseTcpClientDisconnected; - mUdpClientService.RaiseUdpClientReceived += RaiseUdpClientReceived; - mUdpServerService.RaiseUdpServerReceived += RaiseUdpServerReceived; + mUdpClientService.RaiseUdpClientReceived += RaiseServiceUdpClientReceived; + mUdpServerService.RaiseUdpServerReceived += RaiseServiceUdpServerReceived; } private void Unsubscribe() @@ -117,7 +115,7 @@ private void RaiseServiceTcpCientConnected(object sender) { IsTcpClientConnected = true; - OnRaiseTcpCientConnected(); + OnRaiseTcpServiceCientConnected(); mUdpClientService.Start(); mUdpServerService.Start(); @@ -128,7 +126,7 @@ private void RaiseTcpClientDisconnected(object sender) { IsTcpClientConnected = false; - OnRaiseTcpClientDisconnect(); + OnRaiseTcpServiceClientDisconnect(); mUdpClientService.Stop(); mUdpServerService.Stop(); @@ -137,14 +135,14 @@ private void RaiseTcpClientDisconnected(object sender) private void RaiseServiceTcpClientReconnected(object sender, int reconnectCount) { - OnRaiseTcpClientReconnected(reconnectCount); + OnRaiseTcpServiceClientReconnected(reconnectCount); } private void RaiseServiceUdpClientReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size) { string encodedMessage = Encoding.UTF8.GetString(buffer); //string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); - OnRaiseUdpClientReceived(encodedMessage); + OnRaiseUdpServiceClientReceived(encodedMessage); } @@ -152,40 +150,40 @@ private void RaiseServiceUdpServerReceived(object sender, EndPoint endpoint, byt { string encodedMessage = Encoding.UTF8.GetString(buffer); //string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); - OnRaiseUdpServerReceived(encodedMessage); + OnRaiseUdpServiceServerReceived(encodedMessage); } #endregion #region OnRaise events - protected virtual void OnRaiseTcpCientConnected() + protected virtual void OnRaiseTcpServiceCientConnected() { - TcpCientConnected raiseEvent = RaiseTcpCientConnected; + TcpServiceCientConnected raiseEvent = RaiseTcpServiceCientConnected; raiseEvent?.Invoke(this); } - protected virtual void OnRaiseTcpClientDisconnect() + protected virtual void OnRaiseTcpServiceClientDisconnect() { - TcpClientDisconnect raiseEvent = RaiseTcpClientDisconnect; + TcpServiceClientDisconnect raiseEvent = RaiseTcpServiceClientDisconnect; raiseEvent?.Invoke(this); } - public virtual void OnRaiseTcpClientReconnected(int reconnectCounter) + public virtual void OnRaiseTcpServiceClientReconnected(int reconnectCounter) { - TcpClientReconnected raiseEvent = RaiseTcpClientReconnected; + TcpServiceClientReconnected raiseEvent = RaiseTcpServiceClientReconnected; raiseEvent?.Invoke(this, reconnectCounter); } - protected virtual void OnRaiseUdpServerReceived(string message) + protected virtual void OnRaiseUdpServiceServerReceived(string message) { - UdpServerReceived raiseEvent = RaiseUdpServerReceived; + UdpServiceServerReceived raiseEvent = RaiseUdpServiceServerReceived; raiseEvent?.Invoke(this, message); } - protected virtual void OnRaiseUdpClientReceived(string message) + protected virtual void OnRaiseUdpServiceClientReceived(string message) { - UdpClientReceived raiseEvent = RaiseUdpClientReceived; + UdpServiceClientReceived raiseEvent = RaiseUdpServiceClientReceived; raiseEvent?.Invoke(this, message); } diff --git a/AdamController.Services/Interfaces/ICommunicationProviderService.cs b/AdamController.Services/Interfaces/ICommunicationProviderService.cs index 48cea7e..1e428af 100644 --- a/AdamController.Services/Interfaces/ICommunicationProviderService.cs +++ b/AdamController.Services/Interfaces/ICommunicationProviderService.cs @@ -4,11 +4,11 @@ namespace AdamController.Services.Interfaces { #region Delegate - public delegate void TcpCientConnected(object sender); - public delegate void TcpClientDisconnect(object sender); - public delegate void TcpClientReconnected(object sender, int reconnectCounter); - public delegate void UdpServerReceived(object sender, string message); - public delegate void UdpClientReceived(object sender, string message); + public delegate void TcpServiceCientConnected(object sender); + public delegate void TcpServiceClientDisconnect(object sender); + public delegate void TcpServiceClientReconnected(object sender, int reconnectCounter); + public delegate void UdpServiceServerReceived(object sender, string message); + public delegate void UdpServiceClientReceived(object sender, string message); #endregion @@ -19,11 +19,11 @@ public interface ICommunicationProviderService : IDisposable { #region Events - public event TcpCientConnected RaiseTcpCientConnected; - public event TcpClientDisconnect RaiseTcpClientDisconnect; - public event TcpClientReconnected RaiseTcpClientReconnected; - public event UdpServerReceived RaiseUdpServerReceived; - public event UdpClientReceived RaiseUdpClientReceived; + public event TcpServiceCientConnected RaiseTcpServiceCientConnected; + public event TcpServiceClientDisconnect RaiseTcpServiceClientDisconnect; + public event TcpServiceClientReconnected RaiseTcpServiceClientReconnected; + public event UdpServiceServerReceived RaiseUdpServiceServerReceived; + public event UdpServiceClientReceived RaiseUdpServiceClientReceived; @@ -39,16 +39,6 @@ public interface ICommunicationProviderService : IDisposable public void ConnectAllAsync(); public void DisconnectAllAsync(); - - - /// - /// Left for backward compatibility - /// This is where events were unsubscribed, and instances of client classes were destroyed - /// This is now implemented in Dispose services - /// All calls to this method should be replaced with calls to DisconnectAllAsync() - /// - //public void DisconnectAllAndDestroy(); - public void WebSocketSendTextMessage(string message); #endregion diff --git a/AdamController.Services/PythonRemoteRunnerService.cs b/AdamController.Services/PythonRemoteRunnerService.cs index 60d5ab1..0baef17 100644 --- a/AdamController.Services/PythonRemoteRunnerService.cs +++ b/AdamController.Services/PythonRemoteRunnerService.cs @@ -99,13 +99,13 @@ private static string FinishExecuteMessage(string resultJson = null) private void Subscribe() { - mCommunicationProvider.RaiseUdpClientReceived += RaiseUdpClientReceived; + mCommunicationProvider.RaiseUdpServiceClientReceived += RaiseUdpClientReceived; } private void Unsubscribe() { - mCommunicationProvider.RaiseUdpClientReceived -= RaiseUdpClientReceived; + mCommunicationProvider.RaiseUdpServiceClientReceived -= RaiseUdpClientReceived; } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index a0b2d46..a730bf3 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -55,12 +55,12 @@ public ScratchControlViewModel(IRegionManager regionManager, IDialogService dial PythonExecuteEvent(); } - private void RaiseAdamTcpClientDisconnect(object sender) + private void RaiseTcperviceClientDisconnect(object sender) { UpdatePythonInfo(); } - private async void RaiseAdamTcpCientConnected(object sender) + private async void RaiseTcpServiceCientConnected(object sender) { var pythonVersionResult = await BaseApi.GetPythonVersion(); var pythonBinPathResult = await BaseApi.GetPythonBinDir(); @@ -77,14 +77,14 @@ private async void RaiseAdamTcpCientConnected(object sender) public override void OnNavigatedFrom(NavigationContext navigationContext) { - mCommunicationProvider.RaiseAdamTcpCientConnected -= RaiseAdamTcpCientConnected; - mCommunicationProvider.RaiseAdamTcpClientDisconnect -= RaiseAdamTcpClientDisconnect; + mCommunicationProvider.RaiseTcpServiceCientConnected -= RaiseTcpServiceCientConnected; + mCommunicationProvider.RaiseTcpServiceClientDisconnect -= RaiseTcperviceClientDisconnect; } public override void OnNavigatedTo(NavigationContext navigationContext) { - mCommunicationProvider.RaiseAdamTcpCientConnected += RaiseAdamTcpCientConnected; - mCommunicationProvider.RaiseAdamTcpClientDisconnect += RaiseAdamTcpClientDisconnect; + mCommunicationProvider.RaiseTcpServiceCientConnected += RaiseTcpServiceCientConnected; + mCommunicationProvider.RaiseTcpServiceClientDisconnect += RaiseTcperviceClientDisconnect; } #endregion diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index 27bb27d..47b1712 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -48,8 +48,8 @@ public StatusBarViewModel(IRegionManager regionManager, IDialogService dialogSer //ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; //ComunicateHelper.OnAdamTcpReconnected += OnTcpReconnected; - mCommunicationProviderService.RaiseTcpCientConnected += RaiseAdamTcpCientConnected; - mCommunicationProviderService.RaiseTcpClientDisconnect += RaiseAdamTcpClientDisconnect; + mCommunicationProviderService.RaiseTcpServiceCientConnected += RaiseAdamTcpCientConnected; + mCommunicationProviderService.RaiseTcpServiceClientDisconnect += RaiseAdamTcpClientDisconnect; } #endregion From e0f256556c6d59727889d3a1d3a770c51785b3e2 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Fri, 12 Apr 2024 13:04:36 +1000 Subject: [PATCH 079/181] Close issue #21 --- .../Helpers/PythonScriptExecuteHelper.cs | 2 + .../Model/CommandExecuteResult.cs | 1 + .../CommunicationProviderService.cs | 8 +- .../Interfaces/IPythonRemoteRunnerService.cs | 2 +- .../Extensions.cs | 31 ++++ .../RemoteCommandExecuteResult.cs | 37 ++++ .../PythonRemoteRunnerService.cs | 42 +++-- .../WebSocketClientService.cs | 2 +- AdamController/App.xaml.cs | 15 ++ .../Common/Extension.cs | 2 +- .../ComputerVisionControlViewModel.cs | 20 +++ .../ViewModels/ContentRegionViewModel.cs | 14 ++ .../ViewModels/ScratchControlViewModel.cs | 162 ++++++++++-------- .../ScriptEditorControlViewModel.cs | 124 ++++++++++---- .../VisualSettingsControlViewModel.cs | 10 +- .../ViewModels/MenuRegionViewModel.cs | 20 +++ .../ViewModels/StatusBarViewModel.cs | 81 +++++---- 17 files changed, 413 insertions(+), 160 deletions(-) create mode 100644 AdamController.Services/PythonRemoteRunnerDependency/Extensions.cs create mode 100644 AdamController.Services/PythonRemoteRunnerDependency/RemoteCommandExecuteResult.cs diff --git a/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs b/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs index 52f6e95..4870ebb 100644 --- a/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs +++ b/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs @@ -1,8 +1,10 @@ using AdamController.WebApi.Client.Common; using AdamController.WebApi.Client.v1.ResponseModel; +using System; namespace AdamController.Core.Helpers { + [Obsolete] public class PythonScriptExecuteHelper { #region Declaration delegates and events diff --git a/AdamController.Core/Model/CommandExecuteResult.cs b/AdamController.Core/Model/CommandExecuteResult.cs index 095c1b2..8831b7f 100644 --- a/AdamController.Core/Model/CommandExecuteResult.cs +++ b/AdamController.Core/Model/CommandExecuteResult.cs @@ -2,6 +2,7 @@ namespace AdamController.Core.Model { + [Obsolete] public class CommandExecuteResult { /// diff --git a/AdamController.Services/CommunicationProviderService.cs b/AdamController.Services/CommunicationProviderService.cs index 96c5e74..812b629 100644 --- a/AdamController.Services/CommunicationProviderService.cs +++ b/AdamController.Services/CommunicationProviderService.cs @@ -140,16 +140,16 @@ private void RaiseServiceTcpClientReconnected(object sender, int reconnectCount) private void RaiseServiceUdpClientReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size) { - string encodedMessage = Encoding.UTF8.GetString(buffer); - //string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); + //string encodedMessage = Encoding.UTF8.GetString(buffer); + string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); OnRaiseUdpServiceClientReceived(encodedMessage); } private void RaiseServiceUdpServerReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size) { - string encodedMessage = Encoding.UTF8.GetString(buffer); - //string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); + //string encodedMessage = Encoding.UTF8.GetString(buffer); + string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); OnRaiseUdpServiceServerReceived(encodedMessage); } diff --git a/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs b/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs index 2e96cc0..92a3056 100644 --- a/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs +++ b/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs @@ -5,7 +5,7 @@ namespace AdamController.Services.Interfaces #region Delegate public delegate void PythonStandartOutput(object sender, string message); - public delegate void PythonScriptExecuteStart(object sender, string message); + public delegate void PythonScriptExecuteStart(object sender); public delegate void PythonScriptExecuteFinish(object sender, string message); #endregion diff --git a/AdamController.Services/PythonRemoteRunnerDependency/Extensions.cs b/AdamController.Services/PythonRemoteRunnerDependency/Extensions.cs new file mode 100644 index 0000000..13fb3e6 --- /dev/null +++ b/AdamController.Services/PythonRemoteRunnerDependency/Extensions.cs @@ -0,0 +1,31 @@ +using Newtonsoft.Json; + +namespace AdamController.Services.PythonRemoteRunnerDependency +{ + public static class Extensions + { + /// + /// Deserealize jsonString to CommandExecuteResult + /// + /// JSON string with CommandExecuteResult object + /// Returns the CommandExecuteResult object with the result, if deserialization is successful, or a new CommandExecuteResult object otherwise + public static RemoteCommandExecuteResult ToCommandResult(this string jsonString) + { + if (jsonString == null) + return new RemoteCommandExecuteResult(); + + RemoteCommandExecuteResult executeResult = new(); + + try + { + executeResult = JsonConvert.DeserializeObject(jsonString); + } + catch + { + + } + + return executeResult; + } + } +} diff --git a/AdamController.Services/PythonRemoteRunnerDependency/RemoteCommandExecuteResult.cs b/AdamController.Services/PythonRemoteRunnerDependency/RemoteCommandExecuteResult.cs new file mode 100644 index 0000000..505569c --- /dev/null +++ b/AdamController.Services/PythonRemoteRunnerDependency/RemoteCommandExecuteResult.cs @@ -0,0 +1,37 @@ +using System; + +namespace AdamController.Services.PythonRemoteRunnerDependency +{ + public class RemoteCommandExecuteResult + { + /// + /// The succeeded status of an executable. + /// + public bool Succeeded { get; set; } + + /// + /// The exit code of an executable. + /// + public int ExitCode { get; set; } + + /// + /// The standard error of an executable. + /// + public string StandardError { get; set; } = string.Empty; + + /// + /// The start time of an executable. + /// + public DateTime StartTime { get; set; } + + /// + /// The end time of an executable. + /// + public DateTime EndTime { get; set; } + + /// + /// The run time of an executable. + /// + public TimeSpan RunTime { get; set; } + } +} diff --git a/AdamController.Services/PythonRemoteRunnerService.cs b/AdamController.Services/PythonRemoteRunnerService.cs index 0baef17..5839d99 100644 --- a/AdamController.Services/PythonRemoteRunnerService.cs +++ b/AdamController.Services/PythonRemoteRunnerService.cs @@ -1,4 +1,5 @@ using AdamController.Services.Interfaces; +using AdamController.Services.PythonRemoteRunnerDependency; namespace AdamController.Services { @@ -26,11 +27,17 @@ public class PythonRemoteRunnerService : IPythonRemoteRunnerService #endregion + #region ~ + public PythonRemoteRunnerService(ICommunicationProviderService communicationProvider) { mCommunicationProvider = communicationProvider; + + Subscribe(); } + #endregion + #region Public method public void Dispose() @@ -47,7 +54,6 @@ private void MessageParser(string message) switch (message) { case cStartMessage: - //OnExecuteStartEvent.Invoke(string.Empty); OnRaisePythonScriptExecuteStart(); break; @@ -55,27 +61,31 @@ private void MessageParser(string message) break; case string result when result.StartsWith(cFinishMessage): - //OnExecuteFinishEvent.Invoke(FinishExecuteMessage(message.Remove(0, 6))); - break; - + { + var cleanMessage = message.Remove(0, 6); + var finishMessage = ParseFinishExecuteMessage(cleanMessage); + OnRaisePythonScriptExecuteFinish(finishMessage); + break; + } + default: - var messagen = $"{message}"; - OnRaisePythonStandartOutput(messagen); - //OnStandartOutputEvent.Invoke($"{message}\n"); - break; + { + OnRaisePythonStandartOutput($"{message}\n"); + break; + } } } - private static string FinishExecuteMessage(string resultJson = null) + private static string ParseFinishExecuteMessage(string resultJson = null) { string message = "\n======================\n<<Выполнение программы завершено>>"; if (string.IsNullOrEmpty(resultJson)) return message; - //CommandExecuteResult executeResult = resultJson.ToCommandResult(); + RemoteCommandExecuteResult executeResult = resultJson.ToCommandResult(); - /*string messageWithResult = $"{message}\n" + + string messageWithResult = $"{message}\n" + $"\n" + $"Отчет о выполнении\n" + $"======================\n" + @@ -88,11 +98,11 @@ private static string FinishExecuteMessage(string resultJson = null) if (!string.IsNullOrEmpty(executeResult.StandardError)) messageWithResult += $"Ошибка: {executeResult.StandardError}" + - $"\n======================\n";*/ - - return null; //messageWithResult; + $"\n======================\n"; + return messageWithResult; } + #endregion #region Subscribses @@ -128,10 +138,10 @@ protected virtual void OnRaisePythonStandartOutput(string message) raiseEvent?.Invoke(this, message); } - protected virtual void OnRaisePythonScriptExecuteStart(string message = "") + protected virtual void OnRaisePythonScriptExecuteStart() { PythonScriptExecuteStart raiseEvent = RaisePythonScriptExecuteStart; - raiseEvent?.Invoke(this, message); + raiseEvent?.Invoke(this); } protected virtual void OnRaisePythonScriptExecuteFinish(string message) diff --git a/AdamController.Services/WebSocketClientService.cs b/AdamController.Services/WebSocketClientService.cs index 9ae22bf..ccb7d2d 100644 --- a/AdamController.Services/WebSocketClientService.cs +++ b/AdamController.Services/WebSocketClientService.cs @@ -47,7 +47,7 @@ public WebSocketClientService(Uri url) public Task ConnectAsync() { - return mWebsocketClient.StartOrFail(); + return mWebsocketClient.StartOrFail(); } public Task DisconnectAsync() diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index ddd3229..1af9252 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -179,6 +179,14 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return communicationProvider; }); + containerRegistry.RegisterSingleton(containerRegistry => + { + ICommunicationProviderService communicationProvider = containerRegistry.Resolve(); + + PythonRemoteRunnerService remoteRunnerService = new(communicationProvider); + return remoteRunnerService; + }); + RegisterDialogs(containerRegistry); } @@ -294,6 +302,13 @@ private void SetupUnhandledExceptionHandling() private void ShowUnhandledException(Exception e, string unhandledExceptionType, bool promptUserForShutdown) { + if (e.HResult == -2146233088) + { + // This message disables an error about the inability to connect to the websocket server. + // As a temporary measure. Service errors should be handled in the services themselves + if (e.InnerException.Source == "Websocket.Client") + return; + } var messageBoxTitle = $"An unexpected error has occurred: {unhandledExceptionType}"; var messageBoxMessage = $"The following exception occurred:\n\n{e}"; var messageBoxButtons = MessageBoxButton.OK; diff --git a/Legacy/AdamController.WebApi.Client/Common/Extension.cs b/Legacy/AdamController.WebApi.Client/Common/Extension.cs index e0fdb9b..1844334 100644 --- a/Legacy/AdamController.WebApi.Client/Common/Extension.cs +++ b/Legacy/AdamController.WebApi.Client/Common/Extension.cs @@ -1,7 +1,6 @@ using AdamController.WebApi.Client.v1.ResponseModel; using Newtonsoft.Json; using System.Text; -using System.Text.Encodings.Web; using System.Web; namespace AdamController.WebApi.Client.Common @@ -10,6 +9,7 @@ public static class Extension { #region public extensions + [Obsolete] /// /// Deserealize jsonString to CommandExecuteResult /// diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs index ef44dc4..2df818d 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs @@ -6,6 +6,7 @@ using Prism.Commands; using Prism.Regions; using Prism.Services.Dialogs; +using System; namespace AdamController.Modules.ContentRegion.ViewModels { @@ -33,6 +34,25 @@ public ComputerVisionControlViewModel(IRegionManager regionManager, IDialogServi #endregion + #region Navigation + + public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) + { + base.ConfirmNavigationRequest(navigationContext, continuationCallback); + } + + public override void OnNavigatedTo(NavigationContext navigationContext) + { + base.OnNavigatedTo(navigationContext); + } + + public override void OnNavigatedFrom(NavigationContext navigationContext) + { + base.OnNavigatedFrom(navigationContext); + } + + #endregion + #region Commands /// diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs index 312478d..ce43960 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs @@ -32,6 +32,20 @@ public override void ConfirmNavigationRequest(NavigationContext navigationContex } } + //public override void OnNavigatedFrom(NavigationContext navigationContext) + //{ + + //} + + //public override void OnNavigatedTo(NavigationContext navigationContext) + //{ + + //} + + #endregion + + #region Private methods + private void SubRegionsRequestNavigate(string uri, NavigationParameters parameters) { if (string.IsNullOrEmpty(uri)) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index a730bf3..dce6c0b 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -3,6 +3,7 @@ using AdamBlocklyLibrary.Struct; using AdamBlocklyLibrary.Toolbox; using AdamBlocklyLibrary.ToolboxSets; +using AdamController.Core; using AdamController.Core.Helpers; using AdamController.Core.Model; using AdamController.Core.Mvvm; @@ -29,13 +30,14 @@ public class ScratchControlViewModel : RegionViewModelBase #region Services private readonly ICommunicationProviderService mCommunicationProvider; + private readonly IPythonRemoteRunnerService mPythonRemoteRunner; #endregion #region Action field public static Action SendSourceToScriptEditor { get; set; } - public static Action SetSelectedPageIndex { get; set; } + //public static Action SetSelectedPageIndex { get; set; } public static Action AppLogStatusBarAction { get; set; } public static Action CompileLogStatusBarAction { get; set; } public static Action ProgressRingStartAction { get; set; } @@ -46,21 +48,54 @@ public class ScratchControlViewModel : RegionViewModelBase private readonly IMessageDialogManager IDialogManager; private bool mIsWarningStackOwerflowAlreadyShow; - public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider) : base(regionManager, dialogService) + public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; + mPythonRemoteRunner = pythonRemoteRunner; + IDialogManager = new MessageDialogManagerMahapps(Application.Current); - InitAction(); - PythonExecuteEvent(); + InitAction();; } - private void RaiseTcperviceClientDisconnect(object sender) + #region Navigation + + public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) { - UpdatePythonInfo(); + base.ConfirmNavigationRequest(navigationContext, continuationCallback); } - private async void RaiseTcpServiceCientConnected(object sender) + public override void OnNavigatedTo(NavigationContext navigationContext) + { + mCommunicationProvider.RaiseTcpServiceCientConnected += OnRaiseTcpServiceCientConnected; + mCommunicationProvider.RaiseTcpServiceClientDisconnect += OnRaiseTcperviceClientDisconnect; + + mPythonRemoteRunner.RaisePythonScriptExecuteStart += OnRaisePythonScriptExecuteStart; + mPythonRemoteRunner.RaisePythonStandartOutput += OnRaisePythonStandartOutput; + mPythonRemoteRunner.RaisePythonScriptExecuteFinish += OnRaisePythonScriptExecuteFinish; + + base.OnNavigatedTo(navigationContext); + } + + public override void OnNavigatedFrom(NavigationContext navigationContext) + { + mCommunicationProvider.RaiseTcpServiceCientConnected -= OnRaiseTcpServiceCientConnected; + mCommunicationProvider.RaiseTcpServiceClientDisconnect -= OnRaiseTcperviceClientDisconnect; + + mPythonRemoteRunner.RaisePythonScriptExecuteStart -= OnRaisePythonScriptExecuteStart; + mPythonRemoteRunner.RaisePythonStandartOutput -= OnRaisePythonStandartOutput; + mPythonRemoteRunner.RaisePythonScriptExecuteFinish -= OnRaisePythonScriptExecuteFinish; + + base.OnNavigatedFrom(navigationContext); + } + + + #endregion + + + #region Event methods + + private async void OnRaiseTcpServiceCientConnected(object sender) { var pythonVersionResult = await BaseApi.GetPythonVersion(); var pythonBinPathResult = await BaseApi.GetPythonBinDir(); @@ -73,18 +108,41 @@ private async void RaiseTcpServiceCientConnected(object sender) UpdatePythonInfo(pythonVersion, pythonBinPath, pythonWorkDir); } - #region Navigation + private void OnRaiseTcperviceClientDisconnect(object sender) + { + UpdatePythonInfo(); + } - public override void OnNavigatedFrom(NavigationContext navigationContext) + + private void OnRaisePythonScriptExecuteStart(object sender) { - mCommunicationProvider.RaiseTcpServiceCientConnected -= RaiseTcpServiceCientConnected; - mCommunicationProvider.RaiseTcpServiceClientDisconnect -= RaiseTcperviceClientDisconnect; + mIsWarningStackOwerflowAlreadyShow = false; + StartExecuteProgram(); } - public override void OnNavigatedTo(NavigationContext navigationContext) + private void OnRaisePythonStandartOutput(object sender, string message) { - mCommunicationProvider.RaiseTcpServiceCientConnected += RaiseTcpServiceCientConnected; - mCommunicationProvider.RaiseTcpServiceClientDisconnect += RaiseTcperviceClientDisconnect; + if (ResultTextEditorLength > 10000) + { + if (!mIsWarningStackOwerflowAlreadyShow) + { + ResultTextEditor += "\nДальнейший вывод результата, будет скрыт."; + ResultTextEditor += "\nПрограмма продолжает выполняться в неинтерактивном режиме."; + ResultTextEditor += "\nДля остановки нажмите \"Stop\". Или дождитесь завершения."; + + mIsWarningStackOwerflowAlreadyShow = true; + } + + return; + } + + ResultTextEditor += message; + } + + private void OnRaisePythonScriptExecuteFinish(object sender, string message) + { + FinishExecuteProgram(); + ResultTextEditor += message; } #endregion @@ -109,59 +167,8 @@ private void UpdatePythonInfo(string pythonVersion = "", string pythonBinPath = private void InitAction() { - ScratchControlView.NavigationComplete ??= new Action(() => NavigationComplete()); - - ScratchControlView.WebMessageReceived ??= new Action((results) => WebMessageReceived(results)); - } - - #endregion - - #region Native python execute event - - private void PythonExecuteEvent() - { - PythonScriptExecuteHelper.OnExecuteStartEvent += (message) => - { - //if (MainWindowViewModel.GetSelectedPageIndex != 0) - // return; - - mIsWarningStackOwerflowAlreadyShow = false; - - StartExecuteProgram(); - - ResultTextEditor += message; - }; - - PythonScriptExecuteHelper.OnStandartOutputEvent += (message) => - { - //if (MainWindowViewModel.GetSelectedPageIndex != 0) - // return; - - if (ResultTextEditorLength > 10000) - { - if (!mIsWarningStackOwerflowAlreadyShow) - { - ResultTextEditor += "\nДальнейший вывод результата, будет скрыт."; - ResultTextEditor += "\nПрограмма продолжает выполняться в неинтерактивном режиме."; - ResultTextEditor += "\nДля остановки нажмите \"Stop\". Или дождитесь завершения."; - - mIsWarningStackOwerflowAlreadyShow = true; - } - - return; - } - - ResultTextEditor += message; - }; - - PythonScriptExecuteHelper.OnExecuteFinishEvent += (message) => - { - //if (MainWindowViewModel.GetSelectedPageIndex != 0) - // return; - - FinishExecuteProgram(); - ResultTextEditor += message; - }; + ScratchControlView.NavigationComplete ??= new Action(NavigationComplete); + ScratchControlView.WebMessageReceived ??= new Action(WebMessageReceived); } #endregion @@ -170,11 +177,11 @@ private void PythonExecuteEvent() private async void StartExecuteProgram() { - CompileLogStatusBarAction("Сеанс отладки запущен"); + //CompileLogStatusBarAction("Сеанс отладки запущен"); IsEnabledShowOpenDialogButton = false; IsEnabledStopExecuteButton = true; ResultTextEditor = string.Empty; - ProgressRingStartAction(true); + //ProgressRingStartAction(true); if (!Settings.Default.ShadowWorkspaceInDebug) return; @@ -196,8 +203,8 @@ private async void OnStopExecuteProgram(string compileLogStatusBarAction) await ScratchControlView.ExecuteScript(Scripts.ShadowDisable); })); - CompileLogStatusBarAction(compileLogStatusBarAction); - ProgressRingStartAction(false); + //CompileLogStatusBarAction(compileLogStatusBarAction); + //ProgressRingStartAction(false); IsEnabledShowOpenDialogButton = true; IsEnabledStopExecuteButton = false; } @@ -466,12 +473,15 @@ public string ResultTextEditor get => resultTextEditor; set { - if (value == resultTextEditor) return; + if(SetProperty(ref resultTextEditor, value)) + ResultTextEditorLength = ResultTextEditor.Length; + + //if (value == resultTextEditor) return; - resultTextEditor = value; - ResultTextEditorLength = value.Length; + //resultTextEditor = value; + //ResultTextEditorLength = value.Length; - SetProperty(ref resultTextEditor, value); + //SetProperty(ref resultTextEditor, value); } } @@ -633,7 +643,7 @@ public string SourceTextEditor ResultTextEditor += $"Ошибка: {executeResult.StandardError}" + "\n======================"; - }, () => !string.IsNullOrEmpty(SourceTextEditor) && mCommunicationProvider.IsTcpClientConnected); + }, () => true/*!string.IsNullOrEmpty(SourceTextEditor)*/ && true /*mCommunicationProvider.IsTcpClientConnected*/); private DelegateCommand stopExecute; public DelegateCommand StopExecute => stopExecute ??= new DelegateCommand( async () => diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs index 9405810..ecc74e1 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs @@ -18,6 +18,7 @@ public class ScriptEditorControlViewModel : RegionViewModelBase #region Services private readonly ICommunicationProviderService mCommunicationProvider; + private readonly IPythonRemoteRunnerService mPythonRemoteRunner; #endregion public static Action AppLogStatusBarAction { get; set; } @@ -25,60 +26,125 @@ public class ScriptEditorControlViewModel : RegionViewModelBase private bool mIsWarningStackOwerflowAlreadyShow; private readonly IMessageDialogManager IDialogManager; - public ScriptEditorControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider) : base(regionManager, dialogService) + public ScriptEditorControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; + mPythonRemoteRunner = pythonRemoteRunner; IDialogManager = new MessageDialogManagerMahapps(Application.Current); InitAction(); - PythonExecuteEvent(); + //PythonExecuteEvent(); } + #region Navigation + + public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) + { + base.ConfirmNavigationRequest(navigationContext, continuationCallback); + } + + public override void OnNavigatedTo(NavigationContext navigationContext) + { + mPythonRemoteRunner.RaisePythonScriptExecuteStart += OnRaisePythonScriptExecuteStart; + mPythonRemoteRunner.RaisePythonStandartOutput += OnRaisePythonStandartOutput; + mPythonRemoteRunner.RaisePythonScriptExecuteFinish += OnRaisePythonScriptExecuteFinish; + + base.OnNavigatedTo(navigationContext); + } + + public override void OnNavigatedFrom(NavigationContext navigationContext) + { + mPythonRemoteRunner.RaisePythonScriptExecuteStart -= OnRaisePythonScriptExecuteStart; + mPythonRemoteRunner.RaisePythonStandartOutput -= OnRaisePythonStandartOutput; + mPythonRemoteRunner.RaisePythonScriptExecuteFinish -= OnRaisePythonScriptExecuteFinish; + + base.OnNavigatedFrom(navigationContext); + } + + + #endregion + + #region Event methods + + private void OnRaisePythonScriptExecuteStart(object sender) + { + ResultTextEditor = string.Empty; + IsCodeExecuted = true; + mIsWarningStackOwerflowAlreadyShow = false; + } + + private void OnRaisePythonStandartOutput(object sender, string message) + { + if (ResultTextEditorLength > 10000) + { + if (!mIsWarningStackOwerflowAlreadyShow) + { + ResultTextEditor += "\nДальнейший вывод результата, приведет к переполнению буфера, поэтому будет скрыт."; + ResultTextEditor += "\nПрограмма продолжает выполняться в неинтерактивном режиме."; + ResultTextEditor += "\nДля остановки нажмите \"Stop\". Или дождитесь завершения."; + + mIsWarningStackOwerflowAlreadyShow = true; + } + + return; + } + + ResultTextEditor += message; + } + + private void OnRaisePythonScriptExecuteFinish(object sender, string message) + { + IsCodeExecuted = false; + ResultTextEditor += message; + } + + #endregion + #region Python execute event private void PythonExecuteEvent() { - PythonScriptExecuteHelper.OnExecuteStartEvent += (message) => - { + //PythonScriptExecuteHelper.OnExecuteStartEvent += (message) => + //{ //if (MainWindowViewModel.GetSelectedPageIndex != 1) // return; - ResultTextEditor = string.Empty; - IsCodeExecuted = true; - mIsWarningStackOwerflowAlreadyShow = false; - ResultTextEditor += message; - }; + //ResultTextEditor = string.Empty; + //IsCodeExecuted = true; + //mIsWarningStackOwerflowAlreadyShow = false; + //ResultTextEditor += message; + //}; - PythonScriptExecuteHelper.OnStandartOutputEvent += (message) => - { + //PythonScriptExecuteHelper.OnStandartOutputEvent += (message) => + //{ //if (MainWindowViewModel.GetSelectedPageIndex != 1) // return; - if (ResultTextEditorLength > 10000) - { - if (!mIsWarningStackOwerflowAlreadyShow) - { - ResultTextEditor += "\nДальнейший вывод результата, приведет к переполнению буфера, поэтому будет скрыт."; - ResultTextEditor += "\nПрограмма продолжает выполняться в неинтерактивном режиме."; - ResultTextEditor += "\nДля остановки нажмите \"Stop\". Или дождитесь завершения."; + //if (ResultTextEditorLength > 10000) + //{ + //if (!mIsWarningStackOwerflowAlreadyShow) + //{ + // ResultTextEditor += "\nДальнейший вывод результата, приведет к переполнению буфера, поэтому будет скрыт."; + // ResultTextEditor += "\nПрограмма продолжает выполняться в неинтерактивном режиме."; + // ResultTextEditor += "\nДля остановки нажмите \"Stop\". Или дождитесь завершения."; - mIsWarningStackOwerflowAlreadyShow = true; - } + // mIsWarningStackOwerflowAlreadyShow = true; + //} - return; - } + //return; + //} - ResultTextEditor += message; - }; + //ResultTextEditor += message; + //}; - PythonScriptExecuteHelper.OnExecuteFinishEvent += (message) => - { + //PythonScriptExecuteHelper.OnExecuteFinishEvent += (message) => + //{ //if (MainWindowViewModel.GetSelectedPageIndex != 1) // return; - IsCodeExecuted = false; - ResultTextEditor += message; - }; + //IsCodeExecuted = false; + //ResultTextEditor += message; + //}; } #endregion diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index c9fc546..70319de 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -35,16 +35,22 @@ public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogServi #region Navigation - public override void OnNavigatedFrom(NavigationContext navigationContext) + public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) { - + base.ConfirmNavigationRequest(navigationContext, continuationCallback); } public override void OnNavigatedTo(NavigationContext navigationContext) { + base.OnNavigatedTo(navigationContext); + } + public override void OnNavigatedFrom(NavigationContext navigationContext) + { + base.OnNavigatedFrom(navigationContext); } + #endregion public static ObservableCollection BlocklyThemes { get; private set; } = ThemesCollection.BlocklyThemes; diff --git a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs index d5b371c..2f78f39 100644 --- a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs +++ b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs @@ -5,6 +5,7 @@ using Prism.Regions; using Prism.Services.Dialogs; using System.Windows; +using System; namespace AdamController.Modules.MenuRegion.ViewModels { @@ -21,6 +22,25 @@ public MenuRegionViewModel(IRegionManager regionManager, IDialogService dialogSe ShowRegionCommand = new DelegateCommand(ShowRegion); } + #region Navigation + + public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) + { + base.ConfirmNavigationRequest(navigationContext, continuationCallback); + } + + public override void OnNavigatedTo(NavigationContext navigationContext) + { + base.OnNavigatedTo(navigationContext); + } + + public override void OnNavigatedFrom(NavigationContext navigationContext) + { + base.OnNavigatedFrom(navigationContext); + } + + #endregion + #region Command methods diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index 47b1712..cf208ea 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -6,6 +6,7 @@ using Prism.Commands; using Prism.Regions; using Prism.Services.Dialogs; +using System; namespace AdamController.Modules.StatusBarRegion.ViewModels { @@ -43,77 +44,76 @@ public StatusBarViewModel(IRegionManager regionManager, IDialogService dialogSer mCommunicationProviderService = communicationProviderService; OpenNotificationPanelDelegateCommand = new DelegateCommand(OpenNotificationPanel, OpenNotificationPanelCanExecute); + } - //ComunicateHelper.OnAdamTcpConnectedEvent += OnTcpConnected; - //ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; - //ComunicateHelper.OnAdamTcpReconnected += OnTcpReconnected; + #endregion - mCommunicationProviderService.RaiseTcpServiceCientConnected += RaiseAdamTcpCientConnected; - mCommunicationProviderService.RaiseTcpServiceClientDisconnect += RaiseAdamTcpClientDisconnect; + #region Navigation + + public override void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) + { + base.ConfirmNavigationRequest(navigationContext, continuationCallback); + } + + public override void OnNavigatedTo(NavigationContext navigationContext) + { + Subscribe(); + + base.OnNavigatedTo(navigationContext); } + public override void OnNavigatedFrom(NavigationContext navigationContext) + { + Unsubscribe(); + + base.OnNavigatedFrom(navigationContext); + } + + #endregion - #region public fields + #region Public fields private bool progressRingStart; public bool ProgressRingStart { get { return progressRingStart; } - set - { - SetProperty(ref progressRingStart, value); - } + set { SetProperty(ref progressRingStart, value); } } private string compileLogStatusBar = cCompileLogStatusBar; public string CompileLogStatusBar { get { return compileLogStatusBar; } - set - { - SetProperty(ref compileLogStatusBar, value); - } + set { SetProperty(ref compileLogStatusBar, value); } } private string appLogStatusBar = cAppLogStatusBar; public string AppLogStatusBar { get { return appLogStatusBar; } - set - { - SetProperty(ref appLogStatusBar, value); - } + set { SetProperty(ref appLogStatusBar, value); } } private PackIconModernKind connectIcon = PackIconModernKind.Connect; public PackIconModernKind ConnectIcon { get { return connectIcon; } - set - { - SetProperty(ref connectIcon, value); - } + set { SetProperty(ref connectIcon, value); } } private string textOnStatusConnectToolbar = cTextOnStatusConnectToolbarDisconnected; public string TextOnStatusConnectToolbar { get { return textOnStatusConnectToolbar; } - set - { - SetProperty(ref textOnStatusConnectToolbar, value); - } + set { SetProperty(ref textOnStatusConnectToolbar, value); } } private string notificationBadge; public string NotificationBadge { get { return notificationBadge; } - set - { - SetProperty(ref notificationBadge, value); - } + set { SetProperty(ref notificationBadge, value); } } #endregion @@ -144,6 +144,27 @@ private int BadgeCounter #endregion + #region Subscribes + + private void Subscribe() + { + //ComunicateHelper.OnAdamTcpConnectedEvent += OnTcpConnected; + //ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; + //ComunicateHelper.OnAdamTcpReconnected += OnTcpReconnected; + + mCommunicationProviderService.RaiseTcpServiceCientConnected += RaiseAdamTcpCientConnected; + mCommunicationProviderService.RaiseTcpServiceClientDisconnect += RaiseAdamTcpClientDisconnect; + + } + + private void Unsubscribe() + { + mCommunicationProviderService.RaiseTcpServiceCientConnected -= RaiseAdamTcpCientConnected; + mCommunicationProviderService.RaiseTcpServiceClientDisconnect -= RaiseAdamTcpClientDisconnect; + } + + #endregion + #region Event methods private void RaiseAdamTcpClientDisconnect(object sender) From 9927e8792901c7752422c80e9ff36222bf922a42 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Fri, 12 Apr 2024 16:42:40 +1000 Subject: [PATCH 080/181] Preliminary work on #15 --- .../Helpers/PythonScriptExecuteHelper.cs | 80 ------ .../ViewModels/ContentRegionViewModel.cs | 42 +--- .../ViewModels/ScratchControlViewModel.cs | 2 +- .../AdvancedBlocklySettingsViewModel.cs | 2 - .../ViewModels/NotificationViewModel.cs | 233 ++++++++++++++---- .../Views/NotificationView.xaml | 74 +++--- .../ViewModels/MenuRegionViewModel.cs | 5 +- 7 files changed, 233 insertions(+), 205 deletions(-) delete mode 100644 AdamController.Core/Helpers/PythonScriptExecuteHelper.cs diff --git a/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs b/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs deleted file mode 100644 index 4870ebb..0000000 --- a/AdamController.Core/Helpers/PythonScriptExecuteHelper.cs +++ /dev/null @@ -1,80 +0,0 @@ -using AdamController.WebApi.Client.Common; -using AdamController.WebApi.Client.v1.ResponseModel; -using System; - -namespace AdamController.Core.Helpers -{ - [Obsolete] - public class PythonScriptExecuteHelper - { - #region Declaration delegates and events - - public delegate void OnStandartOutput(string message); - public static event OnStandartOutput OnStandartOutputEvent; - - public delegate void OnExecuteStart(string message); - public static event OnExecuteStart OnExecuteStartEvent; - - public delegate void OnExecuteFinish(string message); - public static event OnExecuteFinish OnExecuteFinishEvent; - - #endregion - - static PythonScriptExecuteHelper() - { - //Change on comunication provider - //ComunicateHelper.OnAdamMessageReceivedEvent += OnAdamMessageReceivedAsync; - } - - private static void OnAdamMessageReceivedAsync(string message) - { - switch (message) - { - case "start": - OnExecuteStartEvent.Invoke(string.Empty); - break; - - case "error": - break; - - case string result when result.StartsWith("finish"): - OnExecuteFinishEvent.Invoke(FinishExecuteMessage(message.Remove(0, 6))); - break; - - default: - OnStandartOutputEvent.Invoke($"{message}\n"); - break; - } - } - - private static string FinishExecuteMessage(string resultJson = null) - { - string message = "\n======================\n<<Выполнение программы завершено>>"; - - if(string.IsNullOrEmpty(resultJson)) - return message; - - CommandExecuteResult executeResult = resultJson.ToCommandResult(); - - string messageWithResult = $"{message}\n" + - $"\n" + - $"Отчет о выполнении\n" + - $"======================\n" + - $"Начало выполнения: {executeResult.StartTime}\n" + - $"Завершение выполнения: {executeResult.EndTime}\n" + - $"Общее время выполнения: {executeResult.RunTime}\n" + - $"Код выхода: {executeResult.ExitCode}\n" + - $"Статус успешности завершения: {executeResult.Succeeded}" + - $"\n======================\n"; - - if (!string.IsNullOrEmpty(executeResult.StandardError)) - messageWithResult += $"Ошибка: {executeResult.StandardError}" + - $"\n======================\n"; - - return messageWithResult; - - } - - - } -} diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs index ce43960..a4f93df 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs @@ -30,17 +30,20 @@ public override void ConfirmNavigationRequest(NavigationContext navigationContex RegionChangeAwareService.InsideRegionNavigationRequestName = insideRegionName; SubRegionsRequestNavigate(insideRegionName, navigationContext.Parameters); } - } - //public override void OnNavigatedFrom(NavigationContext navigationContext) - //{ + base.ConfirmNavigationRequest(navigationContext, continuationCallback); + } - //} + public override void OnNavigatedTo(NavigationContext navigationContext) + { + base.OnNavigatedTo(navigationContext); - //public override void OnNavigatedTo(NavigationContext navigationContext) - //{ + } - //} + public override void OnNavigatedFrom(NavigationContext navigationContext) + { + base.OnNavigatedFrom(navigationContext); + } #endregion @@ -91,31 +94,6 @@ private void ComunicateHelperOnAdamUdpReceived(string message) } } - #region SelectedPageIndex - - //private int selectedPageIndex = 0; - //public int SelectedPageIndex - //{ - //get => selectedPageIndex; - //set - //{ - //if (value == selectedPageIndex) - //{ - //return; - //} - - //selectedPageIndex = value; - //GetSelectedPageIndex = value; - - //SetProperty(ref value, selectedPageIndex); - //} - //} - - - //public static int GetSelectedPageIndex { get; private set; } - - #endregion - #region Events TCP/IP clients private void OnTcpDisconnected() diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index dce6c0b..7fe09af 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -564,7 +564,7 @@ public string SourceTextEditor private DelegateCommand sendToExternalSourceEditor; public DelegateCommand SendToExternalSourceEditor => sendToExternalSourceEditor ??= new DelegateCommand(() => { - SetSelectedPageIndex(1); + //SetSelectedPageIndex(1); SendSourceToScriptEditor(SourceTextEditor); }, () => SourceTextEditor?.Length > 0); diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs index 387fbc9..68c31c8 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs @@ -50,7 +50,6 @@ public Color? SelectedBlocklyGridColour #endregion - #region BlocklyToolboxLanguage Settings public static ObservableCollection BlocklyLanguageCollection { get; private set; } = LanguagesCollection.BlocklyLanguageCollection; @@ -76,7 +75,6 @@ public BlocklyLanguageModel SelectedBlocklyToolboxLanguage #endregion - #region BlocklyTheme Settings public static ObservableCollection BlocklyThemes { get; private set; } = ThemesCollection.BlocklyThemes; diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index 11d2267..0b42daa 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -2,8 +2,10 @@ using AdamController.Core.Helpers; using AdamController.Core.Properties; using AdamController.Services.Interfaces; +using AdamController.WebApi.Client.v1; using MahApps.Metro.IconPacks; using Prism.Commands; +using System; using System.Windows; using System.Windows.Threading; @@ -11,6 +13,13 @@ namespace AdamController.Modules.FlayoutsRegion.ViewModels { public class NotificationViewModel : FlyoutBase { + #region DelegateCommands + + public DelegateCommand ConnectButtonComand { get; } + public DelegateCommand ClearNotificationsCommand { get; } + + #endregion + #region Services private readonly ICommunicationProviderService mCommunicationProvider; @@ -29,15 +38,153 @@ public class NotificationViewModel : FlyoutBase public NotificationViewModel(ICommunicationProviderService communicationProvider) { + SetFlyoutParametr(); + mCommunicationProvider = communicationProvider; + ConnectButtonComand = new (ConnectButton, ConnectButtonCanExecute); + ClearNotificationsCommand = new DelegateCommand(ClearNotifications, ClearNotificationsCanExecute); + } + + #endregion + + #region Navigation + + protected override void OnChanging(bool isOpening) + { + //need update status bar on opening + if(isOpening) + Subscribe(); + + if (!isOpening) + Unsubscribe(); + + base.OnChanging(isOpening); + } + + #endregion + + #region Private methods + + private void SetFlyoutParametr() + { Theme = FlyoutTheme.Inverse; - Header= "Центр уведомлений"; + Header = "Центр уведомлений"; IsModal = false; } #endregion + #region Subscription + + private void Subscribe() + { + mCommunicationProvider.RaiseTcpServiceCientConnected += OnRaiseTcpServiceCientConnected; + mCommunicationProvider.RaiseTcpServiceClientReconnected += OnRaiseTcpServiceClientReconnected; + mCommunicationProvider.RaiseTcpServiceClientDisconnect += OnRaiseTcpServiceClientDisconnect; + + } + + private void Unsubscribe() + { + mCommunicationProvider.RaiseTcpServiceCientConnected -= OnRaiseTcpServiceCientConnected; + mCommunicationProvider.RaiseTcpServiceClientReconnected -= OnRaiseTcpServiceClientReconnected; + mCommunicationProvider.RaiseTcpServiceClientDisconnect -= OnRaiseTcpServiceClientDisconnect; + } + + #endregion + + #region Event methods + + private void OnRaiseTcpServiceCientConnected(object sender) + { + // это должно быть не здесь + _ = BaseApi.StopPythonExecute(); + + TextOnConnectFlayotButton = cConnectButtonStatusConnected; + //TextOnStatusConnectToolbar = mToolbarStatusClientConnected; + + //ConnectIcon = PackIconModernKind.Disconnect; + IconOnConnectFlayoutButton = PackIconMaterialKind.Robot; + //throw new NotImplementedException(); + } + + private void OnRaiseTcpServiceClientReconnected(object sender, int reconnectCounter) + { + TextOnConnectFlayotButton = $"{cConnectButtonStatusReconnected} {reconnectCount}"; + //TextOnStatusConnectToolbar = $"{mToolbarStatusClientReconnected} {reconnectCount}"; + + //ConnectIcon = PackIconModernKind.TransitConnectionDeparture; + IconOnConnectFlayoutButton = PackIconMaterialKind.RobotConfused; + } + + private int reconnectCount = 0; + + private void OnRaiseTcpServiceClientDisconnect(object sender) + { + //если центр уведомлений закрыт, обновляем счетчик уведомлений + if (!IsOpen && Settings.Default.IsMessageShowOnAbortMainConnection) + { + //BadgeCounter++; + FailConnectMessageVisibility = Visibility.Visible; + } + + TextOnConnectFlayotButton = cConnectButtonStatusDisconnected; + //TextOnStatusConnectToolbar = mToolbarStatusClientDisconnected; + + //ConnectIcon = PackIconModernKind.Connect; + IconOnConnectFlayoutButton = PackIconMaterialKind.RobotDead; + } + + #endregion + + #region Delegatecommand methods + + private void ConnectButton() + { + //bool isNotifyButton = false; //(string)obj == "IsNotificationButtonCalling"; + + //if (isNotifyButton) + //{ + //ClearNotifications(); + //NotificationFlayoutsIsOpen = false; + //} + + //await Dispatcher.Yield(DispatcherPriority.Normal); + + if (mCommunicationProvider.IsTcpClientConnected) + { + mCommunicationProvider.DisconnectAllAsync(); + //return; + } + + if (!mCommunicationProvider.IsTcpClientConnected) + { + mCommunicationProvider.ConnectAllAsync(); + //return; + } + } + + private bool ConnectButtonCanExecute() + { + return true; + } + + /* #16 */ + private void ClearNotifications() + { + //BadgeCounter = 0; + FailConnectMessageVisibility = Visibility.Collapsed; + } + + private bool ClearNotificationsCanExecute() + { + return true; + } + + #endregion + + #region NotificationMessage Visiblity private Visibility noNewNotificationMessageVisibility = Visibility.Visible; @@ -78,78 +225,62 @@ public double NotificationOpacity #endregion - #region NotificationBadge - /* #16 */ - private void ClearNotification() - { - //BadgeCounter = 0; - FailConnectMessageVisibility = Visibility.Collapsed; - } - - #endregion - #region Connect/Disconnect button (Flayouts) - private string textOnConnectFlayotButton; + private string textOnConnectFlayotButton = cConnectButtonStatusDisconnected; public string TextOnConnectFlayotButton { get => textOnConnectFlayotButton; set => SetProperty(ref textOnConnectFlayotButton, value); } - private PackIconMaterialKind iconOnConnectFlayoutButton; + private PackIconMaterialKind iconOnConnectFlayoutButton = PackIconMaterialKind.Robot; public PackIconMaterialKind IconOnConnectFlayoutButton { get => iconOnConnectFlayoutButton; - set - { - if (value == iconOnConnectFlayoutButton) return; - - iconOnConnectFlayoutButton = value; - SetProperty(ref iconOnConnectFlayoutButton, value); - } + set => SetProperty(ref iconOnConnectFlayoutButton, value); + } #endregion - #region Connect/Disconnect toolbar + #region Events TCP/IP clients - private DelegateCommand connectButtonComand; - public DelegateCommand ConnectButtonComand => connectButtonComand ??= new DelegateCommand(async () => + private void OnTcpDisconnected() { - bool isNotifyButton = false; //(string)obj == "IsNotificationButtonCalling"; - - if (isNotifyButton) - { - ClearNotification(); - //NotificationFlayoutsIsOpen = false; - } - - await Dispatcher.Yield(DispatcherPriority.Normal); - - - if (mCommunicationProvider.IsTcpClientConnected) - { - mCommunicationProvider.DisconnectAllAsync(); - return; - } + //если центр уведомлений закрыт, обновляем счетчик уведомлений + //if (!NotificationFlayoutsIsOpen && Settings.Default.IsMessageShowOnAbortMainConnection) + //{ + //BadgeCounter++; + //FailConnectMessageVisibility = Visibility.Visible; + //} + + //TextOnConnectFlayotButton = mConnectButtonStatusDisconnected; + //TextOnStatusConnectToolbar = mToolbarStatusClientDisconnected; + + //ConnectIcon = PackIconModernKind.Connect; + //IconOnConnectFlayoutButton = PackIconMaterialKind.RobotDead; + } - if (!mCommunicationProvider.IsTcpClientConnected) - { - mCommunicationProvider.ConnectAllAsync(); - return; - } - }); + private void OnTcpConnected() + { + //_ = BaseApi.StopPythonExecute(); - #endregion + //TextOnConnectFlayotButton = mConnectButtonStatusConnected; + //TextOnStatusConnectToolbar = mToolbarStatusClientConnected; - #region Commands + //ConnectIcon = PackIconModernKind.Disconnect; + //IconOnConnectFlayoutButton = PackIconMaterialKind.Robot; + } - private DelegateCommand clearNotifications; - public DelegateCommand ClearNotifications => clearNotifications ??= new DelegateCommand(() => + private void OnTcpReconnected(int reconnectCount) { - ClearNotification(); - }); + //TextOnConnectFlayotButton = $"{mConnectButtonStatusReconnected} {reconnectCount}"; + //TextOnStatusConnectToolbar = $"{mToolbarStatusClientReconnected} {reconnectCount}"; + + //ConnectIcon = PackIconModernKind.TransitConnectionDeparture; + //IconOnConnectFlayoutButton = PackIconMaterialKind.RobotConfused; + } #endregion } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml index 5037bfe..fcaf446 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml @@ -7,14 +7,13 @@ xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks" xmlns:prism="http://prismlibrary.com/" - prism:ViewModelLocator.AutoWireViewModel="True" - > + prism:ViewModelLocator.AutoWireViewModel="True"> + Style="{DynamicResource MahApps.Styles.ScrollViewer}"> - + @@ -62,36 +61,36 @@ Text="Робот Адам отключен!" /> + Width="Auto" Height="Auto" + Margin="10" + FontStyle="Normal" + FontWeight="Bold" + FontSize="14" + Text="Проверьте связь и нажмите переподключить" /> + Margin="10 5 10 10" + mah:ControlsHelper.ContentCharacterCasing="Upper" + Content="Переподключить" + HorizontalAlignment="Stretch" + VerticalAlignment="Center" + HorizontalContentAlignment="Center" + VerticalContentAlignment="Center" + Command="{Binding ConnectButtonComand}" + CommandParameter="IsNotificationButtonCalling" + Style="{StaticResource MahApps.Styles.Button.MetroSquare}"> - + Margin="0 0 10 20" + TextWrapping="WrapWithOverflow" + VerticalAlignment="Bottom" + HorizontalAlignment="Right" + FontWeight="Bold"> + Очистить уведомления @@ -108,18 +107,18 @@ diff --git a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs index 2f78f39..9544c7d 100644 --- a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs +++ b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs @@ -11,9 +11,10 @@ namespace AdamController.Modules.MenuRegion.ViewModels { public class MenuRegionViewModel : RegionViewModelBase { + public DelegateCommand CloseAppCommand { get; } - public DelegateCommand ShowDialogCommand { get; private set; } - public DelegateCommand ShowRegionCommand { get; private set; } + public DelegateCommand ShowDialogCommand { get; } + public DelegateCommand ShowRegionCommand { get; } public MenuRegionViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) { From 55ec6ac8c4b5e69ae13e9715ac4cde94859d27b5 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 13 Apr 2024 10:28:43 +1000 Subject: [PATCH 081/181] Preparatory work for #22 --- .../IStatusBarNotificationDeliveryService.cs | 12 +++++++ .../StatusBarNotificationDeliveryService.cs | 32 +++++++++++++++++++ .../SubRegionChangeAwareService.cs | 13 +++++--- AdamController/App.xaml.cs | 5 +++ .../ViewModels/MainWindowViewModel.cs | 7 +++- .../ViewModels/StatusBarViewModel.cs | 13 +++++++- .../Views/StatusBarView.xaml | 1 + 7 files changed, 76 insertions(+), 7 deletions(-) create mode 100644 AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs create mode 100644 AdamController.Services/StatusBarNotificationDeliveryService.cs diff --git a/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs b/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs new file mode 100644 index 0000000..cb3db64 --- /dev/null +++ b/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs @@ -0,0 +1,12 @@ +namespace AdamController.Services.Interfaces +{ + public delegate void NewCompileLogMessageEventHandler(object sender, string message); + + public interface IStatusBarNotificationDeliveryService + { + public event NewCompileLogMessageEventHandler RaiseNewCompileLogMessageEvent; + + public string CompileLogMessage { get; set; } + + } +} diff --git a/AdamController.Services/StatusBarNotificationDeliveryService.cs b/AdamController.Services/StatusBarNotificationDeliveryService.cs new file mode 100644 index 0000000..af3d9f2 --- /dev/null +++ b/AdamController.Services/StatusBarNotificationDeliveryService.cs @@ -0,0 +1,32 @@ +using AdamController.Services.Interfaces; +using Prism.Mvvm; + + +namespace AdamController.Services +{ + public class StatusBarNotificationDeliveryService : BindableBase, IStatusBarNotificationDeliveryService + { + public event NewCompileLogMessageEventHandler RaiseNewCompileLogMessageEvent; + public StatusBarNotificationDeliveryService() { } + + private string compileLogMessage = string.Empty; + public string CompileLogMessage + { + get { return compileLogMessage; } + set + { + bool isNewValue = SetProperty(ref compileLogMessage, value); + + if (isNewValue) + OnRaiseNewCompileLogMessageEvent(CompileLogMessage); + } + } + + protected virtual void OnRaiseNewCompileLogMessageEvent(string message) + { + NewCompileLogMessageEventHandler raiseEvent = RaiseNewCompileLogMessageEvent; + raiseEvent.Invoke(this, message); + + } + } +} diff --git a/AdamController.Services/SubRegionChangeAwareService.cs b/AdamController.Services/SubRegionChangeAwareService.cs index c63a061..1e83c7e 100644 --- a/AdamController.Services/SubRegionChangeAwareService.cs +++ b/AdamController.Services/SubRegionChangeAwareService.cs @@ -1,21 +1,24 @@ using AdamController.Services.Interfaces; +using Prism.Mvvm; namespace AdamController.Services { - public class SubRegionChangeAwareService : ISubRegionChangeAwareService + public class SubRegionChangeAwareService : BindableBase, ISubRegionChangeAwareService { public SubRegionChangeAwareService() { } public event SubRegionChangeEventHandler RaiseSubRegionChangeEvent; - private string mRegionNavigtedToName; + private string insideRegionNavigationRequestName; public string InsideRegionNavigationRequestName { - get { return mRegionNavigtedToName; } + get { return insideRegionNavigationRequestName; } set { - mRegionNavigtedToName = value; - OnRaiseRegionChangeEvent(); + bool isNewValue = SetProperty(ref insideRegionNavigationRequestName, value); + + if (isNewValue) + OnRaiseRegionChangeEvent(); } } diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 1af9252..c9325d2 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -187,6 +187,11 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return remoteRunnerService; }); + containerRegistry.RegisterSingleton(containerRegistry => + { + return new StatusBarNotificationDeliveryService(); + }); + RegisterDialogs(containerRegistry); } diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index caed53d..62691e9 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -22,15 +22,18 @@ public class MainWindowViewModel : ViewModelBase public IRegionManager RegionManager { get; } private readonly ISubRegionChangeAwareService mSubRegionChangeAwareService; + private readonly IStatusBarNotificationDeliveryService mStatusBarNotification; #endregion #region ~ - public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService, ICommunicationProviderService communicationProviderService) + public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService, IStatusBarNotificationDeliveryService statusBarNotification) + { RegionManager = regionManager; mSubRegionChangeAwareService = subRegionChangeAwareService; + mStatusBarNotification = statusBarNotification; ShowRegionCommand = new DelegateCommand(ShowRegion); Subscribe(); @@ -145,6 +148,8 @@ private void Unsubscribe() private void MainWindowLoaded(object sender, RoutedEventArgs e) { ShowRegionCommand.Execute(SubRegionNames.SubRegionScratch); + + mStatusBarNotification.CompileLogMessage = "Загрузка приложения завершена"; } /// diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index cf208ea..57d3ac8 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -22,6 +22,7 @@ public class StatusBarViewModel : RegionViewModelBase private readonly IFlyoutManager mFlyoutManager; private readonly ICommunicationProviderService mCommunicationProviderService; + private readonly IStatusBarNotificationDeliveryService mStatusBarNotificationDelivery; #endregion @@ -38,10 +39,11 @@ public class StatusBarViewModel : RegionViewModelBase #region ~ - public StatusBarViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager, ICommunicationProviderService communicationProviderService) : base(regionManager, dialogService) + public StatusBarViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager, ICommunicationProviderService communicationProviderService, IStatusBarNotificationDeliveryService statusBarNotification) : base(regionManager, dialogService) { mFlyoutManager = flyoutManager; mCommunicationProviderService = communicationProviderService; + mStatusBarNotificationDelivery = statusBarNotification; OpenNotificationPanelDelegateCommand = new DelegateCommand(OpenNotificationPanel, OpenNotificationPanelCanExecute); } @@ -155,12 +157,16 @@ private void Subscribe() mCommunicationProviderService.RaiseTcpServiceCientConnected += RaiseAdamTcpCientConnected; mCommunicationProviderService.RaiseTcpServiceClientDisconnect += RaiseAdamTcpClientDisconnect; + mStatusBarNotificationDelivery.RaiseNewCompileLogMessageEvent += RaiseNewCompileLogMessageEvent; + } private void Unsubscribe() { mCommunicationProviderService.RaiseTcpServiceCientConnected -= RaiseAdamTcpCientConnected; mCommunicationProviderService.RaiseTcpServiceClientDisconnect -= RaiseAdamTcpClientDisconnect; + + mStatusBarNotificationDelivery.RaiseNewCompileLogMessageEvent -= RaiseNewCompileLogMessageEvent; } #endregion @@ -179,6 +185,11 @@ private void RaiseAdamTcpCientConnected(object sender) TextOnStatusConnectToolbar = cTextOnStatusConnectToolbarConnected; } + private void RaiseNewCompileLogMessageEvent(object sender, string message) + { + CompileLogStatusBar = message; + } + #endregion #region DelegateCommands methods diff --git a/Modules/AdamController.Modules.StatusBar/Views/StatusBarView.xaml b/Modules/AdamController.Modules.StatusBar/Views/StatusBarView.xaml index 6d6265d..98a7c85 100644 --- a/Modules/AdamController.Modules.StatusBar/Views/StatusBarView.xaml +++ b/Modules/AdamController.Modules.StatusBar/Views/StatusBarView.xaml @@ -48,6 +48,7 @@ Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}"> + Date: Sat, 13 Apr 2024 12:29:06 +1000 Subject: [PATCH 082/181] Close issue #22 --- .../IStatusBarNotificationDeliveryService.cs | 26 +++++- .../ISubRegionChangeAwareService.cs | 4 + .../StatusBarNotificationDeliveryService.cs | 88 +++++++++++++++++- .../SubRegionChangeAwareService.cs | 21 ++++- AdamController/App.xaml.cs | 13 ++- .../ViewModels/MainWindowViewModel.cs | 29 ------ .../ComputerVisionControlViewModel.cs | 9 +- .../ViewModels/ContentRegionViewModel.cs | 2 +- .../ViewModels/ScratchControlViewModel.cs | 53 +++++------ .../ScriptEditorControlViewModel.cs | 19 ++-- .../ViewModels/NotificationViewModel.cs | 89 +++++++++++-------- .../ViewModels/StatusBarViewModel.cs | 26 +++++- .../Views/StatusBarView.xaml | 2 + 13 files changed, 260 insertions(+), 121 deletions(-) diff --git a/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs b/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs index cb3db64..5438e96 100644 --- a/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs +++ b/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs @@ -1,12 +1,34 @@ -namespace AdamController.Services.Interfaces +using System; + +namespace AdamController.Services.Interfaces { + #region Delegates + + public delegate void ChangeProgressRingStateEventHandler(object sender, bool newState); public delegate void NewCompileLogMessageEventHandler(object sender, string message); + public delegate void NewAppLogMessageEventHandler(object sender, string message); + public delegate void NewNotificationBadgeMessageEventHandler(object sender, string message); + + #endregion - public interface IStatusBarNotificationDeliveryService + public interface IStatusBarNotificationDeliveryService : IDisposable { + #region Event + + public event ChangeProgressRingStateEventHandler RaiseChangeProgressRingStateEvent; public event NewCompileLogMessageEventHandler RaiseNewCompileLogMessageEvent; + public event NewAppLogMessageEventHandler RaiseNewAppLogMessageEvent; + public event NewNotificationBadgeMessageEventHandler RaiseNewNotificationBadgeMessageEvent; + + #endregion + + #region Public methods + public bool ProgressRingStart { get; set; } public string CompileLogMessage { get; set; } + public string AppLogMessage { get; set; } + public string NotificationBadgeMessage { get; set; } + #endregion } } diff --git a/AdamController.Services/Interfaces/ISubRegionChangeAwareService.cs b/AdamController.Services/Interfaces/ISubRegionChangeAwareService.cs index a3ccf64..a71d8fb 100644 --- a/AdamController.Services/Interfaces/ISubRegionChangeAwareService.cs +++ b/AdamController.Services/Interfaces/ISubRegionChangeAwareService.cs @@ -16,6 +16,10 @@ public interface ISubRegionChangeAwareService : IDisposable #endregion + #region Public fields + public string InsideRegionNavigationRequestName { get; set; } + + #endregion } } diff --git a/AdamController.Services/StatusBarNotificationDeliveryService.cs b/AdamController.Services/StatusBarNotificationDeliveryService.cs index af3d9f2..2a35ec7 100644 --- a/AdamController.Services/StatusBarNotificationDeliveryService.cs +++ b/AdamController.Services/StatusBarNotificationDeliveryService.cs @@ -6,13 +6,42 @@ namespace AdamController.Services { public class StatusBarNotificationDeliveryService : BindableBase, IStatusBarNotificationDeliveryService { + + #region Events + + public event ChangeProgressRingStateEventHandler RaiseChangeProgressRingStateEvent; public event NewCompileLogMessageEventHandler RaiseNewCompileLogMessageEvent; + public event NewAppLogMessageEventHandler RaiseNewAppLogMessageEvent; + public event NewNotificationBadgeMessageEventHandler RaiseNewNotificationBadgeMessageEvent; + + #endregion + + #region ~ + public StatusBarNotificationDeliveryService() { } + #endregion + + #region Public fields + + private bool progressRingStart; + public bool ProgressRingStart + { + get => progressRingStart; + set + { + bool isNewValue = SetProperty(ref progressRingStart, value); + + if (isNewValue) + OnRaiseChangeProgressRingStateEvent(ProgressRingStart); + + } + } + private string compileLogMessage = string.Empty; public string CompileLogMessage { - get { return compileLogMessage; } + get => compileLogMessage; set { bool isNewValue = SetProperty(ref compileLogMessage, value); @@ -21,12 +50,67 @@ public string CompileLogMessage OnRaiseNewCompileLogMessageEvent(CompileLogMessage); } } + + private string appLogMessage = string.Empty; + public string AppLogMessage + { + get => appLogMessage; + set + { + bool isNewValue = SetProperty(ref appLogMessage, value); + + if (isNewValue) + OnRaiseNewAppLogMessageEvent(AppLogMessage); + } + } + + private string notificationBadgeMessage = string.Empty; + public string NotificationBadgeMessage + { + get => notificationBadgeMessage; + set + { + bool isNewValue = SetProperty(ref notificationBadgeMessage, value); + + if (isNewValue) + OnRaiseNewNotificationBadgeMessageEvent(NotificationBadgeMessage); + } + } + + public void Dispose() + { + + } + + #endregion + + + #region OnRaise methods + + protected virtual void OnRaiseChangeProgressRingStateEvent(bool newState) + { + ChangeProgressRingStateEventHandler raiseEvent = RaiseChangeProgressRingStateEvent; + raiseEvent?.Invoke(this, newState); + } protected virtual void OnRaiseNewCompileLogMessageEvent(string message) { NewCompileLogMessageEventHandler raiseEvent = RaiseNewCompileLogMessageEvent; - raiseEvent.Invoke(this, message); + raiseEvent?.Invoke(this, message); + } + protected virtual void OnRaiseNewAppLogMessageEvent(string message) + { + NewAppLogMessageEventHandler raiseEvent = RaiseNewAppLogMessageEvent; + raiseEvent?.Invoke(this, message); } + + protected virtual void OnRaiseNewNotificationBadgeMessageEvent(string message) + { + NewNotificationBadgeMessageEventHandler raiseEvent = RaiseNewNotificationBadgeMessageEvent; + raiseEvent?.Invoke(this, message); + } + + #endregion } } diff --git a/AdamController.Services/SubRegionChangeAwareService.cs b/AdamController.Services/SubRegionChangeAwareService.cs index 1e83c7e..dd84ea5 100644 --- a/AdamController.Services/SubRegionChangeAwareService.cs +++ b/AdamController.Services/SubRegionChangeAwareService.cs @@ -5,10 +5,20 @@ namespace AdamController.Services { public class SubRegionChangeAwareService : BindableBase, ISubRegionChangeAwareService { - public SubRegionChangeAwareService() { } + #region Events public event SubRegionChangeEventHandler RaiseSubRegionChangeEvent; + #endregion + + #region ~ + + public SubRegionChangeAwareService() { } + + #endregion + + #region Public fields + private string insideRegionNavigationRequestName; public string InsideRegionNavigationRequestName { @@ -22,12 +32,19 @@ public string InsideRegionNavigationRequestName } } + public void Dispose() { } + + #endregion + + #region OnRaise events + protected virtual void OnRaiseRegionChangeEvent() { SubRegionChangeEventHandler raiseEvent = RaiseSubRegionChangeEvent; raiseEvent?.Invoke(this); } - public void Dispose(){} + #endregion + } } diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index c9325d2..1b6a00e 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -100,6 +100,11 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return new SubRegionChangeAwareService(); }); + containerRegistry.RegisterSingleton(containerRegistry => + { + return new StatusBarNotificationDeliveryService(); + }); + containerRegistry.RegisterSingleton(containerRegistry => { IContainer container = containerRegistry.GetContainer(); @@ -187,10 +192,7 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return remoteRunnerService; }); - containerRegistry.RegisterSingleton(containerRegistry => - { - return new StatusBarNotificationDeliveryService(); - }); + RegisterDialogs(containerRegistry); } @@ -278,6 +280,9 @@ private void SaveSettiings() private void DisposeServices() { Container.Resolve().Dispose(); + Container.Resolve().Dispose(); + + Container.Resolve().Dispose(); Container.Resolve().Dispose(); } diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index 62691e9..c728986 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -163,34 +163,5 @@ private void RaiseSubRegionChangeEvent(object sender) #endregion - #region Old - - //public MainWindowViewModel() - //{ - //ComunicateHelper.OnAdamTcpConnectedEvent += OnTcpConnected; - //ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; - //ComunicateHelper.OnAdamTcpReconnected += OnTcpReconnected; - //ComunicateHelper.OnAdamLogServerUdpReceivedEvent += ComunicateHelperOnAdamUdpReceived; - - - //InitAction(); - - //if (Settings.Default.AutoStartTcpConnect) - //{ - // ConnectButtonComand.Execute(null); - //} - //else - //{ - //init fields if autorun off - //TextOnConnectFlayotButton = mConnectButtonStatusDisconnected; - //TextOnStatusConnectToolbar = mToolbarStatusClientDisconnected; - - //ConnectIcon = PackIconModernKind.Connect; - //IconOnConnectFlayoutButton = PackIconMaterialKind.RobotDead; - //} - //} - - #endregion - } } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs index 2df818d..6324c00 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs @@ -133,14 +133,7 @@ public override void OnNavigatedFrom(NavigationContext navigationContext) public float SliderValue { get => sliderValue; - set - { - if (sliderValue == value) return; - - sliderValue = value; - - SetProperty(ref sliderValue, value); - } + set => SetProperty(ref sliderValue, value); } public string StopDirrection { get; private set; } = "{\"move\":{\"x\": 0, \"y\": 0, \"z\": 0}}"; diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs index a4f93df..1b1e9e9 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs @@ -25,7 +25,7 @@ public override void ConfirmNavigationRequest(NavigationContext navigationContex { if (navigationContext.NavigationService.Region.Name == RegionNames.ContentRegion) { - var insideRegionName = navigationContext.Uri.OriginalString; + string insideRegionName = navigationContext.Uri.OriginalString; RegionChangeAwareService.InsideRegionNavigationRequestName = insideRegionName; SubRegionsRequestNavigate(insideRegionName, navigationContext.Parameters); diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index 7fe09af..2807d94 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -31,16 +31,13 @@ public class ScratchControlViewModel : RegionViewModelBase private readonly ICommunicationProviderService mCommunicationProvider; private readonly IPythonRemoteRunnerService mPythonRemoteRunner; + private readonly IStatusBarNotificationDeliveryService mStatusBarNotificationDelivery; #endregion #region Action field public static Action SendSourceToScriptEditor { get; set; } - //public static Action SetSelectedPageIndex { get; set; } - public static Action AppLogStatusBarAction { get; set; } - public static Action CompileLogStatusBarAction { get; set; } - public static Action ProgressRingStartAction { get; set; } public static Action ReloadWebView { get; set; } #endregion @@ -48,10 +45,12 @@ public class ScratchControlViewModel : RegionViewModelBase private readonly IMessageDialogManager IDialogManager; private bool mIsWarningStackOwerflowAlreadyShow; - public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner) : base(regionManager, dialogService) + public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, + IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; mPythonRemoteRunner = pythonRemoteRunner; + mStatusBarNotificationDelivery = statusBarNotificationDelivery; IDialogManager = new MessageDialogManagerMahapps(Application.Current); @@ -92,7 +91,6 @@ public override void OnNavigatedFrom(NavigationContext navigationContext) #endregion - #region Event methods private async void OnRaiseTcpServiceCientConnected(object sender) @@ -147,7 +145,6 @@ private void OnRaisePythonScriptExecuteFinish(object sender, string message) #endregion - private void UpdatePythonInfo(string pythonVersion = "", string pythonBinPath = "", string pythonWorkDir = "") { if (string.IsNullOrEmpty(pythonVersion)) @@ -177,11 +174,13 @@ private void InitAction() private async void StartExecuteProgram() { - //CompileLogStatusBarAction("Сеанс отладки запущен"); + mStatusBarNotificationDelivery.CompileLogMessage = "Сеанс отладки запущен"; + mStatusBarNotificationDelivery.ProgressRingStart = true; + IsEnabledShowOpenDialogButton = false; IsEnabledStopExecuteButton = true; ResultTextEditor = string.Empty; - //ProgressRingStartAction(true); + if (!Settings.Default.ShadowWorkspaceInDebug) return; @@ -203,8 +202,9 @@ private async void OnStopExecuteProgram(string compileLogStatusBarAction) await ScratchControlView.ExecuteScript(Scripts.ShadowDisable); })); - //CompileLogStatusBarAction(compileLogStatusBarAction); - //ProgressRingStartAction(false); + mStatusBarNotificationDelivery.CompileLogMessage = compileLogStatusBarAction; + mStatusBarNotificationDelivery.ProgressRingStart = false; + IsEnabledShowOpenDialogButton = true; IsEnabledStopExecuteButton = false; } @@ -269,12 +269,11 @@ private async void InitBlockly() })); - //AppLogStatusBarAction("Загрузка скретч-редактора закончена"); + mStatusBarNotificationDelivery.AppLogMessage = "Загрузка скретч редактора завершена"; } catch { - //the error occurs when switching to another tab before blockly is fully loaded - //AppLogStatusBarAction("Загрузка скретч-редактора внезапно прервана"); + mStatusBarNotificationDelivery.AppLogMessage = "Загрузка скретч-редактора внезапно прервана"; } } @@ -473,15 +472,10 @@ public string ResultTextEditor get => resultTextEditor; set { - if(SetProperty(ref resultTextEditor, value)) + bool isNewValue = SetProperty(ref resultTextEditor, value); + + if (isNewValue) ResultTextEditorLength = ResultTextEditor.Length; - - //if (value == resultTextEditor) return; - - //resultTextEditor = value; - //ResultTextEditorLength = value.Length; - - //SetProperty(ref resultTextEditor, value); } } @@ -506,9 +500,9 @@ public string ResultTextEditorError get => resultTextEditorError; set { + if (value == resultTextEditorError) return; - if (value.Length > 0) resultTextEditorError = $"Error: {value}"; else @@ -564,7 +558,6 @@ public string SourceTextEditor private DelegateCommand sendToExternalSourceEditor; public DelegateCommand SendToExternalSourceEditor => sendToExternalSourceEditor ??= new DelegateCommand(() => { - //SetSelectedPageIndex(1); SendSourceToScriptEditor(SourceTextEditor); }, () => SourceTextEditor?.Length > 0); @@ -580,11 +573,11 @@ public string SourceTextEditor string path = IDialogManager.FilePathToSave; await FileHelper.WriteAsync(path, xmlWorkspace); - AppLogStatusBarAction($"Файл {IDialogManager.FilePathToSave} сохранен"); + mStatusBarNotificationDelivery.AppLogMessage = $"Файл {IDialogManager.FilePathToSave} сохранен"; } else { - AppLogStatusBarAction("Файл не сохранен"); + mStatusBarNotificationDelivery.AppLogMessage = "Файл не сохранен"; } }); @@ -599,11 +592,11 @@ public string SourceTextEditor string xml = await FileHelper.ReadTextAsStringAsync(path); _ = await ExecuteScriptFunctionAsync("loadSavedWorkspace", new object[] { xml }); - AppLogStatusBarAction($"Файл {path} загружен"); + mStatusBarNotificationDelivery.AppLogMessage = $"Файл {path} загружен"; } else { - AppLogStatusBarAction("Файл рабочей области не выбран"); + mStatusBarNotificationDelivery.AppLogMessage = "Файл рабочей области не выбран"; } }); @@ -698,11 +691,11 @@ await Task.Run(() => string path = IDialogManager.FilePathToSave; await FileHelper.WriteAsync(path, pythonProgram); - AppLogStatusBarAction($"Файл {IDialogManager.FilePathToSave} сохранен"); + mStatusBarNotificationDelivery.AppLogMessage = $"Файл {IDialogManager.FilePathToSave} сохранен"; } else { - AppLogStatusBarAction("Файл не сохранен"); + mStatusBarNotificationDelivery.AppLogMessage = "Файл не сохранен"; } }, () => SourceTextEditor?.Length > 0); diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs index ecc74e1..bf69492 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs @@ -19,17 +19,20 @@ public class ScriptEditorControlViewModel : RegionViewModelBase private readonly ICommunicationProviderService mCommunicationProvider; private readonly IPythonRemoteRunnerService mPythonRemoteRunner; + private readonly IStatusBarNotificationDeliveryService mStatusBarNotificationDelivery; #endregion - public static Action AppLogStatusBarAction { get; set; } + + //public static Action AppLogStatusBarAction { get; set; } private bool mIsWarningStackOwerflowAlreadyShow; private readonly IMessageDialogManager IDialogManager; - public ScriptEditorControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner) : base(regionManager, dialogService) + public ScriptEditorControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; mPythonRemoteRunner = pythonRemoteRunner; + mStatusBarNotificationDelivery = statusBarNotificationDelivery; IDialogManager = new MessageDialogManagerMahapps(Application.Current); InitAction(); @@ -352,11 +355,14 @@ await Task.Run(() => string pythonProgram = await FileHelper.ReadTextAsStringAsync(path); SourceTextEditor = pythonProgram; - AppLogStatusBarAction($"Файл {path} загружен"); + mStatusBarNotificationDelivery.AppLogMessage = $"Файл {path} загружен"; + //AppLogStatusBarAction($"Файл {path} загружен"); } else { - AppLogStatusBarAction("Файл c исходным кодом не выбран"); + mStatusBarNotificationDelivery.AppLogMessage = "Файл c исходным кодом не выбран"; + //AppLogStatusBarAction("Файл c исходным кодом не выбран"); + } }); @@ -376,11 +382,12 @@ await Task.Run(() => string path = IDialogManager.FilePathToSave; await FileHelper.WriteAsync(path, pythonProgram); - AppLogStatusBarAction($"Файл {IDialogManager.FilePathToSave} сохранен"); + mStatusBarNotificationDelivery.AppLogMessage = $"Файл {IDialogManager.FilePathToSave} сохранен"; + //AppLogStatusBarAction($"Файл {IDialogManager.FilePathToSave} сохранен"); } else { - AppLogStatusBarAction("Файл не сохранен"); + mStatusBarNotificationDelivery.AppLogMessage = "Файл не сохранен"; } }, () => SourceTextEditor?.Length > 0); diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index 0b42daa..634d5ad 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -38,7 +38,7 @@ public class NotificationViewModel : FlyoutBase public NotificationViewModel(ICommunicationProviderService communicationProvider) { - SetFlyoutParametr(); + SetFlyoutParametrs(); mCommunicationProvider = communicationProvider; @@ -53,8 +53,12 @@ public NotificationViewModel(ICommunicationProviderService communicationProvider protected override void OnChanging(bool isOpening) { //need update status bar on opening - if(isOpening) + if (isOpening) + { Subscribe(); + SetStatusConnection(mCommunicationProvider.IsTcpClientConnected); + } + if (!isOpening) Unsubscribe(); @@ -66,13 +70,45 @@ protected override void OnChanging(bool isOpening) #region Private methods - private void SetFlyoutParametr() + private void SetFlyoutParametrs() { Theme = FlyoutTheme.Inverse; Header = "Центр уведомлений"; IsModal = false; } + private void SetStatusConnection(bool connectionStatus) + { + if (connectionStatus) + { + // это должно быть не здесь + _ = BaseApi.StopPythonExecute(); + + TextOnConnectFlayotButton = cConnectButtonStatusConnected; + //TextOnStatusConnectToolbar = mToolbarStatusClientConnected; + + //ConnectIcon = PackIconModernKind.Disconnect; + IconOnConnectFlayoutButton = PackIconMaterialKind.Robot; + //throw new NotImplementedException(); + } + + if(!connectionStatus) + { + //если центр уведомлений закрыт, обновляем счетчик уведомлений + if (!IsOpen && Settings.Default.IsMessageShowOnAbortMainConnection) + { + //BadgeCounter++; + FailConnectMessageVisibility = Visibility.Visible; + } + + TextOnConnectFlayotButton = cConnectButtonStatusDisconnected; + //TextOnStatusConnectToolbar = mToolbarStatusClientDisconnected; + + //ConnectIcon = PackIconModernKind.Connect; + IconOnConnectFlayoutButton = PackIconMaterialKind.RobotDead; + } + } + #endregion #region Subscription @@ -98,15 +134,7 @@ private void Unsubscribe() private void OnRaiseTcpServiceCientConnected(object sender) { - // это должно быть не здесь - _ = BaseApi.StopPythonExecute(); - - TextOnConnectFlayotButton = cConnectButtonStatusConnected; - //TextOnStatusConnectToolbar = mToolbarStatusClientConnected; - - //ConnectIcon = PackIconModernKind.Disconnect; - IconOnConnectFlayoutButton = PackIconMaterialKind.Robot; - //throw new NotImplementedException(); + SetStatusConnection(true); } private void OnRaiseTcpServiceClientReconnected(object sender, int reconnectCounter) @@ -122,23 +150,12 @@ private void OnRaiseTcpServiceClientReconnected(object sender, int reconnectCoun private void OnRaiseTcpServiceClientDisconnect(object sender) { - //если центр уведомлений закрыт, обновляем счетчик уведомлений - if (!IsOpen && Settings.Default.IsMessageShowOnAbortMainConnection) - { - //BadgeCounter++; - FailConnectMessageVisibility = Visibility.Visible; - } - - TextOnConnectFlayotButton = cConnectButtonStatusDisconnected; - //TextOnStatusConnectToolbar = mToolbarStatusClientDisconnected; - - //ConnectIcon = PackIconModernKind.Connect; - IconOnConnectFlayoutButton = PackIconMaterialKind.RobotDead; + SetStatusConnection(false); } #endregion - #region Delegatecommand methods + #region DelegateCommands methods private void ConnectButton() { @@ -184,7 +201,6 @@ private bool ClearNotificationsCanExecute() #endregion - #region NotificationMessage Visiblity private Visibility noNewNotificationMessageVisibility = Visibility.Visible; @@ -200,15 +216,16 @@ public Visibility FailConnectMessageVisibility get => failConnectMessageVisibility; set { - if (value == failConnectMessageVisibility) return; - - if (value == Visibility.Visible) - NoNewNotificationMessageVisibility = Visibility.Collapsed; - if (value == Visibility.Collapsed) - NoNewNotificationMessageVisibility = Visibility.Visible; - - failConnectMessageVisibility = value; - SetProperty(ref failConnectMessageVisibility, value); + bool isNewValue = SetProperty(ref failConnectMessageVisibility, value); + + if (isNewValue) + { + if (FailConnectMessageVisibility == Visibility.Visible) + NoNewNotificationMessageVisibility = Visibility.Collapsed; + + if (FailConnectMessageVisibility == Visibility.Collapsed) + NoNewNotificationMessageVisibility = Visibility.Visible; + } } } @@ -244,7 +261,7 @@ public PackIconMaterialKind IconOnConnectFlayoutButton #endregion - #region Events TCP/IP clients + #region Events TCP/IP clients OLD private void OnTcpDisconnected() { diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index 57d3ac8..abd93b1 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -157,16 +157,24 @@ private void Subscribe() mCommunicationProviderService.RaiseTcpServiceCientConnected += RaiseAdamTcpCientConnected; mCommunicationProviderService.RaiseTcpServiceClientDisconnect += RaiseAdamTcpClientDisconnect; + mStatusBarNotificationDelivery.RaiseChangeProgressRingStateEvent += RaiseChangeProgressRingStateEvent; mStatusBarNotificationDelivery.RaiseNewCompileLogMessageEvent += RaiseNewCompileLogMessageEvent; - + mStatusBarNotificationDelivery.RaiseNewAppLogMessageEvent += RaiseNewAppLogMessageEvent; + mStatusBarNotificationDelivery.RaiseNewNotificationBadgeMessageEvent += RaiseNewNotificationBadgeMessageEvent; } + + private void Unsubscribe() { mCommunicationProviderService.RaiseTcpServiceCientConnected -= RaiseAdamTcpCientConnected; mCommunicationProviderService.RaiseTcpServiceClientDisconnect -= RaiseAdamTcpClientDisconnect; + + mStatusBarNotificationDelivery.RaiseChangeProgressRingStateEvent -= RaiseChangeProgressRingStateEvent; mStatusBarNotificationDelivery.RaiseNewCompileLogMessageEvent -= RaiseNewCompileLogMessageEvent; + mStatusBarNotificationDelivery.RaiseNewAppLogMessageEvent -= RaiseNewAppLogMessageEvent; + mStatusBarNotificationDelivery.RaiseNewNotificationBadgeMessageEvent -= RaiseNewNotificationBadgeMessageEvent; } #endregion @@ -185,11 +193,27 @@ private void RaiseAdamTcpCientConnected(object sender) TextOnStatusConnectToolbar = cTextOnStatusConnectToolbarConnected; } + private void RaiseChangeProgressRingStateEvent(object sender, bool newState) + { + ProgressRingStart = newState; + } + private void RaiseNewCompileLogMessageEvent(object sender, string message) { CompileLogStatusBar = message; } + private void RaiseNewAppLogMessageEvent(object sender, string message) + { + AppLogStatusBar = message; + } + + private void RaiseNewNotificationBadgeMessageEvent(object sender, string message) + { + NotificationBadge = message; + } + + #endregion #region DelegateCommands methods diff --git a/Modules/AdamController.Modules.StatusBar/Views/StatusBarView.xaml b/Modules/AdamController.Modules.StatusBar/Views/StatusBarView.xaml index 98a7c85..9854e65 100644 --- a/Modules/AdamController.Modules.StatusBar/Views/StatusBarView.xaml +++ b/Modules/AdamController.Modules.StatusBar/Views/StatusBarView.xaml @@ -131,7 +131,9 @@ Background="Transparent" Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}" Style="{StaticResource MahApps.Styles.Button.ToolBar}"> + + From f61f4805ba49b7256289fe36409b8c50854bd3be Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 13 Apr 2024 22:55:05 +1000 Subject: [PATCH 083/181] Fix issue #9 p1 --- AdamController.Core/SubRegionNames.cs | 2 +- .../ViewModels/MenuRegionViewModel.cs | 106 +++++++++++++++++- .../Views/MenuRegionView.xaml | 21 +++- 3 files changed, 121 insertions(+), 8 deletions(-) diff --git a/AdamController.Core/SubRegionNames.cs b/AdamController.Core/SubRegionNames.cs index 1900543..1b64836 100644 --- a/AdamController.Core/SubRegionNames.cs +++ b/AdamController.Core/SubRegionNames.cs @@ -7,7 +7,7 @@ public class SubRegionNames /// public const string InsideConentRegion = $"{nameof(InsideConentRegion)}"; - public const string SubRegionHamburgerMenu = $"{nameof(SubRegionHamburgerMenu)}"; + //public const string SubRegionHamburgerMenu = $"{nameof(SubRegionHamburgerMenu)}"; public const string SubRegionScratch = $"{nameof(SubRegionScratch)}"; diff --git a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs index 9544c7d..804d079 100644 --- a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs +++ b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs @@ -6,18 +6,31 @@ using Prism.Services.Dialogs; using System.Windows; using System; +using AdamController.Services.Interfaces; namespace AdamController.Modules.MenuRegion.ViewModels { public class MenuRegionViewModel : RegionViewModelBase { + #region DelegateCommands + public DelegateCommand CloseAppCommand { get; } public DelegateCommand ShowDialogCommand { get; } public DelegateCommand ShowRegionCommand { get; } - public MenuRegionViewModel(IRegionManager regionManager, IDialogService dialogService) : base(regionManager, dialogService) + #endregion + + #region Services + + private readonly ISubRegionChangeAwareService mSubRegionChangeAware; + + #endregion + + public MenuRegionViewModel(IRegionManager regionManager, IDialogService dialogService, ISubRegionChangeAwareService subRegionChangeAware) : base(regionManager, dialogService) { + mSubRegionChangeAware = subRegionChangeAware; + CloseAppCommand = new DelegateCommand(CloseApp); ShowDialogCommand = new DelegateCommand(ShowDialog); ShowRegionCommand = new DelegateCommand(ShowRegion); @@ -32,16 +45,107 @@ public override void ConfirmNavigationRequest(NavigationContext navigationContex public override void OnNavigatedTo(NavigationContext navigationContext) { + Subscribe(); + base.OnNavigatedTo(navigationContext); } public override void OnNavigatedFrom(NavigationContext navigationContext) { + Unsubscribe(); + base.OnNavigatedFrom(navigationContext); } #endregion + #region Public fields + + private bool isCheckedScratchMenuItem; + public bool IsCheckedScratchMenuItem + { + get => isCheckedScratchMenuItem; + set => SetProperty(ref isCheckedScratchMenuItem, value); + } + + private bool isCheckedScriptEditorMenuItem; + public bool IsCheckedScriptEditorMenuItem + { + get => isCheckedScriptEditorMenuItem; + set => SetProperty(ref isCheckedScriptEditorMenuItem, value); + } + + private bool isCheckedComputerVisionMenuItem; + public bool IsCheckedComputerVisionMenuItem + { + get => isCheckedComputerVisionMenuItem; + set => SetProperty(ref isCheckedComputerVisionMenuItem, value); + } + + private bool isCheckedVisualSettingsMenuItem; + public bool IsCheckedVisualSettingsMenuItem + { + get => isCheckedVisualSettingsMenuItem; + set => SetProperty(ref isCheckedVisualSettingsMenuItem, value); + } + + #endregion + + #region Private methods + + private void ChangeCheckedMenuItem(string selectedSubRegionName) + { + ResetIsCheckedMenuItem(); + + switch (selectedSubRegionName) + { + case SubRegionNames.SubRegionScratch: + IsCheckedScratchMenuItem = true; + break; + case SubRegionNames.SubRegionScriptEditor: + IsCheckedScriptEditorMenuItem = true; + break; + case SubRegionNames.SubRegionComputerVisionControl: + IsCheckedComputerVisionMenuItem = true; + break; + case SubRegionNames.SubRegionVisualSettings: + IsCheckedVisualSettingsMenuItem = true; + break; + } + } + + private void ResetIsCheckedMenuItem() + { + IsCheckedScratchMenuItem = false; + IsCheckedScriptEditorMenuItem = false; + IsCheckedComputerVisionMenuItem = false; + IsCheckedVisualSettingsMenuItem = false; + } + + #endregion + + #region Subscription + + private void Subscribe() + { + mSubRegionChangeAware.RaiseSubRegionChangeEvent += RaiseSubRegionChangeEvent; + } + + private void Unsubscribe() + { + mSubRegionChangeAware.RaiseSubRegionChangeEvent -= RaiseSubRegionChangeEvent; + } + + #endregion + + #region Event methods + + private void RaiseSubRegionChangeEvent(object sender) + { + ChangeCheckedMenuItem(mSubRegionChangeAware.InsideRegionNavigationRequestName); + } + + #endregion #region Command methods diff --git a/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml b/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml index dc6874f..80b5f8b 100644 --- a/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml +++ b/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml @@ -3,7 +3,8 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" xmlns:prism="http://prismlibrary.com/" - prism:ViewModelLocator.AutoWireViewModel="True" > + prism:ViewModelLocator.AutoWireViewModel="True" + xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" > @@ -46,6 +47,7 @@ + @@ -53,19 +55,26 @@ - + + CommandParameter="{x:Static core:SubRegionNames.SubRegionScratch}" + IsChecked="{Binding IsCheckedScratchMenuItem}" /> + + CommandParameter="{x:Static core:SubRegionNames.SubRegionScriptEditor}" + IsChecked="{Binding IsCheckedScriptEditorMenuItem}"/> + + CommandParameter="{x:Static core:SubRegionNames.SubRegionComputerVisionControl}" + IsChecked="{Binding IsCheckedComputerVisionMenuItem}"/> + + CommandParameter="{x:Static core:SubRegionNames.SubRegionVisualSettings}" + IsChecked="{Binding IsCheckedVisualSettingsMenuItem}"/> From 5b03b7872afb91c9ecffa15e48fbe08962977395 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 13 Apr 2024 22:59:16 +1000 Subject: [PATCH 084/181] Clean App.xaml --- AdamController/App.xaml | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/AdamController/App.xaml b/AdamController/App.xaml index 0de90ec..a8f8b42 100644 --- a/AdamController/App.xaml +++ b/AdamController/App.xaml @@ -1,23 +1,17 @@  - - + xmlns:prism="http://prismlibrary.com/"> + - - From 3e84cb5036b309d0baeeffed9b1843d79e928c68 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 14 Apr 2024 07:09:11 +1000 Subject: [PATCH 085/181] Close issue #9 --- AdamController/App.xaml | 6 ++++-- .../AdamController.WebApi.Client.csproj | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/AdamController/App.xaml b/AdamController/App.xaml index a8f8b42..a10b326 100644 --- a/AdamController/App.xaml +++ b/AdamController/App.xaml @@ -10,8 +10,10 @@ - - + + + + diff --git a/Legacy/AdamController.WebApi.Client/AdamController.WebApi.Client.csproj b/Legacy/AdamController.WebApi.Client/AdamController.WebApi.Client.csproj index 299bd63..0b8e6cf 100644 --- a/Legacy/AdamController.WebApi.Client/AdamController.WebApi.Client.csproj +++ b/Legacy/AdamController.WebApi.Client/AdamController.WebApi.Client.csproj @@ -7,7 +7,7 @@ - + From abf2d4768c449eea3b1eb4a3346f244ac5eb7112 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 14 Apr 2024 07:57:50 +1000 Subject: [PATCH 086/181] Close issue #23 --- .../CommunicationProviderService.cs | 60 +++++++++---------- .../ICommunicationProviderService.cs | 22 ++++--- .../Interfaces/IPythonRemoteRunnerService.cs | 12 ++-- .../Interfaces/ITcpClientService.cs | 24 ++++---- .../Interfaces/IUdpClientService.cs | 4 +- .../Interfaces/IUdpServerService.cs | 4 +- .../Interfaces/IWebSocketClientService.cs | 12 ++-- .../PythonRemoteRunnerService.cs | 28 ++++----- AdamController.Services/TcpClientService.cs | 50 ++++++++-------- AdamController.Services/UdpClientService.cs | 8 +-- AdamController.Services/UdpServerService.cs | 8 +-- .../WebSocketClientService.cs | 24 ++++---- .../ViewModels/ScratchControlViewModel.cs | 20 +++---- .../ScriptEditorControlViewModel.cs | 12 ++-- .../ViewModels/NotificationViewModel.cs | 12 ++-- .../ViewModels/StatusBarViewModel.cs | 8 +-- 16 files changed, 153 insertions(+), 155 deletions(-) diff --git a/AdamController.Services/CommunicationProviderService.cs b/AdamController.Services/CommunicationProviderService.cs index 812b629..7280f61 100644 --- a/AdamController.Services/CommunicationProviderService.cs +++ b/AdamController.Services/CommunicationProviderService.cs @@ -9,11 +9,11 @@ public class CommunicationProviderService : ICommunicationProviderService { #region Events - public event TcpServiceCientConnected RaiseTcpServiceCientConnected; - public event TcpServiceClientDisconnect RaiseTcpServiceClientDisconnect; - public event TcpServiceClientReconnected RaiseTcpServiceClientReconnected; - public event UdpServiceServerReceived RaiseUdpServiceServerReceived; - public event UdpServiceClientReceived RaiseUdpServiceClientReceived; + public event TcpServiceCientConnectedEventHandler RaiseTcpServiceCientConnectedEvent; + public event TcpServiceClientDisconnectEventHandler RaiseTcpServiceClientDisconnectEvent; + public event TcpServiceClientReconnectedEventHandler RaiseTcpServiceClientReconnectedEvent; + public event UdpServiceServerReceivedEventHandler RaiseUdpServiceServerReceivedEvent; + public event UdpServiceClientReceivedEventHandler RaiseUdpServiceClientReceivedEvent; #endregion @@ -91,20 +91,20 @@ public void Dispose() private void Subscribe() { - mTcpClientService.RaiseTcpClientReconnected += RaiseServiceTcpClientReconnected; - mTcpClientService.RaiseTcpCientConnected += RaiseServiceTcpCientConnected; - mTcpClientService.RaiseTcpClientDisconnected += RaiseTcpClientDisconnected; - mUdpClientService.RaiseUdpClientReceived += RaiseServiceUdpClientReceived; - mUdpServerService.RaiseUdpServerReceived += RaiseServiceUdpServerReceived; + mTcpClientService.RaiseTcpClientReconnectedEvent += RaiseServiceTcpClientReconnected; + mTcpClientService.RaiseTcpCientConnectedEvent += RaiseServiceTcpCientConnected; + mTcpClientService.RaiseTcpClientDisconnectedEvent += RaiseTcpClientDisconnected; + mUdpClientService.RaiseUdpClientReceivedEvent += RaiseServiceUdpClientReceived; + mUdpServerService.RaiseUdpServerReceivedEvent += RaiseServiceUdpServerReceived; } private void Unsubscribe() { - mTcpClientService.RaiseTcpClientReconnected -= RaiseServiceTcpClientReconnected; - mTcpClientService.RaiseTcpCientConnected -= RaiseServiceTcpCientConnected; - mTcpClientService.RaiseTcpClientDisconnected -= RaiseTcpClientDisconnected; - mUdpClientService.RaiseUdpClientReceived -= RaiseServiceUdpClientReceived; - mUdpServerService.RaiseUdpServerReceived -= RaiseServiceUdpServerReceived; + mTcpClientService.RaiseTcpClientReconnectedEvent -= RaiseServiceTcpClientReconnected; + mTcpClientService.RaiseTcpCientConnectedEvent -= RaiseServiceTcpCientConnected; + mTcpClientService.RaiseTcpClientDisconnectedEvent -= RaiseTcpClientDisconnected; + mUdpClientService.RaiseUdpClientReceivedEvent -= RaiseServiceUdpClientReceived; + mUdpServerService.RaiseUdpServerReceivedEvent -= RaiseServiceUdpServerReceived; } #endregion @@ -115,7 +115,7 @@ private void RaiseServiceTcpCientConnected(object sender) { IsTcpClientConnected = true; - OnRaiseTcpServiceCientConnected(); + OnRaiseTcpServiceCientConnectedEvent(); mUdpClientService.Start(); mUdpServerService.Start(); @@ -126,7 +126,7 @@ private void RaiseTcpClientDisconnected(object sender) { IsTcpClientConnected = false; - OnRaiseTcpServiceClientDisconnect(); + OnRaiseTcpServiceClientDisconnectEvent(); mUdpClientService.Stop(); mUdpServerService.Stop(); @@ -135,14 +135,14 @@ private void RaiseTcpClientDisconnected(object sender) private void RaiseServiceTcpClientReconnected(object sender, int reconnectCount) { - OnRaiseTcpServiceClientReconnected(reconnectCount); + OnRaiseTcpServiceClientReconnectedEvent(reconnectCount); } private void RaiseServiceUdpClientReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size) { //string encodedMessage = Encoding.UTF8.GetString(buffer); string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); - OnRaiseUdpServiceClientReceived(encodedMessage); + OnRaiseUdpServiceClientReceivedEvent(encodedMessage); } @@ -150,40 +150,40 @@ private void RaiseServiceUdpServerReceived(object sender, EndPoint endpoint, byt { //string encodedMessage = Encoding.UTF8.GetString(buffer); string encodedMessage = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); - OnRaiseUdpServiceServerReceived(encodedMessage); + OnRaiseUdpServiceServerReceivedEvent(encodedMessage); } #endregion #region OnRaise events - protected virtual void OnRaiseTcpServiceCientConnected() + protected virtual void OnRaiseTcpServiceCientConnectedEvent() { - TcpServiceCientConnected raiseEvent = RaiseTcpServiceCientConnected; + TcpServiceCientConnectedEventHandler raiseEvent = RaiseTcpServiceCientConnectedEvent; raiseEvent?.Invoke(this); } - protected virtual void OnRaiseTcpServiceClientDisconnect() + protected virtual void OnRaiseTcpServiceClientDisconnectEvent() { - TcpServiceClientDisconnect raiseEvent = RaiseTcpServiceClientDisconnect; + TcpServiceClientDisconnectEventHandler raiseEvent = RaiseTcpServiceClientDisconnectEvent; raiseEvent?.Invoke(this); } - public virtual void OnRaiseTcpServiceClientReconnected(int reconnectCounter) + public virtual void OnRaiseTcpServiceClientReconnectedEvent(int reconnectCounter) { - TcpServiceClientReconnected raiseEvent = RaiseTcpServiceClientReconnected; + TcpServiceClientReconnectedEventHandler raiseEvent = RaiseTcpServiceClientReconnectedEvent; raiseEvent?.Invoke(this, reconnectCounter); } - protected virtual void OnRaiseUdpServiceServerReceived(string message) + protected virtual void OnRaiseUdpServiceServerReceivedEvent(string message) { - UdpServiceServerReceived raiseEvent = RaiseUdpServiceServerReceived; + UdpServiceServerReceivedEventHandler raiseEvent = RaiseUdpServiceServerReceivedEvent; raiseEvent?.Invoke(this, message); } - protected virtual void OnRaiseUdpServiceClientReceived(string message) + protected virtual void OnRaiseUdpServiceClientReceivedEvent(string message) { - UdpServiceClientReceived raiseEvent = RaiseUdpServiceClientReceived; + UdpServiceClientReceivedEventHandler raiseEvent = RaiseUdpServiceClientReceivedEvent; raiseEvent?.Invoke(this, message); } diff --git a/AdamController.Services/Interfaces/ICommunicationProviderService.cs b/AdamController.Services/Interfaces/ICommunicationProviderService.cs index 1e428af..4249605 100644 --- a/AdamController.Services/Interfaces/ICommunicationProviderService.cs +++ b/AdamController.Services/Interfaces/ICommunicationProviderService.cs @@ -4,11 +4,11 @@ namespace AdamController.Services.Interfaces { #region Delegate - public delegate void TcpServiceCientConnected(object sender); - public delegate void TcpServiceClientDisconnect(object sender); - public delegate void TcpServiceClientReconnected(object sender, int reconnectCounter); - public delegate void UdpServiceServerReceived(object sender, string message); - public delegate void UdpServiceClientReceived(object sender, string message); + public delegate void TcpServiceCientConnectedEventHandler(object sender); + public delegate void TcpServiceClientDisconnectEventHandler(object sender); + public delegate void TcpServiceClientReconnectedEventHandler(object sender, int reconnectCounter); + public delegate void UdpServiceServerReceivedEventHandler(object sender, string message); + public delegate void UdpServiceClientReceivedEventHandler(object sender, string message); #endregion @@ -19,13 +19,11 @@ public interface ICommunicationProviderService : IDisposable { #region Events - public event TcpServiceCientConnected RaiseTcpServiceCientConnected; - public event TcpServiceClientDisconnect RaiseTcpServiceClientDisconnect; - public event TcpServiceClientReconnected RaiseTcpServiceClientReconnected; - public event UdpServiceServerReceived RaiseUdpServiceServerReceived; - public event UdpServiceClientReceived RaiseUdpServiceClientReceived; - - + public event TcpServiceCientConnectedEventHandler RaiseTcpServiceCientConnectedEvent; + public event TcpServiceClientDisconnectEventHandler RaiseTcpServiceClientDisconnectEvent; + public event TcpServiceClientReconnectedEventHandler RaiseTcpServiceClientReconnectedEvent; + public event UdpServiceServerReceivedEventHandler RaiseUdpServiceServerReceivedEvent; + public event UdpServiceClientReceivedEventHandler RaiseUdpServiceClientReceivedEvent; #endregion diff --git a/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs b/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs index 92a3056..45adf9e 100644 --- a/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs +++ b/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs @@ -4,9 +4,9 @@ namespace AdamController.Services.Interfaces { #region Delegate - public delegate void PythonStandartOutput(object sender, string message); - public delegate void PythonScriptExecuteStart(object sender); - public delegate void PythonScriptExecuteFinish(object sender, string message); + public delegate void PythonStandartOutputEventHandler(object sender, string message); + public delegate void PythonScriptExecuteStartEventHandler(object sender); + public delegate void PythonScriptExecuteFinishEventHandler(object sender, string message); #endregion @@ -14,9 +14,9 @@ public interface IPythonRemoteRunnerService : IDisposable { #region Events - public event PythonStandartOutput RaisePythonStandartOutput; - public event PythonScriptExecuteStart RaisePythonScriptExecuteStart; - public event PythonScriptExecuteFinish RaisePythonScriptExecuteFinish; + public event PythonStandartOutputEventHandler RaisePythonStandartOutputEvent; + public event PythonScriptExecuteStartEventHandler RaisePythonScriptExecuteStartEvent; + public event PythonScriptExecuteFinishEventHandler RaisePythonScriptExecuteFinishEvent; #endregion } diff --git a/AdamController.Services/Interfaces/ITcpClientService.cs b/AdamController.Services/Interfaces/ITcpClientService.cs index 21ee9e3..9afc450 100644 --- a/AdamController.Services/Interfaces/ITcpClientService.cs +++ b/AdamController.Services/Interfaces/ITcpClientService.cs @@ -5,12 +5,12 @@ namespace AdamController.Services.Interfaces { #region Delegate - public delegate void TcpCientConnected(object sender); - public delegate void TcpCientSent(object sender, long sent, long pending); - public delegate void TcpClientDisconnect(object sender); - public delegate void TcpClientError(object sender, SocketError error); - public delegate void TcpClientReceived(object sender, byte[] buffer, long offset, long size); - public delegate void TcpClientReconnected(object sender, int reconnectCount); + public delegate void TcpCientConnectedEventHandler(object sender); + public delegate void TcpCientSentEventHandler(object sender, long sent, long pending); + public delegate void TcpClientDisconnectEventHandler(object sender); + public delegate void TcpClientErrorEventHandler(object sender, SocketError error); + public delegate void TcpClientReceivedEventHandler(object sender, byte[] buffer, long offset, long size); + public delegate void TcpClientReconnectedEventHandler(object sender, int reconnectCount); #endregion @@ -19,12 +19,12 @@ public interface ITcpClientService : IDisposable #region Events - public event TcpCientConnected RaiseTcpCientConnected; - public event TcpCientSent RaiseTcpCientSent; - public event TcpClientDisconnect RaiseTcpClientDisconnected; - public event TcpClientError RaiseTcpClientError; - public event TcpClientReceived RaiseTcpClientReceived; - public event TcpClientReconnected RaiseTcpClientReconnected; + public event TcpCientConnectedEventHandler RaiseTcpCientConnectedEvent; + public event TcpCientSentEventHandler RaiseTcpCientSentEvent; + public event TcpClientDisconnectEventHandler RaiseTcpClientDisconnectedEvent; + public event TcpClientErrorEventHandler RaiseTcpClientErrorEvent; + public event TcpClientReceivedEventHandler RaiseTcpClientReceivedEvent; + public event TcpClientReconnectedEventHandler RaiseTcpClientReconnectedEvent; #endregion diff --git a/AdamController.Services/Interfaces/IUdpClientService.cs b/AdamController.Services/Interfaces/IUdpClientService.cs index d7dd47b..8d9e2b0 100644 --- a/AdamController.Services/Interfaces/IUdpClientService.cs +++ b/AdamController.Services/Interfaces/IUdpClientService.cs @@ -6,7 +6,7 @@ namespace AdamController.Services.Interfaces { #region Delegate - public delegate void UdpClientReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size); + public delegate void UdpClientReceivedEventHandler(object sender, EndPoint endpoint, byte[] buffer, long offset, long size); #endregion @@ -14,7 +14,7 @@ public interface IUdpClientService : IDisposable { #region Events - public event UdpClientReceived RaiseUdpClientReceived; + public event UdpClientReceivedEventHandler RaiseUdpClientReceivedEvent; #endregion diff --git a/AdamController.Services/Interfaces/IUdpServerService.cs b/AdamController.Services/Interfaces/IUdpServerService.cs index 1519547..3fc7793 100644 --- a/AdamController.Services/Interfaces/IUdpServerService.cs +++ b/AdamController.Services/Interfaces/IUdpServerService.cs @@ -7,7 +7,7 @@ namespace AdamController.Services.Interfaces #region Delegate - public delegate void UdpServerReceived(object sender, EndPoint endpoint, byte[] buffer, long offset, long size); + public delegate void UdpServerReceivedEventHandler(object sender, EndPoint endpoint, byte[] buffer, long offset, long size); #endregion @@ -15,7 +15,7 @@ public interface IUdpServerService : IDisposable { #region Events - public event UdpServerReceived RaiseUdpServerReceived; + public event UdpServerReceivedEventHandler RaiseUdpServerReceivedEvent; #endregion diff --git a/AdamController.Services/Interfaces/IWebSocketClientService.cs b/AdamController.Services/Interfaces/IWebSocketClientService.cs index 8758dcb..4e3ce37 100644 --- a/AdamController.Services/Interfaces/IWebSocketClientService.cs +++ b/AdamController.Services/Interfaces/IWebSocketClientService.cs @@ -6,9 +6,9 @@ namespace AdamController.Services.Interfaces #region Delegate - public delegate void WebSocketClientReceived(object sender, string text); - public delegate void WebSocketConnected(object sender); - public delegate void WebSocketClientDisconnect(object sender); + public delegate void WebSocketClientReceivedEventHandler(object sender, string text); + public delegate void WebSocketConnectedEventHandler(object sender); + public delegate void WebSocketClientDisconnectEventHandler(object sender); #endregion @@ -16,9 +16,9 @@ public interface IWebSocketClientService : IDisposable { #region Events - public event WebSocketClientReceived RaiseWebSocketClientReceived; - public event WebSocketConnected RaiseWebSocketConnected; - public event WebSocketClientDisconnect RaiseWebSocketClientDisconnect; + public event WebSocketClientReceivedEventHandler RaiseWebSocketClientReceivedEvent; + public event WebSocketConnectedEventHandler RaiseWebSocketConnectedEvent; + public event WebSocketClientDisconnectEventHandler RaiseWebSocketClientDisconnectEvent; #endregion diff --git a/AdamController.Services/PythonRemoteRunnerService.cs b/AdamController.Services/PythonRemoteRunnerService.cs index 5839d99..8e91789 100644 --- a/AdamController.Services/PythonRemoteRunnerService.cs +++ b/AdamController.Services/PythonRemoteRunnerService.cs @@ -7,9 +7,9 @@ public class PythonRemoteRunnerService : IPythonRemoteRunnerService { #region Events - public event PythonStandartOutput RaisePythonStandartOutput; - public event PythonScriptExecuteStart RaisePythonScriptExecuteStart; - public event PythonScriptExecuteFinish RaisePythonScriptExecuteFinish; + public event PythonStandartOutputEventHandler RaisePythonStandartOutputEvent; + public event PythonScriptExecuteStartEventHandler RaisePythonScriptExecuteStartEvent; + public event PythonScriptExecuteFinishEventHandler RaisePythonScriptExecuteFinishEvent; #endregion @@ -54,7 +54,7 @@ private void MessageParser(string message) switch (message) { case cStartMessage: - OnRaisePythonScriptExecuteStart(); + OnRaisePythonScriptExecuteStartEvent(); break; case cErrorMessage: @@ -64,13 +64,13 @@ private void MessageParser(string message) { var cleanMessage = message.Remove(0, 6); var finishMessage = ParseFinishExecuteMessage(cleanMessage); - OnRaisePythonScriptExecuteFinish(finishMessage); + OnRaisePythonScriptExecuteFinishEvent(finishMessage); break; } default: { - OnRaisePythonStandartOutput($"{message}\n"); + OnRaisePythonStandartOutputEvent($"{message}\n"); break; } } @@ -109,13 +109,13 @@ private static string ParseFinishExecuteMessage(string resultJson = null) private void Subscribe() { - mCommunicationProvider.RaiseUdpServiceClientReceived += RaiseUdpClientReceived; + mCommunicationProvider.RaiseUdpServiceClientReceivedEvent += RaiseUdpClientReceived; } private void Unsubscribe() { - mCommunicationProvider.RaiseUdpServiceClientReceived -= RaiseUdpClientReceived; + mCommunicationProvider.RaiseUdpServiceClientReceivedEvent -= RaiseUdpClientReceived; } @@ -132,21 +132,21 @@ private void RaiseUdpClientReceived(object sender, string message) #region OnRaise events - protected virtual void OnRaisePythonStandartOutput(string message) + protected virtual void OnRaisePythonStandartOutputEvent(string message) { - PythonStandartOutput raiseEvent = RaisePythonStandartOutput; + PythonStandartOutputEventHandler raiseEvent = RaisePythonStandartOutputEvent; raiseEvent?.Invoke(this, message); } - protected virtual void OnRaisePythonScriptExecuteStart() + protected virtual void OnRaisePythonScriptExecuteStartEvent() { - PythonScriptExecuteStart raiseEvent = RaisePythonScriptExecuteStart; + PythonScriptExecuteStartEventHandler raiseEvent = RaisePythonScriptExecuteStartEvent; raiseEvent?.Invoke(this); } - protected virtual void OnRaisePythonScriptExecuteFinish(string message) + protected virtual void OnRaisePythonScriptExecuteFinishEvent(string message) { - PythonScriptExecuteFinish raiseEvent = RaisePythonScriptExecuteFinish; + PythonScriptExecuteFinishEventHandler raiseEvent = RaisePythonScriptExecuteFinishEvent; raiseEvent?.Invoke(this, message); } diff --git a/AdamController.Services/TcpClientService.cs b/AdamController.Services/TcpClientService.cs index b93cb0c..db0e575 100644 --- a/AdamController.Services/TcpClientService.cs +++ b/AdamController.Services/TcpClientService.cs @@ -11,12 +11,12 @@ public class TcpClientService : NetCoreServer.TcpClient, ITcpClientService { #region Events - public event TcpCientConnected RaiseTcpCientConnected; - public event TcpCientSent RaiseTcpCientSent; - public event TcpClientDisconnect RaiseTcpClientDisconnected; - public event TcpClientError RaiseTcpClientError; - public event TcpClientReceived RaiseTcpClientReceived; - public event TcpClientReconnected RaiseTcpClientReconnected; + public event TcpCientConnectedEventHandler RaiseTcpCientConnectedEvent; + public event TcpCientSentEventHandler RaiseTcpCientSentEvent; + public event TcpClientDisconnectEventHandler RaiseTcpClientDisconnectedEvent; + public event TcpClientErrorEventHandler RaiseTcpClientErrorEvent; + public event TcpClientReceivedEventHandler RaiseTcpClientReceivedEvent; + public event TcpClientReconnectedEventHandler RaiseTcpClientReconnectedEvent; #endregion @@ -103,7 +103,7 @@ protected override void OnDisconnected() if (!mDisconnectAlreadyInvoke) { mDisconnectAlreadyInvoke = true; - OnRaiseTcpClientDisconnected(); + OnRaiseTcpClientDisconnectedEvent(); } return; @@ -116,7 +116,7 @@ protected override void OnDisconnected() if (!mDisconnectAlreadyInvoke) { mDisconnectAlreadyInvoke = true; - OnRaiseTcpClientDisconnected(); + OnRaiseTcpClientDisconnectedEvent(); } RenewVariable(true); @@ -135,7 +135,7 @@ private void Reconnect(CancellationTokenSource tokenSource) { if (!tokenSource.IsCancellationRequested) { - OnRaiseTcpClientReconnected(mReconnectCount--); + OnRaiseTcpClientReconnectedEvent(mReconnectCount--); _ = tokenSource.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(mReconnectTimeout)); _ = ConnectAsync(); @@ -148,7 +148,7 @@ private void Reconnect(CancellationTokenSource tokenSource) protected override void OnConnected() { - OnRaiseTcpCientConnected(); + OnRaiseTcpCientConnectedEvent(); RenewVariable(false); base.OnConnected(); @@ -156,56 +156,56 @@ protected override void OnConnected() protected override void OnSent(long sent, long pending) { - OnRaiseTcpCientSent(sent, pending); + OnRaiseTcpCientSentEvent(sent, pending); } protected override void OnError(SocketError error) { - OnRaiseTcpClientError(error); + OnRaiseTcpClientErrorEvent(error); } protected override void OnReceived(byte[] buffer, long offset, long size) { - OnRaiseTcpClientReceived(buffer, offset, size); + OnRaiseTcpClientReceivedEvent(buffer, offset, size); } #endregion #region OnRaiseEvents - protected virtual void OnRaiseTcpCientConnected() + protected virtual void OnRaiseTcpCientConnectedEvent() { - TcpCientConnected raiseEvent = RaiseTcpCientConnected; + TcpCientConnectedEventHandler raiseEvent = RaiseTcpCientConnectedEvent; raiseEvent?.Invoke(this); } - protected virtual void OnRaiseTcpCientSent(long sent, long pending) + protected virtual void OnRaiseTcpCientSentEvent(long sent, long pending) { - TcpCientSent raiseEvent = RaiseTcpCientSent; + TcpCientSentEventHandler raiseEvent = RaiseTcpCientSentEvent; raiseEvent?.Invoke(this, sent, pending); } - protected virtual void OnRaiseTcpClientDisconnected() + protected virtual void OnRaiseTcpClientDisconnectedEvent() { - TcpClientDisconnect raiseEvent = RaiseTcpClientDisconnected; + TcpClientDisconnectEventHandler raiseEvent = RaiseTcpClientDisconnectedEvent; raiseEvent?.Invoke(this); } - protected virtual void OnRaiseTcpClientError(SocketError socketError) + protected virtual void OnRaiseTcpClientErrorEvent(SocketError socketError) { - TcpClientError raiseEvent = RaiseTcpClientError; + TcpClientErrorEventHandler raiseEvent = RaiseTcpClientErrorEvent; raiseEvent?.Invoke(this, socketError); } - protected virtual void OnRaiseTcpClientReceived(byte[] buffer, long offset, long size) + protected virtual void OnRaiseTcpClientReceivedEvent(byte[] buffer, long offset, long size) { - TcpClientReceived raiseEvent = RaiseTcpClientReceived; + TcpClientReceivedEventHandler raiseEvent = RaiseTcpClientReceivedEvent; raiseEvent?.Invoke(this, buffer, offset, size); } - protected virtual void OnRaiseTcpClientReconnected(int reconnectCount) + protected virtual void OnRaiseTcpClientReconnectedEvent(int reconnectCount) { - TcpClientReconnected raiseEvent = RaiseTcpClientReconnected; + TcpClientReconnectedEventHandler raiseEvent = RaiseTcpClientReconnectedEvent; raiseEvent?.Invoke(this, reconnectCount); } diff --git a/AdamController.Services/UdpClientService.cs b/AdamController.Services/UdpClientService.cs index de10725..3ef1415 100644 --- a/AdamController.Services/UdpClientService.cs +++ b/AdamController.Services/UdpClientService.cs @@ -5,13 +5,13 @@ namespace AdamController.Services { public class UdpClientService : NetCoreServer.UdpServer, IUdpClientService { - public event UdpClientReceived RaiseUdpClientReceived; + public event UdpClientReceivedEventHandler RaiseUdpClientReceivedEvent; public UdpClientService(IPAddress address, int port) : base(address, port) { } protected override void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size) { - OnRaiseUdpClientReceived(endpoint, buffer, offset, size); + OnRaiseUdpClientReceivedEvent(endpoint, buffer, offset, size); ReceiveAsync(); } @@ -27,9 +27,9 @@ protected override void OnStarted() #region OnRaiseEvents - protected virtual void OnRaiseUdpClientReceived(EndPoint endpoint, byte[] buffer, long offset, long size) + protected virtual void OnRaiseUdpClientReceivedEvent(EndPoint endpoint, byte[] buffer, long offset, long size) { - UdpClientReceived raiseEvent = RaiseUdpClientReceived; + UdpClientReceivedEventHandler raiseEvent = RaiseUdpClientReceivedEvent; raiseEvent?.Invoke(this, endpoint, buffer, offset, size); } diff --git a/AdamController.Services/UdpServerService.cs b/AdamController.Services/UdpServerService.cs index 62a9e9f..1a4dceb 100644 --- a/AdamController.Services/UdpServerService.cs +++ b/AdamController.Services/UdpServerService.cs @@ -8,7 +8,7 @@ public class UdpServerService : UdpServer, IUdpServerService { #region Events - public event UdpServerReceived RaiseUdpServerReceived; + public event UdpServerReceivedEventHandler RaiseUdpServerReceivedEvent; #endregion @@ -27,7 +27,7 @@ protected override void OnStarted() protected override void OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size) { - OnRaiseUdpServerReceived(endpoint, buffer, offset, size); + OnRaiseUdpServerReceivedEvent(endpoint, buffer, offset, size); ReceiveAsync(); } @@ -40,9 +40,9 @@ protected override void OnSent(EndPoint endpoint, long sent) #region OnRaiseEvents - protected virtual void OnRaiseUdpServerReceived(EndPoint endpoint, byte[] buffer, long offset, long size) + protected virtual void OnRaiseUdpServerReceivedEvent(EndPoint endpoint, byte[] buffer, long offset, long size) { - UdpServerReceived raiseEvent = RaiseUdpServerReceived; + UdpServerReceivedEventHandler raiseEvent = RaiseUdpServerReceivedEvent; raiseEvent?.Invoke(this, endpoint, buffer, offset, size); } diff --git a/AdamController.Services/WebSocketClientService.cs b/AdamController.Services/WebSocketClientService.cs index ccb7d2d..785e29c 100644 --- a/AdamController.Services/WebSocketClientService.cs +++ b/AdamController.Services/WebSocketClientService.cs @@ -9,9 +9,9 @@ public class WebSocketClientService : IWebSocketClientService { #region Events - public event WebSocketClientReceived RaiseWebSocketClientReceived; - public event WebSocketConnected RaiseWebSocketConnected; - public event WebSocketClientDisconnect RaiseWebSocketClientDisconnect; + public event WebSocketClientReceivedEventHandler RaiseWebSocketClientReceivedEvent; + public event WebSocketConnectedEventHandler RaiseWebSocketConnectedEvent; + public event WebSocketClientDisconnectEventHandler RaiseWebSocketClientDisconnectEvent; #endregion @@ -79,17 +79,17 @@ private void Subscribe() { mWebsocketClient.MessageReceived.Subscribe(message => { - OnRaiseWebSocketClientReceived(message.Text); + OnRaiseWebSocketClientReceivedEvent(message.Text); }); mWebsocketClient.DisconnectionHappened.Subscribe(eventHappened => { - OnRaiseWebSocketClientDisconnect(); + OnRaiseWebSocketClientDisconnectEvent(); }); mWebsocketClient.ReconnectionHappened.Subscribe(eventHappened => { - OnRaiseWebSocketConnected(); + OnRaiseWebSocketConnectedEvent(); }); } @@ -97,21 +97,21 @@ private void Subscribe() #region OnRaiseEvents - protected virtual void OnRaiseWebSocketClientReceived(string text) + protected virtual void OnRaiseWebSocketClientReceivedEvent(string text) { - WebSocketClientReceived raiseEvent = RaiseWebSocketClientReceived; + WebSocketClientReceivedEventHandler raiseEvent = RaiseWebSocketClientReceivedEvent; raiseEvent?.Invoke(this, text); } - protected virtual void OnRaiseWebSocketConnected() + protected virtual void OnRaiseWebSocketConnectedEvent() { - WebSocketConnected raiseEvent = RaiseWebSocketConnected; + WebSocketConnectedEventHandler raiseEvent = RaiseWebSocketConnectedEvent; raiseEvent?.Invoke(this); } - protected virtual void OnRaiseWebSocketClientDisconnect() + protected virtual void OnRaiseWebSocketClientDisconnectEvent() { - WebSocketClientDisconnect raiseEvent = RaiseWebSocketClientDisconnect; + WebSocketClientDisconnectEventHandler raiseEvent = RaiseWebSocketClientDisconnectEvent; raiseEvent?.Invoke(this); } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index 2807d94..946d667 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -66,24 +66,24 @@ public override void ConfirmNavigationRequest(NavigationContext navigationContex public override void OnNavigatedTo(NavigationContext navigationContext) { - mCommunicationProvider.RaiseTcpServiceCientConnected += OnRaiseTcpServiceCientConnected; - mCommunicationProvider.RaiseTcpServiceClientDisconnect += OnRaiseTcperviceClientDisconnect; + mCommunicationProvider.RaiseTcpServiceCientConnectedEvent += OnRaiseTcpServiceCientConnected; + mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent += OnRaiseTcperviceClientDisconnect; - mPythonRemoteRunner.RaisePythonScriptExecuteStart += OnRaisePythonScriptExecuteStart; - mPythonRemoteRunner.RaisePythonStandartOutput += OnRaisePythonStandartOutput; - mPythonRemoteRunner.RaisePythonScriptExecuteFinish += OnRaisePythonScriptExecuteFinish; + mPythonRemoteRunner.RaisePythonScriptExecuteStartEvent += OnRaisePythonScriptExecuteStart; + mPythonRemoteRunner.RaisePythonStandartOutputEvent += OnRaisePythonStandartOutput; + mPythonRemoteRunner.RaisePythonScriptExecuteFinishEvent += OnRaisePythonScriptExecuteFinish; base.OnNavigatedTo(navigationContext); } public override void OnNavigatedFrom(NavigationContext navigationContext) { - mCommunicationProvider.RaiseTcpServiceCientConnected -= OnRaiseTcpServiceCientConnected; - mCommunicationProvider.RaiseTcpServiceClientDisconnect -= OnRaiseTcperviceClientDisconnect; + mCommunicationProvider.RaiseTcpServiceCientConnectedEvent -= OnRaiseTcpServiceCientConnected; + mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent -= OnRaiseTcperviceClientDisconnect; - mPythonRemoteRunner.RaisePythonScriptExecuteStart -= OnRaisePythonScriptExecuteStart; - mPythonRemoteRunner.RaisePythonStandartOutput -= OnRaisePythonStandartOutput; - mPythonRemoteRunner.RaisePythonScriptExecuteFinish -= OnRaisePythonScriptExecuteFinish; + mPythonRemoteRunner.RaisePythonScriptExecuteStartEvent -= OnRaisePythonScriptExecuteStart; + mPythonRemoteRunner.RaisePythonStandartOutputEvent -= OnRaisePythonStandartOutput; + mPythonRemoteRunner.RaisePythonScriptExecuteFinishEvent -= OnRaisePythonScriptExecuteFinish; base.OnNavigatedFrom(navigationContext); } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs index bf69492..a2374e3 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs @@ -48,18 +48,18 @@ public override void ConfirmNavigationRequest(NavigationContext navigationContex public override void OnNavigatedTo(NavigationContext navigationContext) { - mPythonRemoteRunner.RaisePythonScriptExecuteStart += OnRaisePythonScriptExecuteStart; - mPythonRemoteRunner.RaisePythonStandartOutput += OnRaisePythonStandartOutput; - mPythonRemoteRunner.RaisePythonScriptExecuteFinish += OnRaisePythonScriptExecuteFinish; + mPythonRemoteRunner.RaisePythonScriptExecuteStartEvent += OnRaisePythonScriptExecuteStart; + mPythonRemoteRunner.RaisePythonStandartOutputEvent += OnRaisePythonStandartOutput; + mPythonRemoteRunner.RaisePythonScriptExecuteFinishEvent += OnRaisePythonScriptExecuteFinish; base.OnNavigatedTo(navigationContext); } public override void OnNavigatedFrom(NavigationContext navigationContext) { - mPythonRemoteRunner.RaisePythonScriptExecuteStart -= OnRaisePythonScriptExecuteStart; - mPythonRemoteRunner.RaisePythonStandartOutput -= OnRaisePythonStandartOutput; - mPythonRemoteRunner.RaisePythonScriptExecuteFinish -= OnRaisePythonScriptExecuteFinish; + mPythonRemoteRunner.RaisePythonScriptExecuteStartEvent -= OnRaisePythonScriptExecuteStart; + mPythonRemoteRunner.RaisePythonStandartOutputEvent -= OnRaisePythonStandartOutput; + mPythonRemoteRunner.RaisePythonScriptExecuteFinishEvent -= OnRaisePythonScriptExecuteFinish; base.OnNavigatedFrom(navigationContext); } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index 634d5ad..419d22b 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -115,17 +115,17 @@ private void SetStatusConnection(bool connectionStatus) private void Subscribe() { - mCommunicationProvider.RaiseTcpServiceCientConnected += OnRaiseTcpServiceCientConnected; - mCommunicationProvider.RaiseTcpServiceClientReconnected += OnRaiseTcpServiceClientReconnected; - mCommunicationProvider.RaiseTcpServiceClientDisconnect += OnRaiseTcpServiceClientDisconnect; + mCommunicationProvider.RaiseTcpServiceCientConnectedEvent += OnRaiseTcpServiceCientConnected; + mCommunicationProvider.RaiseTcpServiceClientReconnectedEvent += OnRaiseTcpServiceClientReconnected; + mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent += OnRaiseTcpServiceClientDisconnect; } private void Unsubscribe() { - mCommunicationProvider.RaiseTcpServiceCientConnected -= OnRaiseTcpServiceCientConnected; - mCommunicationProvider.RaiseTcpServiceClientReconnected -= OnRaiseTcpServiceClientReconnected; - mCommunicationProvider.RaiseTcpServiceClientDisconnect -= OnRaiseTcpServiceClientDisconnect; + mCommunicationProvider.RaiseTcpServiceCientConnectedEvent -= OnRaiseTcpServiceCientConnected; + mCommunicationProvider.RaiseTcpServiceClientReconnectedEvent -= OnRaiseTcpServiceClientReconnected; + mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent -= OnRaiseTcpServiceClientDisconnect; } #endregion diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index abd93b1..655655d 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -154,8 +154,8 @@ private void Subscribe() //ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; //ComunicateHelper.OnAdamTcpReconnected += OnTcpReconnected; - mCommunicationProviderService.RaiseTcpServiceCientConnected += RaiseAdamTcpCientConnected; - mCommunicationProviderService.RaiseTcpServiceClientDisconnect += RaiseAdamTcpClientDisconnect; + mCommunicationProviderService.RaiseTcpServiceCientConnectedEvent += RaiseAdamTcpCientConnected; + mCommunicationProviderService.RaiseTcpServiceClientDisconnectEvent += RaiseAdamTcpClientDisconnect; mStatusBarNotificationDelivery.RaiseChangeProgressRingStateEvent += RaiseChangeProgressRingStateEvent; mStatusBarNotificationDelivery.RaiseNewCompileLogMessageEvent += RaiseNewCompileLogMessageEvent; @@ -167,8 +167,8 @@ private void Subscribe() private void Unsubscribe() { - mCommunicationProviderService.RaiseTcpServiceCientConnected -= RaiseAdamTcpCientConnected; - mCommunicationProviderService.RaiseTcpServiceClientDisconnect -= RaiseAdamTcpClientDisconnect; + mCommunicationProviderService.RaiseTcpServiceCientConnectedEvent -= RaiseAdamTcpCientConnected; + mCommunicationProviderService.RaiseTcpServiceClientDisconnectEvent -= RaiseAdamTcpClientDisconnect; mStatusBarNotificationDelivery.RaiseChangeProgressRingStateEvent -= RaiseChangeProgressRingStateEvent; From 1cf87aaa1c02b9110cc4e1965376652231c64673 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 14 Apr 2024 08:43:49 +1000 Subject: [PATCH 087/181] Prepare works #16 --- .../IStatusBarNotificationDeliveryService.cs | 3 ++ .../StatusBarNotificationDeliveryService.cs | 20 +++++++++++ .../ViewModels/NotificationViewModel.cs | 36 ++++++++++++------- .../ViewModels/StatusBarViewModel.cs | 7 ++-- 4 files changed, 52 insertions(+), 14 deletions(-) diff --git a/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs b/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs index 5438e96..8ccb8fd 100644 --- a/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs +++ b/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs @@ -8,6 +8,7 @@ namespace AdamController.Services.Interfaces public delegate void NewCompileLogMessageEventHandler(object sender, string message); public delegate void NewAppLogMessageEventHandler(object sender, string message); public delegate void NewNotificationBadgeMessageEventHandler(object sender, string message); + public delegate void UpdateNotificationCounterEventHandler(object sender, int counter); #endregion @@ -19,6 +20,7 @@ public interface IStatusBarNotificationDeliveryService : IDisposable public event NewCompileLogMessageEventHandler RaiseNewCompileLogMessageEvent; public event NewAppLogMessageEventHandler RaiseNewAppLogMessageEvent; public event NewNotificationBadgeMessageEventHandler RaiseNewNotificationBadgeMessageEvent; + public event UpdateNotificationCounterEventHandler RaiseUpdateNotificationCounterEvent; #endregion @@ -28,6 +30,7 @@ public interface IStatusBarNotificationDeliveryService : IDisposable public string CompileLogMessage { get; set; } public string AppLogMessage { get; set; } public string NotificationBadgeMessage { get; set; } + public int NotificationCounter { get; set; } #endregion } diff --git a/AdamController.Services/StatusBarNotificationDeliveryService.cs b/AdamController.Services/StatusBarNotificationDeliveryService.cs index 2a35ec7..7c2f305 100644 --- a/AdamController.Services/StatusBarNotificationDeliveryService.cs +++ b/AdamController.Services/StatusBarNotificationDeliveryService.cs @@ -13,6 +13,7 @@ public class StatusBarNotificationDeliveryService : BindableBase, IStatusBarNoti public event NewCompileLogMessageEventHandler RaiseNewCompileLogMessageEvent; public event NewAppLogMessageEventHandler RaiseNewAppLogMessageEvent; public event NewNotificationBadgeMessageEventHandler RaiseNewNotificationBadgeMessageEvent; + public event UpdateNotificationCounterEventHandler RaiseUpdateNotificationCounterEvent; #endregion @@ -77,6 +78,19 @@ public string NotificationBadgeMessage } } + private int notificationCounter; + public int NotificationCounter + { + get => notificationCounter; + set + { + bool isNewValue = SetProperty(ref notificationCounter, value); + + if (isNewValue) + OnRaiseUpdateNotificationCounterEvent(NotificationCounter); + } + } + public void Dispose() { @@ -111,6 +125,12 @@ protected virtual void OnRaiseNewNotificationBadgeMessageEvent(string message) raiseEvent?.Invoke(this, message); } + protected virtual void OnRaiseUpdateNotificationCounterEvent(int counter) + { + UpdateNotificationCounterEventHandler raiseEvent = RaiseUpdateNotificationCounterEvent; + raiseEvent?.Invoke(this, counter); + } + #endregion } } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index 419d22b..ded8315 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -1,13 +1,11 @@ using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; -using AdamController.Core.Helpers; using AdamController.Core.Properties; +using AdamController.Services; using AdamController.Services.Interfaces; using AdamController.WebApi.Client.v1; using MahApps.Metro.IconPacks; using Prism.Commands; -using System; using System.Windows; -using System.Windows.Threading; namespace AdamController.Modules.FlayoutsRegion.ViewModels { @@ -23,6 +21,7 @@ public class NotificationViewModel : FlyoutBase #region Services private readonly ICommunicationProviderService mCommunicationProvider; + private readonly IStatusBarNotificationDeliveryService mStatusBarNotificationDeliveryService; #endregion @@ -36,14 +35,18 @@ public class NotificationViewModel : FlyoutBase #region ~ - public NotificationViewModel(ICommunicationProviderService communicationProvider) + public NotificationViewModel(ICommunicationProviderService communicationProvider, IStatusBarNotificationDeliveryService statusBarNotificationDelivery) { SetFlyoutParametrs(); + mCommunicationProvider = communicationProvider; + mStatusBarNotificationDeliveryService = statusBarNotificationDelivery; ConnectButtonComand = new (ConnectButton, ConnectButtonCanExecute); ClearNotificationsCommand = new DelegateCommand(ClearNotifications, ClearNotificationsCanExecute); + + Subscribe(); } #endregion @@ -60,12 +63,14 @@ protected override void OnChanging(bool isOpening) } - if (!isOpening) - Unsubscribe(); + //if (!isOpening) + //Unsubscribe(); base.OnChanging(isOpening); } + + #endregion #region Private methods @@ -95,10 +100,13 @@ private void SetStatusConnection(bool connectionStatus) if(!connectionStatus) { //если центр уведомлений закрыт, обновляем счетчик уведомлений - if (!IsOpen && Settings.Default.IsMessageShowOnAbortMainConnection) + if (Settings.Default.IsMessageShowOnAbortMainConnection) { - //BadgeCounter++; - FailConnectMessageVisibility = Visibility.Visible; + mStatusBarNotificationDeliveryService.NotificationCounter++; + + if (!IsOpen) + FailConnectMessageVisibility = Visibility.Visible; + } TextOnConnectFlayotButton = cConnectButtonStatusDisconnected; @@ -139,18 +147,19 @@ private void OnRaiseTcpServiceCientConnected(object sender) private void OnRaiseTcpServiceClientReconnected(object sender, int reconnectCounter) { - TextOnConnectFlayotButton = $"{cConnectButtonStatusReconnected} {reconnectCount}"; + mStatusBarNotificationDeliveryService.NotificationCounter = reconnectCounter; + TextOnConnectFlayotButton = $"{cConnectButtonStatusReconnected} {reconnectCounter}"; //TextOnStatusConnectToolbar = $"{mToolbarStatusClientReconnected} {reconnectCount}"; //ConnectIcon = PackIconModernKind.TransitConnectionDeparture; IconOnConnectFlayoutButton = PackIconMaterialKind.RobotConfused; } - private int reconnectCount = 0; + //private int reconnectCount = 0; private void OnRaiseTcpServiceClientDisconnect(object sender) { - SetStatusConnection(false); + SetStatusConnection(false); } #endregion @@ -190,7 +199,10 @@ private bool ConnectButtonCanExecute() /* #16 */ private void ClearNotifications() { + //BadgeCounter = 0; + mStatusBarNotificationDeliveryService.NotificationCounter = 0; + FailConnectMessageVisibility = Visibility.Collapsed; } diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index 655655d..a911668 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -161,10 +161,9 @@ private void Subscribe() mStatusBarNotificationDelivery.RaiseNewCompileLogMessageEvent += RaiseNewCompileLogMessageEvent; mStatusBarNotificationDelivery.RaiseNewAppLogMessageEvent += RaiseNewAppLogMessageEvent; mStatusBarNotificationDelivery.RaiseNewNotificationBadgeMessageEvent += RaiseNewNotificationBadgeMessageEvent; + mStatusBarNotificationDelivery.RaiseUpdateNotificationCounterEvent += RaiseUpdateNotificationCounterEvent; } - - private void Unsubscribe() { mCommunicationProviderService.RaiseTcpServiceCientConnectedEvent -= RaiseAdamTcpCientConnected; @@ -213,6 +212,10 @@ private void RaiseNewNotificationBadgeMessageEvent(object sender, string message NotificationBadge = message; } + private void RaiseUpdateNotificationCounterEvent(object sender, int counter) + { + BadgeCounter = counter; + } #endregion From 11edcad5feba7f85ceecc49ebe338ce65fa84050 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 14 Apr 2024 13:50:32 +1000 Subject: [PATCH 088/181] Prepare works #16 --- .../IStatusBarNotificationDeliveryService.cs | 11 +- .../StatusBarNotificationDeliveryService.cs | 32 +-- .../ViewModels/MainWindowViewModel.cs | 20 +- .../ViewModels/NotificationViewModel.cs | 253 ++++++------------ .../Views/NotificationView.xaml | 19 +- .../ViewModels/StatusBarViewModel.cs | 58 ++-- 6 files changed, 155 insertions(+), 238 deletions(-) diff --git a/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs b/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs index 8ccb8fd..62cb2dc 100644 --- a/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs +++ b/AdamController.Services/Interfaces/IStatusBarNotificationDeliveryService.cs @@ -7,7 +7,6 @@ namespace AdamController.Services.Interfaces public delegate void ChangeProgressRingStateEventHandler(object sender, bool newState); public delegate void NewCompileLogMessageEventHandler(object sender, string message); public delegate void NewAppLogMessageEventHandler(object sender, string message); - public delegate void NewNotificationBadgeMessageEventHandler(object sender, string message); public delegate void UpdateNotificationCounterEventHandler(object sender, int counter); #endregion @@ -19,19 +18,23 @@ public interface IStatusBarNotificationDeliveryService : IDisposable public event ChangeProgressRingStateEventHandler RaiseChangeProgressRingStateEvent; public event NewCompileLogMessageEventHandler RaiseNewCompileLogMessageEvent; public event NewAppLogMessageEventHandler RaiseNewAppLogMessageEvent; - public event NewNotificationBadgeMessageEventHandler RaiseNewNotificationBadgeMessageEvent; public event UpdateNotificationCounterEventHandler RaiseUpdateNotificationCounterEvent; #endregion - #region Public methods + #region Public fields public bool ProgressRingStart { get; set; } public string CompileLogMessage { get; set; } public string AppLogMessage { get; set; } - public string NotificationBadgeMessage { get; set; } public int NotificationCounter { get; set; } #endregion + + #region Public fields + + public void ResetNotificationCounter(); + + #endregion } } diff --git a/AdamController.Services/StatusBarNotificationDeliveryService.cs b/AdamController.Services/StatusBarNotificationDeliveryService.cs index 7c2f305..9931092 100644 --- a/AdamController.Services/StatusBarNotificationDeliveryService.cs +++ b/AdamController.Services/StatusBarNotificationDeliveryService.cs @@ -12,7 +12,6 @@ public class StatusBarNotificationDeliveryService : BindableBase, IStatusBarNoti public event ChangeProgressRingStateEventHandler RaiseChangeProgressRingStateEvent; public event NewCompileLogMessageEventHandler RaiseNewCompileLogMessageEvent; public event NewAppLogMessageEventHandler RaiseNewAppLogMessageEvent; - public event NewNotificationBadgeMessageEventHandler RaiseNewNotificationBadgeMessageEvent; public event UpdateNotificationCounterEventHandler RaiseUpdateNotificationCounterEvent; #endregion @@ -65,19 +64,6 @@ public string AppLogMessage } } - private string notificationBadgeMessage = string.Empty; - public string NotificationBadgeMessage - { - get => notificationBadgeMessage; - set - { - bool isNewValue = SetProperty(ref notificationBadgeMessage, value); - - if (isNewValue) - OnRaiseNewNotificationBadgeMessageEvent(NotificationBadgeMessage); - } - } - private int notificationCounter; public int NotificationCounter { @@ -91,14 +77,22 @@ public int NotificationCounter } } + #endregion + + #region Public methode + + public void ResetNotificationCounter() + { + NotificationCounter = 0; + } + public void Dispose() { - + } #endregion - #region OnRaise methods protected virtual void OnRaiseChangeProgressRingStateEvent(bool newState) @@ -119,12 +113,6 @@ protected virtual void OnRaiseNewAppLogMessageEvent(string message) raiseEvent?.Invoke(this, message); } - protected virtual void OnRaiseNewNotificationBadgeMessageEvent(string message) - { - NewNotificationBadgeMessageEventHandler raiseEvent = RaiseNewNotificationBadgeMessageEvent; - raiseEvent?.Invoke(this, message); - } - protected virtual void OnRaiseUpdateNotificationCounterEvent(int counter) { UpdateNotificationCounterEventHandler raiseEvent = RaiseUpdateNotificationCounterEvent; diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index c728986..0a21b85 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -1,9 +1,8 @@ using AdamController.Core; using AdamController.Core.Mvvm; using AdamController.Services.Interfaces; -using DryIoc; +using AdamController.WebApi.Client.v1; using Prism.Commands; -using Prism.Mvvm; using Prism.Regions; using System.Reflection; using System.Windows; @@ -23,17 +22,20 @@ public class MainWindowViewModel : ViewModelBase public IRegionManager RegionManager { get; } private readonly ISubRegionChangeAwareService mSubRegionChangeAwareService; private readonly IStatusBarNotificationDeliveryService mStatusBarNotification; + private readonly ICommunicationProviderService mCommunicationProviderService; #endregion #region ~ - public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService, IStatusBarNotificationDeliveryService statusBarNotification) + public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService, + IStatusBarNotificationDeliveryService statusBarNotification, ICommunicationProviderService communicationProviderService) { RegionManager = regionManager; mSubRegionChangeAwareService = subRegionChangeAwareService; mStatusBarNotification = statusBarNotification; + mCommunicationProviderService = communicationProviderService; ShowRegionCommand = new DelegateCommand(ShowRegion); Subscribe(); @@ -125,6 +127,7 @@ private void ShowRegion(string subRegionName) private void Subscribe() { mSubRegionChangeAwareService.RaiseSubRegionChangeEvent += RaiseSubRegionChangeEvent; + mCommunicationProviderService.RaiseTcpServiceCientConnectedEvent += RaiseTcpServiceCientConnectedEvent; Application.Current.MainWindow.Loaded += MainWindowLoaded; } @@ -134,6 +137,7 @@ private void Subscribe() private void Unsubscribe() { mSubRegionChangeAwareService.RaiseSubRegionChangeEvent -= RaiseSubRegionChangeEvent; + mCommunicationProviderService.RaiseTcpServiceCientConnectedEvent -= RaiseTcpServiceCientConnectedEvent; Application.Current.MainWindow.Loaded -= MainWindowLoaded; } @@ -161,6 +165,16 @@ private void RaiseSubRegionChangeEvent(object sender) ChangeSelectedIndexByRegionName(changeRegionName); } + /// + /// It is not clear where to put this, so it will not get lost here. + /// + /// Stops a remotely executed script that may have been executing before the connection was lost. + /// + private void RaiseTcpServiceCientConnectedEvent(object sender) + { + _ = BaseApi.StopPythonExecute(); + } + #endregion } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index ded8315..83d44fe 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -1,6 +1,5 @@ using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; using AdamController.Core.Properties; -using AdamController.Services; using AdamController.Services.Interfaces; using AdamController.WebApi.Client.v1; using MahApps.Metro.IconPacks; @@ -13,8 +12,8 @@ public class NotificationViewModel : FlyoutBase { #region DelegateCommands - public DelegateCommand ConnectButtonComand { get; } - public DelegateCommand ClearNotificationsCommand { get; } + public DelegateCommand ConnectButtonDelegateCommand { get; } + public DelegateCommand ResetNotificationsDelegateCommand { get; } #endregion @@ -39,14 +38,11 @@ public NotificationViewModel(ICommunicationProviderService communicationProvider { SetFlyoutParametrs(); - mCommunicationProvider = communicationProvider; mStatusBarNotificationDeliveryService = statusBarNotificationDelivery; - ConnectButtonComand = new (ConnectButton, ConnectButtonCanExecute); - ClearNotificationsCommand = new DelegateCommand(ClearNotifications, ClearNotificationsCanExecute); - - Subscribe(); + ConnectButtonDelegateCommand = new (ConnectButton, ConnectButtonCanExecute); + ResetNotificationsDelegateCommand = new (ResetNotifications, ResetNotificationsCanExecute); } #endregion @@ -55,7 +51,7 @@ public NotificationViewModel(ICommunicationProviderService communicationProvider protected override void OnChanging(bool isOpening) { - //need update status bar on opening + if (isOpening) { Subscribe(); @@ -63,13 +59,65 @@ protected override void OnChanging(bool isOpening) } - //if (!isOpening) - //Unsubscribe(); + if (!isOpening) + Unsubscribe(); base.OnChanging(isOpening); } - + + + #endregion + + #region Public field + + private Visibility noNewNotificationMessageVisibility = Visibility.Visible; + public Visibility NoNewNotificationMessageVisibility + { + get => noNewNotificationMessageVisibility; + set => SetProperty(ref noNewNotificationMessageVisibility, value); + } + + private Visibility failConnectNotificationVisibility = Visibility.Collapsed; + public Visibility FailConnectNotificationVisibility + { + get => failConnectNotificationVisibility; + set + { + bool isNewValue = SetProperty(ref failConnectNotificationVisibility, value); + + if (isNewValue) + { + if (FailConnectNotificationVisibility == Visibility.Visible) + NoNewNotificationMessageVisibility = Visibility.Collapsed; + + if (FailConnectNotificationVisibility == Visibility.Collapsed) + NoNewNotificationMessageVisibility = Visibility.Visible; + } + } + } + + private double notificationOpacity = Settings.Default.NotificationOpacity; + public double NotificationOpacity + { + get => notificationOpacity; + set => SetProperty(ref notificationOpacity, value); + } + + private string contentConnectButton = cConnectButtonStatusDisconnected; + public string ContentConnectButton + { + get => contentConnectButton; + set => SetProperty(ref contentConnectButton, value); + } + + private PackIconMaterialKind iconConnectButton = PackIconMaterialKind.Robot; + public PackIconMaterialKind IconConnectButton + { + get => iconConnectButton; + set => SetProperty(ref iconConnectButton, value); + + } #endregion @@ -82,38 +130,35 @@ private void SetFlyoutParametrs() IsModal = false; } - private void SetStatusConnection(bool connectionStatus) + /// + /// + /// + /// true is connected, false disconetcted, null reconected + /// + private void SetStatusConnection(bool? connectionStatus, int reconnectCounter = 0) { - if (connectionStatus) + if (connectionStatus == true) { - // это должно быть не здесь - _ = BaseApi.StopPythonExecute(); - - TextOnConnectFlayotButton = cConnectButtonStatusConnected; - //TextOnStatusConnectToolbar = mToolbarStatusClientConnected; - - //ConnectIcon = PackIconModernKind.Disconnect; - IconOnConnectFlayoutButton = PackIconMaterialKind.Robot; - //throw new NotImplementedException(); + ContentConnectButton = cConnectButtonStatusConnected; + IconConnectButton = PackIconMaterialKind.Robot; } - if(!connectionStatus) + if(connectionStatus == false) { - //если центр уведомлений закрыт, обновляем счетчик уведомлений if (Settings.Default.IsMessageShowOnAbortMainConnection) { - mStatusBarNotificationDeliveryService.NotificationCounter++; - if (!IsOpen) - FailConnectMessageVisibility = Visibility.Visible; - + FailConnectNotificationVisibility = Visibility.Visible; } - TextOnConnectFlayotButton = cConnectButtonStatusDisconnected; - //TextOnStatusConnectToolbar = mToolbarStatusClientDisconnected; + ContentConnectButton = cConnectButtonStatusDisconnected; + IconConnectButton = PackIconMaterialKind.RobotDead; + } - //ConnectIcon = PackIconModernKind.Connect; - IconOnConnectFlayoutButton = PackIconMaterialKind.RobotDead; + if(connectionStatus == null) + { + ContentConnectButton = $"{cConnectButtonStatusReconnected} {reconnectCounter}"; + IconConnectButton = PackIconMaterialKind.RobotConfused; } } @@ -125,8 +170,7 @@ private void Subscribe() { mCommunicationProvider.RaiseTcpServiceCientConnectedEvent += OnRaiseTcpServiceCientConnected; mCommunicationProvider.RaiseTcpServiceClientReconnectedEvent += OnRaiseTcpServiceClientReconnected; - mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent += OnRaiseTcpServiceClientDisconnect; - + mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent += OnRaiseTcpServiceClientDisconnect; } private void Unsubscribe() @@ -147,16 +191,9 @@ private void OnRaiseTcpServiceCientConnected(object sender) private void OnRaiseTcpServiceClientReconnected(object sender, int reconnectCounter) { - mStatusBarNotificationDeliveryService.NotificationCounter = reconnectCounter; - TextOnConnectFlayotButton = $"{cConnectButtonStatusReconnected} {reconnectCounter}"; - //TextOnStatusConnectToolbar = $"{mToolbarStatusClientReconnected} {reconnectCount}"; - - //ConnectIcon = PackIconModernKind.TransitConnectionDeparture; - IconOnConnectFlayoutButton = PackIconMaterialKind.RobotConfused; + SetStatusConnection(null, reconnectCounter); } - //private int reconnectCount = 0; - private void OnRaiseTcpServiceClientDisconnect(object sender) { SetStatusConnection(false); @@ -168,27 +205,11 @@ private void OnRaiseTcpServiceClientDisconnect(object sender) private void ConnectButton() { - //bool isNotifyButton = false; //(string)obj == "IsNotificationButtonCalling"; - - //if (isNotifyButton) - //{ - //ClearNotifications(); - //NotificationFlayoutsIsOpen = false; - //} - - //await Dispatcher.Yield(DispatcherPriority.Normal); - if (mCommunicationProvider.IsTcpClientConnected) - { mCommunicationProvider.DisconnectAllAsync(); - //return; - } - + if (!mCommunicationProvider.IsTcpClientConnected) - { mCommunicationProvider.ConnectAllAsync(); - //return; - } } private bool ConnectButtonCanExecute() @@ -196,122 +217,18 @@ private bool ConnectButtonCanExecute() return true; } - /* #16 */ - private void ClearNotifications() + private void ResetNotifications() { - - //BadgeCounter = 0; - mStatusBarNotificationDeliveryService.NotificationCounter = 0; - - FailConnectMessageVisibility = Visibility.Collapsed; + mStatusBarNotificationDeliveryService.ResetNotificationCounter(); + FailConnectNotificationVisibility = Visibility.Collapsed; } - private bool ClearNotificationsCanExecute() + private bool ResetNotificationsCanExecute() { return true; } #endregion - - #region NotificationMessage Visiblity - - private Visibility noNewNotificationMessageVisibility = Visibility.Visible; - public Visibility NoNewNotificationMessageVisibility - { - get => noNewNotificationMessageVisibility; - set => SetProperty(ref noNewNotificationMessageVisibility, value); - } - - private Visibility failConnectMessageVisibility = Visibility.Collapsed; - public Visibility FailConnectMessageVisibility - { - get => failConnectMessageVisibility; - set - { - bool isNewValue = SetProperty(ref failConnectMessageVisibility, value); - - if (isNewValue) - { - if (FailConnectMessageVisibility == Visibility.Visible) - NoNewNotificationMessageVisibility = Visibility.Collapsed; - - if (FailConnectMessageVisibility == Visibility.Collapsed) - NoNewNotificationMessageVisibility = Visibility.Visible; - } - } - } - - #endregion - - #region NotificationOpacity - - private double notificationOpacity = Settings.Default.NotificationOpacity; - public double NotificationOpacity - { - get => notificationOpacity; - set => SetProperty(ref notificationOpacity, value); - } - - #endregion - - #region Connect/Disconnect button (Flayouts) - - private string textOnConnectFlayotButton = cConnectButtonStatusDisconnected; - public string TextOnConnectFlayotButton - { - get => textOnConnectFlayotButton; - set => SetProperty(ref textOnConnectFlayotButton, value); - } - - private PackIconMaterialKind iconOnConnectFlayoutButton = PackIconMaterialKind.Robot; - public PackIconMaterialKind IconOnConnectFlayoutButton - { - get => iconOnConnectFlayoutButton; - set => SetProperty(ref iconOnConnectFlayoutButton, value); - - } - - #endregion - - #region Events TCP/IP clients OLD - - private void OnTcpDisconnected() - { - //если центр уведомлений закрыт, обновляем счетчик уведомлений - //if (!NotificationFlayoutsIsOpen && Settings.Default.IsMessageShowOnAbortMainConnection) - //{ - //BadgeCounter++; - //FailConnectMessageVisibility = Visibility.Visible; - //} - - //TextOnConnectFlayotButton = mConnectButtonStatusDisconnected; - //TextOnStatusConnectToolbar = mToolbarStatusClientDisconnected; - - //ConnectIcon = PackIconModernKind.Connect; - //IconOnConnectFlayoutButton = PackIconMaterialKind.RobotDead; - } - - private void OnTcpConnected() - { - //_ = BaseApi.StopPythonExecute(); - - //TextOnConnectFlayotButton = mConnectButtonStatusConnected; - //TextOnStatusConnectToolbar = mToolbarStatusClientConnected; - - //ConnectIcon = PackIconModernKind.Disconnect; - //IconOnConnectFlayoutButton = PackIconMaterialKind.Robot; - } - - private void OnTcpReconnected(int reconnectCount) - { - //TextOnConnectFlayotButton = $"{mConnectButtonStatusReconnected} {reconnectCount}"; - //TextOnStatusConnectToolbar = $"{mToolbarStatusClientReconnected} {reconnectCount}"; - - //ConnectIcon = PackIconModernKind.TransitConnectionDeparture; - //IconOnConnectFlayoutButton = PackIconMaterialKind.RobotConfused; - } - - #endregion } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml index fcaf446..0ddb305 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml @@ -36,7 +36,7 @@ @@ -90,9 +90,10 @@ VerticalAlignment="Bottom" HorizontalAlignment="Right" FontWeight="Bold"> - - Очистить уведомления - + + + Очистить уведомления + @@ -112,8 +113,8 @@ HorizontalContentAlignment="Center" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" - Command="{Binding ConnectButtonComand}" Background="Transparent" + Command="{Binding ConnectButtonDelegateCommand}" Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}" Style="{StaticResource MahApps.Styles.Button.MetroSquare.Accent}" @@ -123,9 +124,9 @@ + Width="Auto" + Height="Auto" + Kind="{Binding IconConnectButton}" /> diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index a911668..67119c4 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -1,6 +1,7 @@ using AdamController.Controls.CustomControls.Services; using AdamController.Core; using AdamController.Core.Mvvm; +using AdamController.Services; using AdamController.Services.Interfaces; using MahApps.Metro.IconPacks; using Prism.Commands; @@ -128,19 +129,13 @@ private int BadgeCounter get { return badgeCounter; } set { - if (badgeCounter == value) - return; + var isNewValue = SetProperty(ref badgeCounter, value); - if (value == 0) - { - badgeCounter = value; - NotificationBadge = ""; - return; - } + if(isNewValue) + NotificationBadge = $"{BadgeCounter}"; - badgeCounter = value; - - NotificationBadge = $"{BadgeCounter}"; + if(BadgeCounter == 0) + NotificationBadge = string.Empty; } } @@ -150,46 +145,49 @@ private int BadgeCounter private void Subscribe() { - //ComunicateHelper.OnAdamTcpConnectedEvent += OnTcpConnected; - //ComunicateHelper.OnAdamTcpDisconnectedEvent += OnTcpDisconnected; - //ComunicateHelper.OnAdamTcpReconnected += OnTcpReconnected; - - mCommunicationProviderService.RaiseTcpServiceCientConnectedEvent += RaiseAdamTcpCientConnected; - mCommunicationProviderService.RaiseTcpServiceClientDisconnectEvent += RaiseAdamTcpClientDisconnect; + mCommunicationProviderService.RaiseTcpServiceCientConnectedEvent += RaiseAdamTcpCientConnectedEvent; + mCommunicationProviderService.RaiseTcpServiceClientDisconnectEvent += RaiseAdamTcpClientDisconnectEvent; + mCommunicationProviderService.RaiseTcpServiceClientReconnectedEvent += RaiseTcpServiceClientReconnectedEvent; mStatusBarNotificationDelivery.RaiseChangeProgressRingStateEvent += RaiseChangeProgressRingStateEvent; mStatusBarNotificationDelivery.RaiseNewCompileLogMessageEvent += RaiseNewCompileLogMessageEvent; mStatusBarNotificationDelivery.RaiseNewAppLogMessageEvent += RaiseNewAppLogMessageEvent; - mStatusBarNotificationDelivery.RaiseNewNotificationBadgeMessageEvent += RaiseNewNotificationBadgeMessageEvent; mStatusBarNotificationDelivery.RaiseUpdateNotificationCounterEvent += RaiseUpdateNotificationCounterEvent; } private void Unsubscribe() { - mCommunicationProviderService.RaiseTcpServiceCientConnectedEvent -= RaiseAdamTcpCientConnected; - mCommunicationProviderService.RaiseTcpServiceClientDisconnectEvent -= RaiseAdamTcpClientDisconnect; - + mCommunicationProviderService.RaiseTcpServiceCientConnectedEvent -= RaiseAdamTcpCientConnectedEvent; + mCommunicationProviderService.RaiseTcpServiceClientDisconnectEvent -= RaiseAdamTcpClientDisconnectEvent; + mCommunicationProviderService.RaiseTcpServiceClientReconnectedEvent -= RaiseTcpServiceClientReconnectedEvent; mStatusBarNotificationDelivery.RaiseChangeProgressRingStateEvent -= RaiseChangeProgressRingStateEvent; mStatusBarNotificationDelivery.RaiseNewCompileLogMessageEvent -= RaiseNewCompileLogMessageEvent; mStatusBarNotificationDelivery.RaiseNewAppLogMessageEvent -= RaiseNewAppLogMessageEvent; - mStatusBarNotificationDelivery.RaiseNewNotificationBadgeMessageEvent -= RaiseNewNotificationBadgeMessageEvent; } #endregion #region Event methods - private void RaiseAdamTcpClientDisconnect(object sender) + private void RaiseAdamTcpCientConnectedEvent(object sender) { - ConnectIcon = PackIconModernKind.Connect; - TextOnStatusConnectToolbar = cTextOnStatusConnectToolbarDisconnected; + ConnectIcon = PackIconModernKind.Disconnect; + TextOnStatusConnectToolbar = cTextOnStatusConnectToolbarConnected; } - private void RaiseAdamTcpCientConnected(object sender) + private void RaiseTcpServiceClientReconnectedEvent(object sender, int reconnectCounter) { - ConnectIcon = PackIconModernKind.Disconnect; - TextOnStatusConnectToolbar = cTextOnStatusConnectToolbarConnected; + mStatusBarNotificationDelivery.NotificationCounter++; + ConnectIcon = PackIconModernKind.TransitConnectionDeparture; + TextOnStatusConnectToolbar = $"{cTextOnStatusConnectToolbarReconnected} {reconnectCounter}"; + } + + private void RaiseAdamTcpClientDisconnectEvent(object sender) + { + ConnectIcon = PackIconModernKind.Connect; + TextOnStatusConnectToolbar = cTextOnStatusConnectToolbarDisconnected; + mStatusBarNotificationDelivery.NotificationCounter++; } private void RaiseChangeProgressRingStateEvent(object sender, bool newState) @@ -207,10 +205,6 @@ private void RaiseNewAppLogMessageEvent(object sender, string message) AppLogStatusBar = message; } - private void RaiseNewNotificationBadgeMessageEvent(object sender, string message) - { - NotificationBadge = message; - } private void RaiseUpdateNotificationCounterEvent(object sender, int counter) { From 67ff7aec98a178dec252ec616b2843b9f2ba92b3 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 15 Apr 2024 10:10:48 +1000 Subject: [PATCH 089/181] Close #16 --- .../ViewModels/NotificationViewModel.cs | 58 +++++++++++++------ .../Views/NotificationView.xaml | 19 +++--- .../ViewModels/StatusBarViewModel.cs | 18 +++++- 3 files changed, 63 insertions(+), 32 deletions(-) diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index 83d44fe..093e104 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -1,7 +1,6 @@ using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; using AdamController.Core.Properties; using AdamController.Services.Interfaces; -using AdamController.WebApi.Client.v1; using MahApps.Metro.IconPacks; using Prism.Commands; using System.Windows; @@ -12,15 +11,16 @@ public class NotificationViewModel : FlyoutBase { #region DelegateCommands - public DelegateCommand ConnectButtonDelegateCommand { get; } - public DelegateCommand ResetNotificationsDelegateCommand { get; } + public DelegateCommand ConnectButtonDelegateCommand { get; private set; } + public DelegateCommand ReconnectNotificationButtonDelegateCommand { get; private set; } + public DelegateCommand ResetNotificationsDelegateCommand { get; private set; } #endregion #region Services - private readonly ICommunicationProviderService mCommunicationProvider; - private readonly IStatusBarNotificationDeliveryService mStatusBarNotificationDeliveryService; + private ICommunicationProviderService mCommunicationProvider; + private IStatusBarNotificationDeliveryService mStatusBarNotificationDeliveryService; #endregion @@ -42,6 +42,7 @@ public NotificationViewModel(ICommunicationProviderService communicationProvider mStatusBarNotificationDeliveryService = statusBarNotificationDelivery; ConnectButtonDelegateCommand = new (ConnectButton, ConnectButtonCanExecute); + ReconnectNotificationButtonDelegateCommand = new (ReconnectNotificationButton, ReconnectNotificationButtonCanExecute); ResetNotificationsDelegateCommand = new (ResetNotifications, ResetNotificationsCanExecute); } @@ -55,18 +56,24 @@ protected override void OnChanging(bool isOpening) if (isOpening) { Subscribe(); + SetStatusConnection(mCommunicationProvider.IsTcpClientConnected); } if (!isOpening) + { Unsubscribe(); + ConnectButtonDelegateCommand = null; + ReconnectNotificationButtonDelegateCommand = null; + ResetNotificationsDelegateCommand = null; + } + + base.OnChanging(isOpening); } - - #endregion #region Public field @@ -97,13 +104,6 @@ public Visibility FailConnectNotificationVisibility } } - private double notificationOpacity = Settings.Default.NotificationOpacity; - public double NotificationOpacity - { - get => notificationOpacity; - set => SetProperty(ref notificationOpacity, value); - } - private string contentConnectButton = cConnectButtonStatusDisconnected; public string ContentConnectButton { @@ -131,7 +131,7 @@ private void SetFlyoutParametrs() } /// - /// + /// Controls the display of the connection status /// /// true is connected, false disconetcted, null reconected /// @@ -205,11 +205,15 @@ private void OnRaiseTcpServiceClientDisconnect(object sender) private void ConnectButton() { - if (mCommunicationProvider.IsTcpClientConnected) + bool isConnected = mCommunicationProvider.IsTcpClientConnected; + + if (isConnected) + { mCommunicationProvider.DisconnectAllAsync(); - - if (!mCommunicationProvider.IsTcpClientConnected) - mCommunicationProvider.ConnectAllAsync(); + return; + } + + mCommunicationProvider.ConnectAllAsync(); } private bool ConnectButtonCanExecute() @@ -228,6 +232,22 @@ private bool ResetNotificationsCanExecute() return true; } + private void ReconnectNotificationButton() + { + bool isConnected = mCommunicationProvider.IsTcpClientConnected; + + if (!isConnected) + { + mCommunicationProvider.ConnectAllAsync(); + ResetNotifications(); + } + } + + private bool ReconnectNotificationButtonCanExecute() + { + return true; + } + #endregion } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml index 0ddb305..be27fb2 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml @@ -53,12 +53,12 @@ + Width="Auto" Height="Auto" + Margin="10 20 0 0" + FontStyle="Normal" + FontWeight="Bold" + FontSize="18" + Text="Робот Адам отключен!" /> @@ -91,7 +90,7 @@ HorizontalAlignment="Right" FontWeight="Bold"> - + Очистить уведомления diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index 67119c4..f922c74 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -131,16 +131,28 @@ private int BadgeCounter { var isNewValue = SetProperty(ref badgeCounter, value); - if(isNewValue) - NotificationBadge = $"{BadgeCounter}"; - if(BadgeCounter == 0) + if (isNewValue) + UpdateNotificationBagde(); + + if (BadgeCounter == 0) NotificationBadge = string.Empty; } } #endregion + /// + /// BadgeCounter < 2 + /// Restricts the notification counter so that it is not updated on repeated connections. + /// Only one notification will work. When the second one appears, they will need to be distinguished somehow. + /// + private void UpdateNotificationBagde() + { + if(BadgeCounter < 2) + NotificationBadge = $"{BadgeCounter}"; + } + #region Subscribes private void Subscribe() From 8fd3ac66bae9e7508b7a5ad79bf7697bee3d2047 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 15 Apr 2024 13:49:24 +1000 Subject: [PATCH 090/181] Prepare works #25 --- .../Views/VisualSettingsControlView.xaml | 3 +- .../AdvancedBlocklySettingsViewModel.cs | 304 ++++++--- .../ViewModels/NotificationViewModel.cs | 8 +- .../Views/AdvancedBlocklySettingsView.xaml | 623 +++++++++--------- .../Views/NotificationView.xaml | 5 +- 5 files changed, 551 insertions(+), 392 deletions(-) diff --git a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml index fe68faf..9436142 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml @@ -341,11 +341,13 @@ FontWeight="Normal" ItemsSource="{Binding BlocklyLanguageCollection}" SelectedItem="{Binding SelectedBlocklyWorkspaceLanguage}"> + + @@ -374,7 +376,6 @@ diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs index 68c31c8..b7e4e96 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs @@ -13,96 +13,117 @@ namespace AdamController.Modules.FlayoutsRegion.ViewModels { public class AdvancedBlocklySettingsViewModel : FlyoutBase { + #region DelegateCommands + + public DelegateCommand ChangeToolboxLanguageToggleSwitchDelegateCommand { get; private set; } + public DelegateCommand ChangeGridColorToggleSwitchDelegateCommand { get; private set; } + public DelegateCommand ChangeBlocklyThemeToogleSwitchDelegateCommand { get; private set; } + public DelegateCommand ChangeSpacingToggleSwitchDelegateCommand { get; private set; } + public DelegateCommand EnableShowGridDelegateCommand { get; private set; } + + #endregion + public AdvancedBlocklySettingsViewModel() { - Header = "Продвинутые настройки скретч-редактора"; - + SetFlyoutParametrs(); } - protected override void OnOpening(FlyoutParameters flyoutParameters) + #region Navigation + + protected override void OnChanging(bool isOpening) { - base.OnOpening(flyoutParameters); + + if (isOpening) + { + UpdatePublicFields(); + Subscribe(); + CreateDelegateCommand(); + } + + + if (!isOpening) + { + ClearPublicFields(); + Unsubscribe(); + ResetDelegateCommand(); + } + + base.OnChanging(isOpening); } - protected override void OnClosing(FlyoutParameters flyoutParameters) + #endregion + + #region Public fields + + private void UpdatePublicFields() { - base.OnClosing(flyoutParameters); + SelectedBlocklyGridColour = MahApps.Metro.Controls.ColorHelper.ColorFromString(Settings.Default.BlocklyGridColour); + BlocklyLanguageCollection = new ObservableCollection(LanguagesCollection.BlocklyLanguageCollection); + SelectedBlocklyToolboxLanguage = BlocklyLanguageCollection.FirstOrDefault(x => x.BlocklyLanguage == Settings.Default.BlocklyToolboxLanguage); + BlocklyThemes = new ObservableCollection(ThemesCollection.BlocklyThemes); + SelectedBlocklyTheme = BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == Settings.Default.BlocklyTheme); } - #region BlocklyGridColour settings + private void ClearPublicFields() + { + //SelectedBlocklyGridColour = null; + BlocklyLanguageCollection = null; + //SelectedBlocklyToolboxLanguage = null; + BlocklyThemes = null; + //SelectedBlocklyTheme = null; + } - private Color? selectedBlocklyGridColour = MahApps.Metro.Controls.ColorHelper.ColorFromString(Settings.Default.BlocklyGridColour); + private Color? selectedBlocklyGridColour; public Color? SelectedBlocklyGridColour { get => selectedBlocklyGridColour; set { - if (value == selectedBlocklyGridColour) - { - return; - } - selectedBlocklyGridColour = value; + bool isNewValue = SetProperty(ref selectedBlocklyGridColour, value); - SetProperty(ref selectedBlocklyGridColour, value); - Settings.Default.BlocklyGridColour = selectedBlocklyGridColour.ToString(); + if (isNewValue) + Settings.Default.BlocklyGridColour = SelectedBlocklyGridColour.ToString(); } } - #endregion - - #region BlocklyToolboxLanguage Settings - - public static ObservableCollection BlocklyLanguageCollection { get; private set; } = LanguagesCollection.BlocklyLanguageCollection; + private ObservableCollection blocklyLanguageCollection; + public ObservableCollection BlocklyLanguageCollection + { + get => blocklyLanguageCollection; + set => SetProperty(ref blocklyLanguageCollection, value); + } - private BlocklyLanguageModel selectedBlocklyToolboxLanguage = BlocklyLanguageCollection.FirstOrDefault(x => x.BlocklyLanguage == Settings.Default.BlocklyToolboxLanguage); + private BlocklyLanguageModel selectedBlocklyToolboxLanguage; public BlocklyLanguageModel SelectedBlocklyToolboxLanguage { get => selectedBlocklyToolboxLanguage; - set - { - if (value == selectedBlocklyToolboxLanguage) - { - return; - } - - selectedBlocklyToolboxLanguage = value; - - SetProperty(ref selectedBlocklyToolboxLanguage, value); - - Settings.Default.BlocklyToolboxLanguage = selectedBlocklyToolboxLanguage.BlocklyLanguage; - } + set => SetProperty(ref selectedBlocklyToolboxLanguage, value); } - #endregion - - #region BlocklyTheme Settings - - public static ObservableCollection BlocklyThemes { get; private set; } = ThemesCollection.BlocklyThemes; + private ObservableCollection blocklyThemes; + public ObservableCollection BlocklyThemes + { + get => blocklyThemes; + set => SetProperty(ref blocklyThemes, value); + } - private BlocklyThemeModel selectedBlocklyTheme = BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == Settings.Default.BlocklyTheme); + private BlocklyThemeModel selectedBlocklyTheme; public BlocklyThemeModel SelectedBlocklyTheme { get => selectedBlocklyTheme; - set - { - if (value == selectedBlocklyTheme) - { - return; - } - - selectedBlocklyTheme = value; - SetProperty(ref selectedBlocklyTheme, value); - - Settings.Default.BlocklyTheme = selectedBlocklyTheme.BlocklyTheme; - - if (Settings.Default.ChangeGridColorSwitchToggleSwitchState) return; - SelectGridColorDependingSelectedTheme(SelectedBlocklyTheme.BlocklyTheme); - } + set => SetProperty(ref selectedBlocklyTheme, value); } #endregion - #region SelectMainTheme + #region Private metods + + private void SetFlyoutParametrs() + { + Theme = FlyoutTheme.Inverse; + Header = "Продвинутые настройки скретч-редактора"; + IsModal = true; + } private void SelectGridColorDependingSelectedTheme(BlocklyTheme theme) { @@ -126,63 +147,190 @@ private void SelectGridColorDependingSelectedTheme(BlocklyTheme theme) } } + private void CreateDelegateCommand() + { + ChangeToolboxLanguageToggleSwitchDelegateCommand = new DelegateCommand(ChangeToolboxLanguageToggleSwitch, ChangeToolboxLanguageToggleSwitchCanExecute); + ChangeGridColorToggleSwitchDelegateCommand = new DelegateCommand(ChangeGridColorToggleSwitch, ChangeGridColorToggleSwitchCanExecute); + ChangeBlocklyThemeToogleSwitchDelegateCommand = new DelegateCommand(ChangeBlocklyThemeToogleSwitch, ChangeBlocklyThemeToogleSwitchCanExecute); + ChangeSpacingToggleSwitchDelegateCommand = new DelegateCommand(ChangeSpacingToggleSwitch, ChangeSpacingToggleSwitchCanExecute); + EnableShowGridDelegateCommand = new DelegateCommand(EnableShowGridDelegate, EnableShowGridDelegateCanExecute); + } + + private void ResetDelegateCommand() + { + ChangeToolboxLanguageToggleSwitchDelegateCommand = null; + ChangeGridColorToggleSwitchDelegateCommand = null; + ChangeBlocklyThemeToogleSwitchDelegateCommand = null; + ChangeSpacingToggleSwitchDelegateCommand = null; + EnableShowGridDelegateCommand = null; + } + #endregion - #region Commands + #region Delegate command methods - private DelegateCommand changeToolboxLanguageToggleSwitchCommand; - public DelegateCommand ChangeToolboxLanguageToggleSwitchCommand => changeToolboxLanguageToggleSwitchCommand ??= new DelegateCommand(obj => + private void ChangeToolboxLanguageToggleSwitch(bool? obj) { bool? toogleSwitchState = obj; - if (toogleSwitchState == true) return; + if (toogleSwitchState == true) + return; SelectedBlocklyToolboxLanguage = BlocklyLanguageCollection.FirstOrDefault(x => x.BlocklyLanguage == Settings.Default.BlocklyWorkspaceLanguage); + Settings.Default.BlocklyToolboxLanguage = SelectedBlocklyToolboxLanguage.BlocklyLanguage; + } - }); + private bool ChangeToolboxLanguageToggleSwitchCanExecute(bool? nullable) + { + return true; + } - private DelegateCommand changeGridColorToggleSwitchCommand; - public DelegateCommand ChangeGridColorToggleSwitchCommand => changeGridColorToggleSwitchCommand ??= new DelegateCommand(obj => + private void ChangeGridColorToggleSwitch(bool? obj) { bool? toogleSwitchState = obj; - if (toogleSwitchState == true) return; + if (toogleSwitchState == true) + return; + + SelectGridColorDependingSelectedTheme(SelectedBlocklyTheme.BlocklyTheme); + + //if (isNewValue) + //{ + // Settings.Default.BlocklyTheme = SelectedBlocklyTheme.BlocklyTheme; + + if (Settings.Default.ChangeGridColorSwitchToggleSwitchState) + return; SelectGridColorDependingSelectedTheme(SelectedBlocklyTheme.BlocklyTheme); - }); + Settings.Default.BlocklyTheme = SelectedBlocklyTheme.BlocklyTheme; + + // SelectGridColorDependingSelectedTheme(SelectedBlocklyTheme.BlocklyTheme); + //} + } - private DelegateCommand changeBlocklyThemeToogleSwitchCommand; - public DelegateCommand ChangeBlocklyThemeToogleSwitchCommand => changeBlocklyThemeToogleSwitchCommand ??= new DelegateCommand(obj => + private bool ChangeGridColorToggleSwitchCanExecute(bool? nullable) + { + return true; + } + + private void ChangeBlocklyThemeToogleSwitch(bool? obj) { bool? toogleSwitchState = obj; - if (toogleSwitchState == true) return; + if (toogleSwitchState == true) + return; if (Settings.Default.BaseTheme == "Dark") { - SelectedBlocklyTheme = BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == BlocklyTheme.Dark); + SelectedBlocklyTheme = BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == BlocklyTheme.Dark); } else if (Settings.Default.BaseTheme == "Light") { SelectedBlocklyTheme = BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == BlocklyTheme.Classic); } - }); + } - private DelegateCommand changeSpacingToggleSwitchCommand; - public DelegateCommand ChangeSpacingToggleSwitchCommand => changeSpacingToggleSwitchCommand ??= new DelegateCommand(obj => + private bool ChangeBlocklyThemeToogleSwitchCanExecute(bool? nullable) { - bool? toogleSwitchState = obj; + return true; + } - if (toogleSwitchState == true) return; + private void ChangeSpacingToggleSwitch(bool? obj) + { + bool? toogleSwitchState = obj; + if (toogleSwitchState == true) + return; + Settings.Default.BlocklyGridSpacing = 20; - }); + } + + private bool ChangeSpacingToggleSwitchCanExecute(bool? nullable) + { + return true; + } - private DelegateCommand enableShowGridCommand; - public DelegateCommand EnableShowGridCommand => enableShowGridCommand ??= new DelegateCommand(() => + private void EnableShowGridDelegate() { Settings.Default.BlocklyShowGrid = true; - }); + } + + private bool EnableShowGridDelegateCanExecute() + { + return true; + } + + #endregion + + #region Subscriptions + + private void Subscribe() + { + + } + + private void Unsubscribe() + { + + } + + #endregion + + #region Commands + + //private DelegateCommand changeToolboxLanguageToggleSwitchCommand; + //public DelegateCommand ChangeToolboxLanguageToggleSwitchCommand => changeToolboxLanguageToggleSwitchCommand ??= new DelegateCommand(obj => + //{ + //bool? toogleSwitchState = obj; + + //if (toogleSwitchState == true) return; + + //SelectedBlocklyToolboxLanguage = BlocklyLanguageCollection.FirstOrDefault(x => x.BlocklyLanguage == Settings.Default.BlocklyWorkspaceLanguage); + + //}); + + //private DelegateCommand changeGridColorToggleSwitchCommand; + //public DelegateCommand ChangeGridColorToggleSwitchCommand => changeGridColorToggleSwitchCommand ??= new DelegateCommand(obj => + //{ + // bool? toogleSwitchState = obj; + + // if (toogleSwitchState == true) return; + + // SelectGridColorDependingSelectedTheme(SelectedBlocklyTheme.BlocklyTheme); + //}); + + //private DelegateCommand changeBlocklyThemeToogleSwitchCommand; + //public DelegateCommand ChangeBlocklyThemeToogleSwitchCommand => changeBlocklyThemeToogleSwitchCommand ??= new DelegateCommand(obj => + //{ + // bool? toogleSwitchState = obj; + + // if (toogleSwitchState == true) return; + + // if (Settings.Default.BaseTheme == "Dark") + // { + // SelectedBlocklyTheme = BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == BlocklyTheme.Dark); + // } + // else if (Settings.Default.BaseTheme == "Light") + // { + // SelectedBlocklyTheme = BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == BlocklyTheme.Classic); + // } + //}); + + //private DelegateCommand changeSpacingToggleSwitchCommand; + //public DelegateCommand ChangeSpacingToggleSwitchCommand => changeSpacingToggleSwitchCommand ??= new DelegateCommand(obj => + //{ + // bool? toogleSwitchState = obj; + + // if (toogleSwitchState == true) return; + + // Settings.Default.BlocklyGridSpacing = 20; + //}); + + //private DelegateCommand enableShowGridCommand; + //public DelegateCommand EnableShowGridCommand => enableShowGridCommand ??= new DelegateCommand(() => + //{ + // Settings.Default.BlocklyShowGrid = true; + //}); #endregion } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index 093e104..2c5c042 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -40,10 +40,6 @@ public NotificationViewModel(ICommunicationProviderService communicationProvider mCommunicationProvider = communicationProvider; mStatusBarNotificationDeliveryService = statusBarNotificationDelivery; - - ConnectButtonDelegateCommand = new (ConnectButton, ConnectButtonCanExecute); - ReconnectNotificationButtonDelegateCommand = new (ReconnectNotificationButton, ReconnectNotificationButtonCanExecute); - ResetNotificationsDelegateCommand = new (ResetNotifications, ResetNotificationsCanExecute); } #endregion @@ -57,6 +53,10 @@ protected override void OnChanging(bool isOpening) { Subscribe(); + ConnectButtonDelegateCommand = new(ConnectButton, ConnectButtonCanExecute); + ReconnectNotificationButtonDelegateCommand = new(ReconnectNotificationButton, ReconnectNotificationButtonCanExecute); + ResetNotificationsDelegateCommand = new(ResetNotifications, ResetNotificationsCanExecute); + SetStatusConnection(mCommunicationProvider.IsTcpClientConnected); } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/AdvancedBlocklySettingsView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/AdvancedBlocklySettingsView.xaml index d3acb00..33ab8b8 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/AdvancedBlocklySettingsView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/AdvancedBlocklySettingsView.xaml @@ -1,18 +1,19 @@  + prism:ViewModelLocator.AutoWireViewModel="True"> + + + + + - - @@ -54,21 +55,22 @@ + IsEnabled="False" + Margin="7 0 0 0" + x:Name="LogicSwitch" + Header="Цвет категории логические" + OnContent="Вручную" + OffContent="Автоматически" + IsOn="{Binding BlocklyLogicCategoryStateD, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" + VerticalAlignment="Bottom"/> + IsEnabled="{Binding ElementName=LogicSwitch, Path=IsEnabled}" + VerticalAlignment="Bottom" + HorizontalAlignment="Center" + SelectedItem="{Binding BlocklyGridColour}" + Style="{DynamicResource MahApps.Styles.ListBox.HamburgerMenu}"> + Red Green Blue @@ -76,41 +78,43 @@ Yellow White Gray + + mah:TextBoxHelper.ClearTextButton="True" + mah:TextBoxHelper.Watermark="Альтернативное название"/> + IsEnabled="False" + Margin="7 0 0 0" + x:Name="ColourSwitch" + Header="Цвет категории цвета" + OnContent="Вручную" + OffContent="Автоматически" + IsOn="{Binding BlocklyColorCategoryStateD, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" + VerticalAlignment="Bottom"/> + IsEnabled="{Binding ElementName=ColourSwitch, Path=IsEnabled}" + VerticalAlignment="Bottom" + HorizontalAlignment="Center" + SelectedItem="{Binding BlocklyGridColour}" + Style="{DynamicResource MahApps.Styles.ListBox.HamburgerMenu}"> + Red Green Blue @@ -118,41 +122,41 @@ Yellow White Gray - + + Margin="0 0 20 0" + Text="{Binding BlocklyColourCategoryAlternateName, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" + FontWeight="Bold" + VerticalAlignment="Bottom" + HorizontalAlignment="Left" + TextAlignment="Left" + Style="{DynamicResource MahApps.Styles.TextBox.Window.QuickLaunch.VisualStudio}" + mah:TextBoxHelper.ClearTextButton="True" + mah:TextBoxHelper.Watermark="Альтернативное название"/> + IsEnabled="False" + Margin="7 0 0 0" + x:Name="ListsSwitch" + Header="Цвет категория cписки" + OnContent="Вручную" + OffContent="Автоматически" + VerticalAlignment="Bottom" + IsOn="{Binding BlocklyListsCategoryStateD, Mode=TwoWay, Source={x:Static properties:Settings.Default}}"/> + IsEnabled="{Binding ElementName=ListsSwitch, Path=IsEnabled}" + VerticalAlignment="Bottom" + HorizontalAlignment="Center" + SelectedItem="{Binding BlocklyGridColour}" + Style="{DynamicResource MahApps.Styles.ListBox.HamburgerMenu}"> + Red Green Blue @@ -160,40 +164,42 @@ Yellow White Gray + + Margin="0 0 20 0" + Text="{Binding BlocklyListsCategoryAlternateName, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" + FontWeight="Bold" + VerticalAlignment="Bottom" + HorizontalAlignment="Left" + TextAlignment="Left" + Style="{DynamicResource MahApps.Styles.TextBox.Window.QuickLaunch.VisualStudio}" + mah:TextBoxHelper.ClearTextButton="True" + mah:TextBoxHelper.Watermark="Альтернативное название"/> + IsEnabled="False" + Margin="7 0 0 0" + x:Name="LoopSwitch" + Header="Цвет категории циклы" + OnContent="Вручную" + OffContent="Автоматически" + VerticalAlignment="Bottom" + IsOn="{Binding BlocklyLoopCategoryStateD, Mode=TwoWay, Source={x:Static properties:Settings.Default}}"/> + IsEnabled="{Binding ElementName=LoopSwitch, Path=IsEnabled}" + VerticalAlignment="Bottom" + HorizontalAlignment="Center" + SelectedItem="{Binding BlocklyGridColour}" + Style="{DynamicResource MahApps.Styles.ListBox.HamburgerMenu}"> + Red Green Blue @@ -201,41 +207,42 @@ Yellow White Gray + + mah:TextBoxHelper.ClearTextButton="True" + mah:TextBoxHelper.Watermark="Альтернативное название"/> + IsEnabled="False" + Margin="7 0 0 0" + x:Name="MathSwitch" + Header="Цвет категории математические" + OnContent="Вручную" + OffContent="Автоматически" + VerticalAlignment="Bottom" + IsOn="{Binding BlocklyMathCategoryStateD, Mode=TwoWay, Source={x:Static properties:Settings.Default}}"/> + IsEnabled="{Binding ElementName=MathSwitch, Path=IsEnabled}" + VerticalAlignment="Bottom" + HorizontalAlignment="Center" + SelectedItem="{Binding BlocklyGridColour}" + Style="{DynamicResource MahApps.Styles.ListBox.HamburgerMenu}"> Red Green @@ -244,40 +251,42 @@ Yellow White Gray + + Text="{Binding BlocklyMathCategoryAlternateName, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" + FontWeight="Bold" + VerticalAlignment="Bottom" + HorizontalAlignment="Left" + TextAlignment="Left" + Style="{DynamicResource MahApps.Styles.TextBox.Window.QuickLaunch.VisualStudio}" + Margin="0 0 20 0" + mah:TextBoxHelper.ClearTextButton="True" + mah:TextBoxHelper.Watermark="Альтернативное название"/> + IsEnabled="False" + Margin="7 0 0 0" + x:Name="ProcedureSwitch" + Header="Цвет категории процедуры" + OnContent="Вручную" + OffContent="Автоматически" + VerticalAlignment="Bottom" + IsOn="{Binding BlocklyProcedureCategoryStateD, Mode=TwoWay, Source={x:Static properties:Settings.Default}}"/> + IsEnabled="{Binding ElementName=ProcedureSwitch, Path=IsEnabled}" + VerticalAlignment="Bottom" + HorizontalAlignment="Center" + SelectedItem="{Binding BlocklyGridColour}" + Style="{DynamicResource MahApps.Styles.ListBox.HamburgerMenu}"> + Red Green Blue @@ -285,41 +294,43 @@ Yellow White Gray + + Text="{Binding BlocklyProcedureCategoryAlternateName, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" + FontWeight="Bold" + VerticalAlignment="Bottom" + HorizontalAlignment="Left" + TextAlignment="Left" + Style="{DynamicResource MahApps.Styles.TextBox.Window.QuickLaunch.VisualStudio}" + Margin="0 0 20 0" + mah:TextBoxHelper.ClearTextButton="True" + mah:TextBoxHelper.Watermark="Альтернативное название"/> + IsEnabled="False" + Margin="7 0 20 0" + x:Name="DynamicVariableSwitch" + Header="Цвет категории динамические переменные" + OnContent="Вручную" + OffContent="Автоматически" + VerticalAlignment="Bottom" + IsOn="{Binding BlocklyDynamicVariableCategoryStateD, Mode=TwoWay, Source={x:Static properties:Settings.Default}}"/> + IsEnabled="{Binding ElementName=DynamicVariableSwitch, Path=IsEnabled}" + VerticalAlignment="Bottom" + HorizontalAlignment="Center" + Margin="0 0 0 3" + SelectedItem="{Binding BlocklyGridColour}" + Style="{DynamicResource MahApps.Styles.ListBox.HamburgerMenu}"> + Red Green Blue @@ -327,42 +338,43 @@ Yellow White Gray + + Margin="0 0 20 0" + Text="{Binding BlocklyDynamicVariableCategoryAlternateName, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" + FontWeight="Bold" + VerticalAlignment="Bottom" + HorizontalAlignment="Left" + TextAlignment="Left" + Style="{DynamicResource MahApps.Styles.TextBox.Window.QuickLaunch.VisualStudio}" + mah:TextBoxHelper.ClearTextButton="True" + mah:TextBoxHelper.Watermark="Альтернативное название"/> + IsEnabled="False" + Margin="7 0 0 0" + x:Name="VariableSwitch" + Header="Цвет категории переменные" + OnContent="Вручную" + OffContent="Автоматически" + VerticalAlignment="Bottom" + IsOn="{Binding BlocklyVariableCategoryStateD, Mode=TwoWay, Source={x:Static properties:Settings.Default}}"/> + IsEnabled="{Binding ElementName=VariableSwitch, Path=IsEnabled}" + VerticalAlignment="Bottom" + HorizontalAlignment="Center" + Margin="0 0 0 3" + SelectedItem="{Binding BlocklyGridColour}" + Style="{DynamicResource MahApps.Styles.ListBox.HamburgerMenu}"> + Red Green Blue @@ -370,46 +382,46 @@ Yellow White Gray + + Text="{Binding BlocklyVariableCategoryAlternateName, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" + FontWeight="Bold" + VerticalAlignment="Bottom" + HorizontalAlignment="Left" + TextAlignment="Left" + Style="{DynamicResource MahApps.Styles.TextBox.Window.QuickLaunch.VisualStudio}" + Margin="0 0 20 0" + mah:TextBoxHelper.ClearTextButton="True" + mah:TextBoxHelper.Watermark="Альтернативное название"/> - + Margin="7 0 0 0" + x:Name="ChangeToolboxLanguage" + Header="Язык панели инструментов" + OnContent="Вручную" + OffContent="Автоматически" + VerticalAlignment="Bottom" + Command="{Binding ChangeToolboxLanguageToggleSwitchDelegateCommand}" + CommandParameter="{Binding ElementName=ChangeToolboxLanguage, Path=IsOn}" + IsOn="{Binding ChangeToolboxLanguageToggleSwitchState, Mode=TwoWay, Source={x:Static properties:Settings.Default}}"/> + + IsEnabled="{Binding ElementName=ChangeToolboxLanguage, Path=IsOn}" + Margin="5 20 20 5" + DisplayMemberPath="LanguageName" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Left" + FontWeight="Normal" + ItemsSource="{Binding BlocklyLanguageCollection}" + SelectedItem="{Binding SelectedBlocklyToolboxLanguage}"> @@ -421,34 +433,34 @@ + Grid.ColumnSpan="3" + VerticalAlignment="Center" + HorizontalAlignment="Left" + FontWeight="Bold" + Margin="0 20 0 10" + Text="Настройки рабочей области"/> - + Margin="7 0 0 0" + x:Name="ChangeGridColorSwitch" + Header="Цвет сетки" + OnContent="Вручную" + OffContent="Автоматически" + VerticalAlignment="Bottom" + Command="{Binding ChangeGridColorToggleSwitchDelegateCommand}" + CommandParameter="{Binding ElementName=ChangeGridColorSwitch, Path=IsOn}" + IsEnabled="{Binding BlocklyShowGrid, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" + IsOn="{Binding ChangeGridColorSwitchToggleSwitchState, Mode=TwoWay, Source={x:Static properties:Settings.Default}}"/> + + Padding="0 0 0 10" + VerticalAlignment="Bottom" + HorizontalAlignment="Center" + SelectedItem="{Binding SelectedBlocklyGridColour}" + Style="{DynamicResource MahApps.Styles.ListBox.HamburgerMenu}"> Red Green @@ -458,88 +470,89 @@ White Gray - - - - - - + + + + + + + + - + Margin="7 0 0 0" + x:Name="ChangeSpacingSwitch" + Header="Размер ячейки" + OnContent="Вручную" + OffContent="Автоматически" + VerticalAlignment="Bottom" + IsOn="{Binding ChangeSpacingSwitchToggleSwitchState, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" + IsEnabled="{Binding BlocklyShowGrid, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" + Command="{Binding ChangeSpacingToggleSwitchDelegateCommand}" + CommandParameter="{Binding ElementName=ChangeSpacingSwitch, Path=IsOn}"/> + - - - - - - - + Value="{Binding BlocklyGridSpacing, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" + Padding="0 0 4 0" + Minimum="5" + Maximum="50" + Interval="5" + FontWeight="Medium" + TextAlignment="Right" + Margin="5 20 20 5"> + + + + + + + Отображение сетки отключено в основных настройках. - Включить... + Grid.RowSpan="2" + TextWrapping="WrapWithOverflow" + VerticalAlignment="Center" + HorizontalAlignment="Center" + FontWeight="Bold" + Margin="0 20 20 10" + mah:VisibilityHelper.IsHidden= "{Binding ElementName=ChangeGridColorSwitch, Path=IsEnabled}">Отображение сетки отключено в основных настройках. + Включить... + - + Margin="7 0 0 0" + x:Name="ChangeBlocklyTheme" + Header="Тема рабочей области" + OnContent="Вручную" + OffContent="Автоматически" + VerticalAlignment="Bottom" + Command="{Binding ChangeBlocklyThemeToogleSwitchDelegateCommand}" + CommandParameter="{Binding ElementName=ChangeBlocklyTheme, Path=IsOn}" + IsOn="{Binding ChangeBlocklyThemeToggleSwitchState, Mode=TwoWay, Source={x:Static properties:Settings.Default}}"/> + + IsEnabled="{Binding ElementName=ChangeBlocklyTheme, Path=IsOn}" + Margin="5 20 20 5" + DisplayMemberPath="BlocklyThemeName" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Left" + FontWeight="Normal" + ItemsSource="{Binding BlocklyThemes}" + SelectedItem="{Binding SelectedBlocklyTheme}"> @@ -551,27 +564,27 @@ + Grid.ColumnSpan="3" + VerticalAlignment="Center" + HorizontalAlignment="Left" + FontWeight="Bold" + Margin="0 20 0 10" + Text="Настройки области вывода результатов"/> + Margin="7 0 0 0" + Header="Показывать в области выполнения" + OnContent="Отчет о запуске и результат выполнения" + OffContent="Только результат выполнения" + VerticalAlignment="Bottom" + IsOn="{Binding ChangeExtendedExecuteReportToggleSwitchState, Mode=TwoWay, Source={x:Static properties:Settings.Default}}"/> + Grid.ColumnSpan="2" + IsChecked="True" + Content="Использовать так же для редактора скриптов" + IsEnabled="False" + HorizontalAlignment="Center"/> diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml index be27fb2..29936f6 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/NotificationView.xaml @@ -1,9 +1,6 @@  - + From bac8114bd809e5d09609eec55c334b1f80417b58 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 15 Apr 2024 16:26:29 +1000 Subject: [PATCH 091/181] Close issue #27 --- .../ViewModels/ScratchControlViewModel.cs | 6 +- .../VisualSettingsControlViewModel.cs | 169 +++++++++++------- .../Views/ScratchControlView.xaml.cs | 11 +- .../Views/VisualSettingsControlView.xaml | 12 +- .../Views/VisualSettingsControlView.xaml.cs | 24 ++- .../ViewModels/NotificationViewModel.cs | 20 +-- 6 files changed, 143 insertions(+), 99 deletions(-) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index 946d667..fb3b8ff 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -38,7 +38,7 @@ public class ScratchControlViewModel : RegionViewModelBase #region Action field public static Action SendSourceToScriptEditor { get; set; } - public static Action ReloadWebView { get; set; } + public Action ReloadWebView { get; set; } #endregion @@ -54,7 +54,7 @@ public ScratchControlViewModel(IRegionManager regionManager, IDialogService dial IDialogManager = new MessageDialogManagerMahapps(Application.Current); - InitAction();; + InitAction(); } #region Navigation @@ -73,6 +73,8 @@ public override void OnNavigatedTo(NavigationContext navigationContext) mPythonRemoteRunner.RaisePythonStandartOutputEvent += OnRaisePythonStandartOutput; mPythonRemoteRunner.RaisePythonScriptExecuteFinishEvent += OnRaisePythonScriptExecuteFinish; + ReloadWebViewCommand.Execute(); + base.OnNavigatedTo(navigationContext); } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index 70319de..a704fcd 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -13,11 +13,34 @@ using System.Collections.ObjectModel; using System.Linq; using System.Windows; +using System.Windows.Media; namespace AdamController.Modules.ContentRegion.ViewModels { public class VisualSettingsControlViewModel : RegionViewModelBase { + #region DelegateCommands + + public DelegateCommand OpenAdvancedBlocklySettingsDelegateCommand { get; } + + public DelegateCommand ChangeBaseThemeDelegateCommand { get; } + + //public DelegateCommand ChangeThemeColorSchemeDelegateCommand { get; } + + #endregion + + #region Action + + //public static Action ChangeBaseTheme { get; set; } + + public static Action ChangeNotificationOpacity { get; set; } + //public static Action ChangeThemeColorScheme { get; set; } + //public static Action OpenAdvancedBlocklySettings { get; set; } + public static Action SetToolboxLanguage { get; set; } + public static Action SetBlocklyThemeAndGridColor { get; set; } + + #endregion + #region Service private IFlyoutManager FlyoutManager { get; } @@ -29,6 +52,34 @@ public class VisualSettingsControlViewModel : RegionViewModelBase public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager) : base(regionManager, dialogService) { FlyoutManager = flyoutManager; + + OpenAdvancedBlocklySettingsDelegateCommand = new DelegateCommand(OpenAdvancedBlocklySettings, OpenAdvancedBlocklySettingsCanExecute); + ChangeBaseThemeDelegateCommand = new DelegateCommand(ChangeBaseTheme, ChangeBaseThemeCanExecute); + //ChangeThemeColorScheme = new DelegateCommand() + } + + #endregion + + #region DelegateCommand methods + + private void OpenAdvancedBlocklySettings() + { + FlyoutManager.OpenFlyout(FlyoutNames.FlyotAdvancedBlocklySettings); + } + + private bool OpenAdvancedBlocklySettingsCanExecute() + { + return true; + } + + private void ChangeBaseTheme(string theme) + { + ChangeTheme(theme); + } + + private bool ChangeBaseThemeCanExecute(string theme) + { + return true; } #endregion @@ -53,12 +104,36 @@ public override void OnNavigatedFrom(NavigationContext navigationContext) #endregion - public static ObservableCollection BlocklyThemes { get; private set; } = ThemesCollection.BlocklyThemes; + #region Private methods + + private void ChangeTheme(string newTheme) + { + _ = ThemeManager.Current.ChangeThemeBaseColor(Application.Current, newTheme); + + if (!Settings.Default.ChangeBlocklyThemeToggleSwitchState) + { + if (newTheme == "Dark") + { + Settings.Default.BlocklyTheme = BlocklyTheme.Dark; + Settings.Default.BlocklyGridColour = Colors.White.ToString(); + } + + if (newTheme == "Light") + { + Settings.Default.BlocklyTheme = BlocklyTheme.Classic; + Settings.Default.BlocklyGridColour = Colors.Black.ToString(); + } + } + } + private void ChangeThemeColorScheme(string colorScheme) + { + ThemeManager.Current.ChangeThemeColorScheme(Application.Current, colorScheme); + } - #region LanguageSettings + #endregion - #region AppLanguage + public static ObservableCollection BlocklyThemes { get; private set; } = ThemesCollection.BlocklyThemes; public static ObservableCollection LanguageApp { get; private set; } = LanguagesCollection.AppLanguageCollection; @@ -81,10 +156,6 @@ public AppLanguageModel SelectedLanguageApp } } - #endregion - - #region BlocklyLanguage - public static ObservableCollection BlocklyLanguageCollection { get; private set; } = LanguagesCollection.BlocklyLanguageCollection; private BlocklyLanguageModel selectedBlocklyWorkspaceLanguage = BlocklyLanguageCollection.FirstOrDefault(x => x.BlocklyLanguage == Settings.Default.BlocklyWorkspaceLanguage); @@ -111,12 +182,6 @@ public BlocklyLanguageModel SelectedBlocklyWorkspaceLanguage } } - #endregion - - #endregion - - #region ColorScheme Settings - public ReadOnlyObservableCollection ColorScheme { get; set; } = ThemeManager.Current.ColorSchemes; private string selectedColorScheme = ThemeManager.Current.DetectTheme(Application.Current).ColorScheme; @@ -125,22 +190,13 @@ public string SelectedColorScheme get => selectedColorScheme; set { - if (value == selectedColorScheme) - { - return; - } - - selectedColorScheme = value; - - ChangeThemeColorScheme(selectedColorScheme); + bool isNewValue = SetProperty(ref selectedColorScheme, value); - SetProperty(ref selectedColorScheme, value); + if(isNewValue) + ChangeThemeColorScheme(selectedColorScheme); } } - #endregion - - #region BlocklyGridLenth settings //TODO unused this variable private short blocklyGridLenth = Settings.Default.BlocklyGridLenth; public short BlocklyGridLenth @@ -160,8 +216,7 @@ public short BlocklyGridLenth } } - #endregion - + private double notificationOpacity = Settings.Default.NotificationOpacity; public double NotificationOpacity { @@ -179,48 +234,36 @@ public double NotificationOpacity } - #region Command + - private DelegateCommand openAdvancedBlocklySettingsCommand; - public DelegateCommand OpenAdvancedBlocklySettingsCommand => openAdvancedBlocklySettingsCommand ??= new DelegateCommand(() => - { - FlyoutManager.OpenFlyout(FlyoutNames.FlyotAdvancedBlocklySettings); - }); + //private DelegateCommand openAdvancedBlocklySettingsCommand; + //public DelegateCommand OpenAdvancedBlocklySettingsCommand => openAdvancedBlocklySettingsCommand ??= new DelegateCommand(() => + //{ + // FlyoutManager.OpenFlyout(FlyoutNames.FlyotAdvancedBlocklySettings); + //}); - private DelegateCommand changeBaseColorTheme; + //private DelegateCommand changeBaseColorTheme; - public DelegateCommand ChangeBaseColorTheme => changeBaseColorTheme ??= new DelegateCommand(obj => - { - string mainTheme = obj; + //public DelegateCommand ChangeBaseColorTheme => changeBaseColorTheme ??= new DelegateCommand(obj => + //{ + //string mainTheme = obj; - if (mainTheme == null) return; + //if (mainTheme == null) return; - ChangeBaseTheme(mainTheme); + //ChangeBaseTheme(mainTheme); - if (!Settings.Default.ChangeBlocklyThemeToggleSwitchState) - { - if (mainTheme == "Dark") - { - SetBlocklyThemeAndGridColor(BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == BlocklyTheme.Dark)); - } - else if (mainTheme == "Light") - { - SetBlocklyThemeAndGridColor(BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == BlocklyTheme.Classic)); - } - } - }); - - #endregion - - #region Action + //if (!Settings.Default.ChangeBlocklyThemeToggleSwitchState) + //{ + // if (mainTheme == "Dark") + // { + // SetBlocklyThemeAndGridColor(BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == BlocklyTheme.Dark)); + // } + // else if (mainTheme == "Light") + // { + // SetBlocklyThemeAndGridColor(BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == BlocklyTheme.Classic)); + // } + //} + //}); - public static Action ChangeNotificationOpacity { get; set; } - public static Action ChangeBaseTheme { get; set; } - public static Action ChangeThemeColorScheme { get; set; } - //public static Action OpenAdvancedBlocklySettings { get; set; } - public static Action SetToolboxLanguage { get; set; } - public static Action SetBlocklyThemeAndGridColor { get; set; } - - #endregion } } diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs index 36ced35..2f3acb9 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs @@ -3,6 +3,7 @@ using AdamController.Core.Model; using AdamController.Core.Properties; using AdamController.Modules.ContentRegion.ViewModels; +using AdamController.Services.Interfaces; using Microsoft.Web.WebView2.Core; using Newtonsoft.Json; using System; @@ -39,7 +40,6 @@ public static ScratchControlView Instance #endregion #region Action - public static Action NavigationComplete { get; set; } public static Action WebMessageReceived { get; set; } @@ -48,9 +48,11 @@ public static ScratchControlView Instance private readonly string mPathToSource = Path.Combine(FolderHelper.CommonDirAppData, "BlocklySource"); private readonly string mPath = Path.Combine(Path.GetTempPath(), "AdamBrowser"); + public ScratchControlView() { mInstance = this; + InitializeComponent(); WebView.CoreWebView2InitializationCompleted += WebViewCoreWebView2InitializationCompleted; @@ -61,12 +63,15 @@ public ScratchControlView() TextResulEditor.TextChanged += TextResulEditorTextChanged; - if (ScratchControlViewModel.ReloadWebView == null) + ScratchControlViewModel viewModel = DataContext as ScratchControlViewModel; + + if (viewModel.ReloadWebView == null) { - ScratchControlViewModel.ReloadWebView = new Action(() => WebView.CoreWebView2.Reload()); + viewModel.ReloadWebView = new Action(() => WebView?.CoreWebView2?.Reload()); } } + private void TextResulEditorTextChanged(object sender, EventArgs e) { Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => diff --git a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml index 9436142..4448d33 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml @@ -6,7 +6,7 @@ xmlns:controlzex="urn:controlzex" xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase" xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" - xmlns:localConverter="clr-namespace:AdamController.Core.Converters;assembly=AdamController.Core" + xmlns:converter="clr-namespace:AdamController.Core.Converters;assembly=AdamController.Core" xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks" xmlns:properties="clr-namespace:AdamController.Core.Properties;assembly=AdamController.Core" xmlns:prism="http://prismlibrary.com/" @@ -79,9 +79,8 @@ VerticalAlignment="Center" Content="Темная" Margin="20 5 10 10" - Command="{Binding ChangeBaseColorTheme}" + Command="{Binding ChangeBaseThemeDelegateCommand}" CommandParameter="Dark" - Style="{DynamicResource MahApps.Styles.Button}" Background="{DynamicResource MahApps.Brushes.ThemeBackground}" Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}" @@ -92,9 +91,8 @@ Margin="10 5 20 10" HorizontalAlignment="Stretch" VerticalAlignment="Center" - Command="{Binding ChangeBaseColorTheme}" + Command="{Binding ChangeBaseThemeDelegateCommand}" CommandParameter="Light" - Style="{DynamicResource MahApps.Styles.Button}" Background="{DynamicResource MahApps.Brushes.ThemeBackground}" Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}" @@ -471,7 +469,7 @@ /// true is connected, false disconetcted, null reconected /// - private void SetStatusConnection(bool? connectionStatus, int reconnectCounter = 0) + private void UpdateStatusConnection(bool? connectionStatus, int reconnectCounter = 0) { if (connectionStatus == true) { @@ -186,17 +184,17 @@ private void Unsubscribe() private void OnRaiseTcpServiceCientConnected(object sender) { - SetStatusConnection(true); + UpdateStatusConnection(true); } private void OnRaiseTcpServiceClientReconnected(object sender, int reconnectCounter) { - SetStatusConnection(null, reconnectCounter); + UpdateStatusConnection(null, reconnectCounter); } private void OnRaiseTcpServiceClientDisconnect(object sender) { - SetStatusConnection(false); + UpdateStatusConnection(false); } #endregion From cb5dbf8800e6f2ba588111d9167794bc5a6773bd Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Wed, 17 Apr 2024 10:26:42 +1000 Subject: [PATCH 092/181] Fix #26 p1 --- .../Interfaces/IWebViewProvider.cs | 37 ++++++ AdamController.Services/WebViewProvider.cs | 69 +++++++++++ .../WebMessageJsonReceived.cs | 14 +++ AdamController/App.xaml.cs | 8 +- .../ViewModels/ScratchControlViewModel.cs | 109 +++++++++++------ .../Views/ScratchControlView.xaml | 12 +- .../Views/ScratchControlView.xaml.cs | 112 +++++++++++------- 7 files changed, 275 insertions(+), 86 deletions(-) create mode 100644 AdamController.Services/Interfaces/IWebViewProvider.cs create mode 100644 AdamController.Services/WebViewProvider.cs create mode 100644 AdamController.Services/WebViewProviderDependency/WebMessageJsonReceived.cs diff --git a/AdamController.Services/Interfaces/IWebViewProvider.cs b/AdamController.Services/Interfaces/IWebViewProvider.cs new file mode 100644 index 0000000..48f8777 --- /dev/null +++ b/AdamController.Services/Interfaces/IWebViewProvider.cs @@ -0,0 +1,37 @@ +using AdamController.Services.WebViewProviderDependency; +using System; +using System.Threading.Tasks; + +namespace AdamController.Services.Interfaces +{ + #region Delegate + + /*event in view model*/ + public delegate void WebViewNavigationCompleteEventHandler(object sender); + public delegate void WebViewbMessageReceivedEventHandler(object sender, WebMessageJsonReceived webMessageReceived); + + /*event in view */ + public delegate Task ExecuteJavaScriptEventHandler(object sender, string script); + public delegate void ExecuteReloadWebViewEventHandler(object sender); + + #endregion + + public interface IWebViewProvider : IDisposable + { + /*event in view model*/ + public event WebViewNavigationCompleteEventHandler RaiseWebViewNavigationCompleteEvent; + public event WebViewbMessageReceivedEventHandler RaiseWebViewMessageReceivedEvent; + + /*event in view */ + public event ExecuteJavaScriptEventHandler RaiseExecuteJavaScriptEvent; + public event ExecuteReloadWebViewEventHandler RaiseExecuteReloadWebViewEvent; + + public Task ExecuteJavaScript(string script); + + /* in view model */ + public void ReloadWebView(); + public void NavigationComplete(); + + public void WebViewMessageReceived(WebMessageJsonReceived receivedResult); + } +} diff --git a/AdamController.Services/WebViewProvider.cs b/AdamController.Services/WebViewProvider.cs new file mode 100644 index 0000000..734890a --- /dev/null +++ b/AdamController.Services/WebViewProvider.cs @@ -0,0 +1,69 @@ +using AdamController.Services.Interfaces; +using AdamController.Services.WebViewProviderDependency; +using System.Threading.Tasks; + +namespace AdamController.Services +{ + public class WebViewProvider : IWebViewProvider + { + /*event in view model*/ + public event WebViewNavigationCompleteEventHandler RaiseWebViewNavigationCompleteEvent; + public event WebViewbMessageReceivedEventHandler RaiseWebViewMessageReceivedEvent; + + /*event in view */ + public event ExecuteJavaScriptEventHandler RaiseExecuteJavaScriptEvent; + public event ExecuteReloadWebViewEventHandler RaiseExecuteReloadWebViewEvent; + + public void Dispose() + { + + } + + public void WebViewMessageReceived(WebMessageJsonReceived receivedResult) + { + OnRaiseWebViewbMessageReceivedEvent(receivedResult); + } + + public Task ExecuteJavaScript(string script) + { + return OnRaiseExecuteJavaScriptEvent(script); + } + + public void NavigationComplete() + { + OnRaiseWebViewNavigationCompleteEvent(); + } + + public virtual void ReloadWebView() + { + OnRaiseExecuteReloadWebViewEvent(); + } + + protected virtual void OnRaiseWebViewNavigationCompleteEvent() + { + WebViewNavigationCompleteEventHandler raiseEvent = RaiseWebViewNavigationCompleteEvent; + raiseEvent?.Invoke(this); + } + + + protected virtual void OnRaiseWebViewbMessageReceivedEvent(WebMessageJsonReceived result) + { + WebViewbMessageReceivedEventHandler raiseEvent = RaiseWebViewMessageReceivedEvent; + raiseEvent?.Invoke(this, result); + } + + protected virtual Task OnRaiseExecuteJavaScriptEvent(string script) + { + ExecuteJavaScriptEventHandler raiseEvent = RaiseExecuteJavaScriptEvent; + return raiseEvent?.Invoke(this, script); + } + + protected virtual void OnRaiseExecuteReloadWebViewEvent() + { + ExecuteReloadWebViewEventHandler raiseEvent = RaiseExecuteReloadWebViewEvent; + raiseEvent?.Invoke(this); + } + + + } +} diff --git a/AdamController.Services/WebViewProviderDependency/WebMessageJsonReceived.cs b/AdamController.Services/WebViewProviderDependency/WebMessageJsonReceived.cs new file mode 100644 index 0000000..b7132fb --- /dev/null +++ b/AdamController.Services/WebViewProviderDependency/WebMessageJsonReceived.cs @@ -0,0 +1,14 @@ +using Newtonsoft.Json; +using System; + +namespace AdamController.Services.WebViewProviderDependency +{ + public class WebMessageJsonReceived : EventArgs + { + [JsonProperty("action")] + public string Action { get; set; } + + [JsonProperty("data")] + public string Data { get; set; } + } +} diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 1b6a00e..df9c6bb 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -95,6 +95,12 @@ protected override void OnInitialized() protected override void RegisterTypes(IContainerRegistry containerRegistry) { + containerRegistry.RegisterSingleton(containerRegistry => + { + return new WebViewProvider(); + }); + + containerRegistry.RegisterSingleton(containerRegistry => { return new SubRegionChangeAwareService(); @@ -192,8 +198,6 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return remoteRunnerService; }); - - RegisterDialogs(containerRegistry); } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index fb3b8ff..5bc4a9a 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -5,12 +5,13 @@ using AdamBlocklyLibrary.ToolboxSets; using AdamController.Core; using AdamController.Core.Helpers; -using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Core.Properties; using AdamController.Modules.ContentRegion.Views; using AdamController.Services.Interfaces; +using AdamController.Services.WebViewProviderDependency; using AdamController.WebApi.Client.v1; +using ControlzEx.Standard; using MessageDialogManagerLib; using Newtonsoft.Json; using Prism.Commands; @@ -32,13 +33,15 @@ public class ScratchControlViewModel : RegionViewModelBase private readonly ICommunicationProviderService mCommunicationProvider; private readonly IPythonRemoteRunnerService mPythonRemoteRunner; private readonly IStatusBarNotificationDeliveryService mStatusBarNotificationDelivery; + private readonly IWebViewProvider mWebViewProvider; + #endregion #region Action field public static Action SendSourceToScriptEditor { get; set; } - public Action ReloadWebView { get; set; } + //public Action ReloadWebView { get; set; } #endregion @@ -46,15 +49,16 @@ public class ScratchControlViewModel : RegionViewModelBase private bool mIsWarningStackOwerflowAlreadyShow; public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, - IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery) : base(regionManager, dialogService) + IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IWebViewProvider webViewProvider) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; mPythonRemoteRunner = pythonRemoteRunner; mStatusBarNotificationDelivery = statusBarNotificationDelivery; + mWebViewProvider = webViewProvider; IDialogManager = new MessageDialogManagerMahapps(Application.Current); - InitAction(); + //InitAction(); } #region Navigation @@ -73,11 +77,27 @@ public override void OnNavigatedTo(NavigationContext navigationContext) mPythonRemoteRunner.RaisePythonStandartOutputEvent += OnRaisePythonStandartOutput; mPythonRemoteRunner.RaisePythonScriptExecuteFinishEvent += OnRaisePythonScriptExecuteFinish; - ReloadWebViewCommand.Execute(); + mWebViewProvider.RaiseWebViewMessageReceivedEvent += RaiseWebViewbMessageReceivedEvent; + mWebViewProvider.RaiseWebViewNavigationCompleteEvent += RaiseWebViewNavigationCompleteEvent; + //ReloadWebViewCommand.Execute(); base.OnNavigatedTo(navigationContext); } + private void RaiseWebViewNavigationCompleteEvent(object sender) + { + InitBlockly(); + //throw new NotImplementedException(); + } + + private void RaiseWebViewbMessageReceivedEvent(object sender, WebMessageJsonReceived webMessageReceived) + { + if (webMessageReceived.Action == "sendSourceCode") + { + SourceTextEditor = webMessageReceived.Data; + } + } + public override void OnNavigatedFrom(NavigationContext navigationContext) { mCommunicationProvider.RaiseTcpServiceCientConnectedEvent -= OnRaiseTcpServiceCientConnected; @@ -87,6 +107,9 @@ public override void OnNavigatedFrom(NavigationContext navigationContext) mPythonRemoteRunner.RaisePythonStandartOutputEvent -= OnRaisePythonStandartOutput; mPythonRemoteRunner.RaisePythonScriptExecuteFinishEvent -= OnRaisePythonScriptExecuteFinish; + mWebViewProvider.RaiseWebViewMessageReceivedEvent -= RaiseWebViewbMessageReceivedEvent; + mWebViewProvider.RaiseWebViewNavigationCompleteEvent -= RaiseWebViewNavigationCompleteEvent; + base.OnNavigatedFrom(navigationContext); } @@ -164,11 +187,11 @@ private void UpdatePythonInfo(string pythonVersion = "", string pythonBinPath = #region Action initialize - private void InitAction() - { - ScratchControlView.NavigationComplete ??= new Action(NavigationComplete); - ScratchControlView.WebMessageReceived ??= new Action(WebMessageReceived); - } + //private void InitAction() + //{ + // ScratchControlView.NavigationComplete ??= new Action(NavigationComplete); + // ScratchControlView.WebMessageReceived ??= new Action(WebMessageReceived); + //} #endregion @@ -188,7 +211,8 @@ private async void StartExecuteProgram() await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(async () => { - await ScratchControlView.ExecuteScript(Scripts.ShadowEnable); + await mWebViewProvider.ExecuteJavaScript(Scripts.ShadowEnable); + //await ScratchControlView.ExecuteScript(Scripts.ShadowEnable); })); } @@ -201,7 +225,8 @@ private async void OnStopExecuteProgram(string compileLogStatusBarAction) { await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(async () => { - await ScratchControlView.ExecuteScript(Scripts.ShadowDisable); + await mWebViewProvider.ExecuteJavaScript(Scripts.ShadowDisable); + //await ScratchControlView.ExecuteScript(Scripts.ShadowDisable); })); mStatusBarNotificationDelivery.CompileLogMessage = compileLogStatusBarAction; @@ -213,13 +238,13 @@ private async void OnStopExecuteProgram(string compileLogStatusBarAction) #endregion - private void WebMessageReceived(WebMessageJsonReceived results) - { - if (results.Action == "sendSourceCode") - { - SourceTextEditor = results.Data; - } - } + //private void WebMessageReceived(WebMessageJsonReceived results) + //{ + // if (results.Action == "sendSourceCode") + // { + // SourceTextEditor = results.Data; + // } + //} #region IsEnabled buttons field @@ -244,10 +269,10 @@ public bool IsEnabledShowOpenDialogButton /// /// Run js-script after web view navigation complete /// - private void NavigationComplete() - { - InitBlockly(); - } + //private void NavigationComplete() + //{ + // InitBlockly(); + // } private async void InitBlockly() { @@ -259,13 +284,19 @@ private async void InitBlockly() { await LoadBlocklySrc(); await LoadBlocklyBlockLocalLangSrc(language); - _ = await ScratchControlView.ExecuteScript(InitWorkspace()); - _ = await ScratchControlView.ExecuteScript(Scripts.ListenerCreatePythonCode); - _ = await ScratchControlView.ExecuteScript(Scripts.ListenerSavedBlocks); + + await mWebViewProvider.ExecuteJavaScript(InitWorkspace()); + await mWebViewProvider.ExecuteJavaScript(Scripts.ListenerCreatePythonCode); + await mWebViewProvider.ExecuteJavaScript(Scripts.ListenerSavedBlocks); + + //_ = await ScratchControlView.ExecuteScript(InitWorkspace()); + //_ = await ScratchControlView.ExecuteScript(Scripts.ListenerCreatePythonCode); + //_ = await ScratchControlView.ExecuteScript(Scripts.ListenerSavedBlocks); if (Settings.Default.BlocklyRestoreBlockOnLoad) { - _ = await ScratchControlView.ExecuteScript(Scripts.RestoreSavedBlocks); + await mWebViewProvider.ExecuteJavaScript(Scripts.RestoreSavedBlocks); + //_ = await ScratchControlView.ExecuteScript(Scripts.RestoreSavedBlocks); } @@ -427,15 +458,18 @@ private async Task LoadBlocklySrc() Scripts.AdamCommonPytnonGenSrc }); - _ = await ScratchControlView.ExecuteScript(loadLocalSrc); + await mWebViewProvider.ExecuteJavaScript(loadLocalSrc); + //_ = await ScratchControlView.ExecuteScript(loadLocalSrc); //Thread.Sleep(1000); - Thread.Sleep(500); - _ = await ScratchControlView.ExecuteScript(loadLocalAdamBlockSrc); + //Thread.Sleep(500); + await mWebViewProvider.ExecuteJavaScript(loadLocalAdamBlockSrc); + //_ = await ScratchControlView.ExecuteScript(loadLocalAdamBlockSrc); //Thread.Sleep(1000); - Thread.Sleep(500); - _ = await ScratchControlView.ExecuteScript(loadLocalAdamPythonGenSrc); + //Thread.Sleep(500); + await mWebViewProvider.ExecuteJavaScript(loadLocalAdamPythonGenSrc); + //_ = await ScratchControlView.ExecuteScript(loadLocalAdamPythonGenSrc); } /// @@ -554,7 +588,8 @@ public string SourceTextEditor public DelegateCommand ReloadWebViewCommand => reloadWebViewCommand ??= new DelegateCommand(() => { SourceTextEditor = string.Empty; - ReloadWebView(); + mWebViewProvider.ReloadWebView(); + //ReloadWebView(); }); private DelegateCommand sendToExternalSourceEditor; @@ -567,7 +602,8 @@ public string SourceTextEditor private DelegateCommand showSaveFileDialogCommand; public DelegateCommand ShowSaveFileDialogCommand => showSaveFileDialogCommand ??= new DelegateCommand(async () => { - string workspace = await ScratchControlView.ExecuteScript("getSavedWorkspace()"); + string workspace = await mWebViewProvider.ExecuteJavaScript("getSavedWorkspace()"); + //string workspace = await ScratchControlView.ExecuteScript("getSavedWorkspace()"); string xmlWorkspace = JsonConvert.DeserializeObject(workspace); if (IDialogManager.ShowSaveFileDialog("Сохранить рабочую область", Settings.Default.SavedUserWorkspaceFolderPath, "workspace", ".xml", "XML documents (.xml)|*.xml")) @@ -707,10 +743,11 @@ await Task.Run(() => #region ExecuteScripts - private static async Task ExecuteScriptFunctionAsync(string functionName, params object[] parameters) + private async Task ExecuteScriptFunctionAsync(string functionName, params object[] parameters) { string script = Scripts.SerealizeObject(functionName, parameters); - return await ScratchControlView.ExecuteScript(script); + return await mWebViewProvider.ExecuteJavaScript(script); + //return await ScratchControlView.ExecuteScript(script); } #endregion diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml index 27815a9..3cdbc5a 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml @@ -24,9 +24,9 @@ + Mode=TwoWay, + Converter={StaticResource GridLengthConverter}, + Source={x:Static properties:Settings.Default }}"/> @@ -34,9 +34,9 @@ + Mode=TwoWay, + Converter={StaticResource GridLengthConverter}, + Source={x:Static properties:Settings.Default }}"/> diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs index 2f3acb9..42f7dd9 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs @@ -1,9 +1,9 @@  using AdamController.Core.Helpers; -using AdamController.Core.Model; using AdamController.Core.Properties; using AdamController.Modules.ContentRegion.ViewModels; using AdamController.Services.Interfaces; +using AdamController.Services.WebViewProviderDependency; using Microsoft.Web.WebView2.Core; using Newtonsoft.Json; using System; @@ -19,65 +19,88 @@ public partial class ScratchControlView : UserControl { #region Singelton - private static ScratchControlView mInstance = null; - private static readonly object padlock = new(); - - public static ScratchControlView Instance - { - get - { - lock (padlock) - { - if (mInstance == null) - { - mInstance = new ScratchControlView(); - } - return mInstance; - } - } - } + //private static ScratchControlView mInstance = null; + //private static readonly object padlock = new(); + + //public static ScratchControlView Instance + //{ + // get + // { + // lock (padlock) + // { + // if (mInstance == null) + // { + // mInstance = new ScratchControlView(); + // } + // return mInstance; + // } + // } + //} #endregion #region Action - public static Action NavigationComplete { get; set; } - public static Action WebMessageReceived { get; set; } + //public static Action NavigationComplete { get; set; } + //public static Action WebMessageReceived { get; set; } + + #endregion + + #region Services + private readonly IWebViewProvider mWebViewProvider; #endregion private readonly string mPathToSource = Path.Combine(FolderHelper.CommonDirAppData, "BlocklySource"); private readonly string mPath = Path.Combine(Path.GetTempPath(), "AdamBrowser"); - public ScratchControlView() + public ScratchControlView(IWebViewProvider webViewProvider) { - mInstance = this; + //mInstance = this; InitializeComponent(); + InitializeWebViewCore(); + + mWebViewProvider = webViewProvider; WebView.CoreWebView2InitializationCompleted += WebViewCoreWebView2InitializationCompleted; WebView.NavigationCompleted += WebViewNavigationCompleted; WebView.WebMessageReceived += WebViewWebMessageReceived; - - InitializeWebViewCore(); + + mWebViewProvider.RaiseExecuteJavaScriptEvent += RaiseExecuteJavaScriptEvent; + mWebViewProvider.RaiseExecuteReloadWebViewEvent += RaiseExecuteReloadWebViewEvent; TextResulEditor.TextChanged += TextResulEditorTextChanged; - ScratchControlViewModel viewModel = DataContext as ScratchControlViewModel; + //ScratchControlViewModel viewModel = DataContext as ScratchControlViewModel; - if (viewModel.ReloadWebView == null) - { - viewModel.ReloadWebView = new Action(() => WebView?.CoreWebView2?.Reload()); - } + //if (viewModel.ReloadWebView == null) + //{ + // viewModel.ReloadWebView = new Action(() => WebView?.CoreWebView2?.Reload()); + //} + } + + private void RaiseExecuteReloadWebViewEvent(object sender) + { + WebView.CoreWebView2.Reload(); + } + + private async Task RaiseExecuteJavaScriptEvent(object sender, string script) + { + string result = await WebView.ExecuteScriptAsync(script); + return result; + //string result = await ExecuteScripts(script);//WebView.ExecuteScriptAsync(script).Result; + //return result; } + private void WebViewNavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e) + { + mWebViewProvider.NavigationComplete(); + } private void TextResulEditorTextChanged(object sender, EventArgs e) { - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => - { - TextResulEditor.ScrollToEnd(); - })); + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(TextResulEditor.ScrollToEnd)); } private async void InitializeWebViewCore() @@ -99,21 +122,26 @@ private void WebViewCoreWebView2InitializationCompleted(object sender, CoreWebVi #region Func - public static Func> ExecuteScript = async script => await mInstance.ExecuteScripts(script); + //public static Func> ExecuteScript = async script => await mInstance.ExecuteScripts(script); - public async Task ExecuteScripts(string script) - { - string result = await WebView.ExecuteScriptAsync(script); - return result; - } + //public async Task ExecuteScripts(string script) + //{ + // string result = await WebView.ExecuteScriptAsync(script); + // return result; + //} #endregion - private void WebViewNavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e) => NavigationComplete(); + //private void WebViewNavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e) => NavigationComplete(); private void WebViewWebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e) { - ParseJsonReceived(e.WebMessageAsJson); + dynamic jsonClean = JsonConvert.DeserializeObject(e.WebMessageAsJson); + WebMessageJsonReceived receivedResult = JsonConvert.DeserializeObject(jsonClean); + if (receivedResult == null) return; + + mWebViewProvider.WebViewMessageReceived(receivedResult); + //ParseJsonReceived(e.WebMessageAsJson); } private async void ParseJsonReceived(string json) @@ -124,7 +152,7 @@ private async void ParseJsonReceived(string json) WebMessageJsonReceived results = JsonConvert.DeserializeObject(jsonClean); if (results == null) return; - WebMessageReceived(results); + //WebMessageReceived(results); })); } } From 90bb4b233d8c5077837cdf4f040134c3390c98b6 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Wed, 17 Apr 2024 10:36:23 +1000 Subject: [PATCH 093/181] Fix #26 p2 --- .../ViewModels/ScratchControlViewModel.cs | 50 -------------- .../Views/ScratchControlView.xaml.cs | 66 +------------------ 2 files changed, 1 insertion(+), 115 deletions(-) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index 5bc4a9a..18c6957 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -18,7 +18,6 @@ using Prism.Regions; using Prism.Services.Dialogs; using System; -using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; @@ -35,13 +34,11 @@ public class ScratchControlViewModel : RegionViewModelBase private readonly IStatusBarNotificationDeliveryService mStatusBarNotificationDelivery; private readonly IWebViewProvider mWebViewProvider; - #endregion #region Action field public static Action SendSourceToScriptEditor { get; set; } - //public Action ReloadWebView { get; set; } #endregion @@ -57,8 +54,6 @@ public ScratchControlViewModel(IRegionManager regionManager, IDialogService dial mWebViewProvider = webViewProvider; IDialogManager = new MessageDialogManagerMahapps(Application.Current); - - //InitAction(); } #region Navigation @@ -79,7 +74,6 @@ public override void OnNavigatedTo(NavigationContext navigationContext) mWebViewProvider.RaiseWebViewMessageReceivedEvent += RaiseWebViewbMessageReceivedEvent; mWebViewProvider.RaiseWebViewNavigationCompleteEvent += RaiseWebViewNavigationCompleteEvent; - //ReloadWebViewCommand.Execute(); base.OnNavigatedTo(navigationContext); } @@ -185,16 +179,6 @@ private void UpdatePythonInfo(string pythonVersion = "", string pythonBinPath = PythonWorkDir = $"Рабочая дирректория {pythonWorkDir}"; } - #region Action initialize - - //private void InitAction() - //{ - // ScratchControlView.NavigationComplete ??= new Action(NavigationComplete); - // ScratchControlView.WebMessageReceived ??= new Action(WebMessageReceived); - //} - - #endregion - #region Execute program event private async void StartExecuteProgram() @@ -226,7 +210,6 @@ private async void OnStopExecuteProgram(string compileLogStatusBarAction) await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(async () => { await mWebViewProvider.ExecuteJavaScript(Scripts.ShadowDisable); - //await ScratchControlView.ExecuteScript(Scripts.ShadowDisable); })); mStatusBarNotificationDelivery.CompileLogMessage = compileLogStatusBarAction; @@ -238,14 +221,6 @@ private async void OnStopExecuteProgram(string compileLogStatusBarAction) #endregion - //private void WebMessageReceived(WebMessageJsonReceived results) - //{ - // if (results.Action == "sendSourceCode") - // { - // SourceTextEditor = results.Data; - // } - //} - #region IsEnabled buttons field private bool isEnabledStopExecuteButton = false; @@ -266,14 +241,6 @@ public bool IsEnabledShowOpenDialogButton #region Initialize Blockly - /// - /// Run js-script after web view navigation complete - /// - //private void NavigationComplete() - //{ - // InitBlockly(); - // } - private async void InitBlockly() { BlocklyLanguage language = Settings.Default.BlocklyWorkspaceLanguage; @@ -289,14 +256,9 @@ private async void InitBlockly() await mWebViewProvider.ExecuteJavaScript(Scripts.ListenerCreatePythonCode); await mWebViewProvider.ExecuteJavaScript(Scripts.ListenerSavedBlocks); - //_ = await ScratchControlView.ExecuteScript(InitWorkspace()); - //_ = await ScratchControlView.ExecuteScript(Scripts.ListenerCreatePythonCode); - //_ = await ScratchControlView.ExecuteScript(Scripts.ListenerSavedBlocks); - if (Settings.Default.BlocklyRestoreBlockOnLoad) { await mWebViewProvider.ExecuteJavaScript(Scripts.RestoreSavedBlocks); - //_ = await ScratchControlView.ExecuteScript(Scripts.RestoreSavedBlocks); } @@ -459,17 +421,8 @@ private async Task LoadBlocklySrc() }); await mWebViewProvider.ExecuteJavaScript(loadLocalSrc); - //_ = await ScratchControlView.ExecuteScript(loadLocalSrc); - - //Thread.Sleep(1000); - //Thread.Sleep(500); await mWebViewProvider.ExecuteJavaScript(loadLocalAdamBlockSrc); - //_ = await ScratchControlView.ExecuteScript(loadLocalAdamBlockSrc); - - //Thread.Sleep(1000); - //Thread.Sleep(500); await mWebViewProvider.ExecuteJavaScript(loadLocalAdamPythonGenSrc); - //_ = await ScratchControlView.ExecuteScript(loadLocalAdamPythonGenSrc); } /// @@ -589,7 +542,6 @@ public string SourceTextEditor { SourceTextEditor = string.Empty; mWebViewProvider.ReloadWebView(); - //ReloadWebView(); }); private DelegateCommand sendToExternalSourceEditor; @@ -603,7 +555,6 @@ public string SourceTextEditor public DelegateCommand ShowSaveFileDialogCommand => showSaveFileDialogCommand ??= new DelegateCommand(async () => { string workspace = await mWebViewProvider.ExecuteJavaScript("getSavedWorkspace()"); - //string workspace = await ScratchControlView.ExecuteScript("getSavedWorkspace()"); string xmlWorkspace = JsonConvert.DeserializeObject(workspace); if (IDialogManager.ShowSaveFileDialog("Сохранить рабочую область", Settings.Default.SavedUserWorkspaceFolderPath, "workspace", ".xml", "XML documents (.xml)|*.xml")) @@ -747,7 +698,6 @@ private async Task ExecuteScriptFunctionAsync(string functionName, param { string script = Scripts.SerealizeObject(functionName, parameters); return await mWebViewProvider.ExecuteJavaScript(script); - //return await ScratchControlView.ExecuteScript(script); } #endregion diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs index 42f7dd9..a02a43c 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs @@ -17,37 +17,10 @@ namespace AdamController.Modules.ContentRegion.Views { public partial class ScratchControlView : UserControl { - #region Singelton - - //private static ScratchControlView mInstance = null; - //private static readonly object padlock = new(); - - //public static ScratchControlView Instance - //{ - // get - // { - // lock (padlock) - // { - // if (mInstance == null) - // { - // mInstance = new ScratchControlView(); - // } - // return mInstance; - // } - // } - //} - - #endregion - - #region Action - //public static Action NavigationComplete { get; set; } - //public static Action WebMessageReceived { get; set; } - - #endregion - #region Services private readonly IWebViewProvider mWebViewProvider; + #endregion private readonly string mPathToSource = Path.Combine(FolderHelper.CommonDirAppData, "BlocklySource"); @@ -56,8 +29,6 @@ public partial class ScratchControlView : UserControl public ScratchControlView(IWebViewProvider webViewProvider) { - //mInstance = this; - InitializeComponent(); InitializeWebViewCore(); @@ -71,13 +42,6 @@ public ScratchControlView(IWebViewProvider webViewProvider) mWebViewProvider.RaiseExecuteReloadWebViewEvent += RaiseExecuteReloadWebViewEvent; TextResulEditor.TextChanged += TextResulEditorTextChanged; - - //ScratchControlViewModel viewModel = DataContext as ScratchControlViewModel; - - //if (viewModel.ReloadWebView == null) - //{ - // viewModel.ReloadWebView = new Action(() => WebView?.CoreWebView2?.Reload()); - //} } private void RaiseExecuteReloadWebViewEvent(object sender) @@ -89,8 +53,6 @@ private async Task RaiseExecuteJavaScriptEvent(object sender, string scr { string result = await WebView.ExecuteScriptAsync(script); return result; - //string result = await ExecuteScripts(script);//WebView.ExecuteScriptAsync(script).Result; - //return result; } private void WebViewNavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e) @@ -120,19 +82,6 @@ private void WebViewCoreWebView2InitializationCompleted(object sender, CoreWebVi WebView.CoreWebView2.Navigate("https://localhost/index.html"); } - #region Func - - //public static Func> ExecuteScript = async script => await mInstance.ExecuteScripts(script); - - //public async Task ExecuteScripts(string script) - //{ - // string result = await WebView.ExecuteScriptAsync(script); - // return result; - //} - - #endregion - - //private void WebViewNavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e) => NavigationComplete(); private void WebViewWebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e) { @@ -141,19 +90,6 @@ private void WebViewWebMessageReceived(object sender, CoreWebView2WebMessageRece if (receivedResult == null) return; mWebViewProvider.WebViewMessageReceived(receivedResult); - //ParseJsonReceived(e.WebMessageAsJson); - } - - private async void ParseJsonReceived(string json) - { - await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => - { - dynamic jsonClean = JsonConvert.DeserializeObject(json); - WebMessageJsonReceived results = JsonConvert.DeserializeObject(jsonClean); - if (results == null) return; - - //WebMessageReceived(results); - })); } } From 898b67ba307960b5fde6ce0e2d55cb5c072a8f55 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Wed, 17 Apr 2024 15:34:05 +1000 Subject: [PATCH 094/181] Fix #26 p3 p4 p5 --- .../Model/WebMessageJsonReceived.cs | 13 - .../NavigationParametersKey.cs | 7 + AdamController.Services/DialogManager.cs | 11 + .../Interfaces/IDialogManagerService.cs | 9 + .../Interfaces/IWebViewProvider.cs | 1 - AdamController/App.xaml.cs | 8 + .../ViewModels/MainWindowViewModel.cs | 3 +- AdamController/Views/MainWindow.xaml | 32 +- .../ViewModels/ScratchControlViewModel.cs | 748 ++++++++++-------- .../ScriptEditorControlViewModel.cs | 11 +- .../VisualSettingsControlViewModel.cs | 11 +- .../Views/ScratchControlView.xaml | 93 +-- .../Views/ScratchControlView.xaml.cs | 3 +- .../Views/StatusBarView.xaml | 3 +- 14 files changed, 543 insertions(+), 410 deletions(-) delete mode 100644 AdamController.Core/Model/WebMessageJsonReceived.cs create mode 100644 AdamController.Core/NavigationParametersKey.cs create mode 100644 AdamController.Services/DialogManager.cs create mode 100644 AdamController.Services/Interfaces/IDialogManagerService.cs diff --git a/AdamController.Core/Model/WebMessageJsonReceived.cs b/AdamController.Core/Model/WebMessageJsonReceived.cs deleted file mode 100644 index 170bb48..0000000 --- a/AdamController.Core/Model/WebMessageJsonReceived.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Newtonsoft.Json; - -namespace AdamController.Core.Model -{ - public class WebMessageJsonReceived - { - [JsonProperty("action")] - public string Action { get; set; } - - [JsonProperty("data")] - public string Data { get; set; } - } -} diff --git a/AdamController.Core/NavigationParametersKey.cs b/AdamController.Core/NavigationParametersKey.cs new file mode 100644 index 0000000..e424c4e --- /dev/null +++ b/AdamController.Core/NavigationParametersKey.cs @@ -0,0 +1,7 @@ +namespace AdamController.Core +{ + public class NavigationParametersKey + { + public const string SourceCode = nameof(SourceCode); + } +} diff --git a/AdamController.Services/DialogManager.cs b/AdamController.Services/DialogManager.cs new file mode 100644 index 0000000..f22f1d3 --- /dev/null +++ b/AdamController.Services/DialogManager.cs @@ -0,0 +1,11 @@ +using AdamController.Services.Interfaces; +using MessageDialogManagerLib; +using System.Windows; + +namespace AdamController.Services +{ + public class DialogManager : MessageDialogManagerMahapps, IDialogManagerService + { + public DialogManager(Application app) : base(app) {} + } +} diff --git a/AdamController.Services/Interfaces/IDialogManagerService.cs b/AdamController.Services/Interfaces/IDialogManagerService.cs new file mode 100644 index 0000000..5ce9104 --- /dev/null +++ b/AdamController.Services/Interfaces/IDialogManagerService.cs @@ -0,0 +1,9 @@ +using MessageDialogManagerLib; + +namespace AdamController.Services.Interfaces +{ + /// + /// The old dialog call type integrated into the service + /// + public interface IDialogManagerService : IMessageDialogManager {} +} diff --git a/AdamController.Services/Interfaces/IWebViewProvider.cs b/AdamController.Services/Interfaces/IWebViewProvider.cs index 48f8777..8e302a8 100644 --- a/AdamController.Services/Interfaces/IWebViewProvider.cs +++ b/AdamController.Services/Interfaces/IWebViewProvider.cs @@ -31,7 +31,6 @@ public interface IWebViewProvider : IDisposable /* in view model */ public void ReloadWebView(); public void NavigationComplete(); - public void WebViewMessageReceived(WebMessageJsonReceived receivedResult); } } diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index df9c6bb..0610043 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -224,6 +224,14 @@ private void StartWebApi() private static void RegisterDialogs(IContainerRegistry containerRegistry) { containerRegistry.RegisterDialog(); + + //The old dialog call type integrated into the service + containerRegistry.RegisterSingleton(containerRegistry => + { + var app = Current; + return new DialogManager(app); + }); + } protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings) diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index 0a21b85..31fb27a 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -29,8 +29,7 @@ public class MainWindowViewModel : ViewModelBase #region ~ public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService, - IStatusBarNotificationDeliveryService statusBarNotification, ICommunicationProviderService communicationProviderService) - + IStatusBarNotificationDeliveryService statusBarNotification, ICommunicationProviderService communicationProviderService) { RegionManager = regionManager; mSubRegionChangeAwareService = subRegionChangeAwareService; diff --git a/AdamController/Views/MainWindow.xaml b/AdamController/Views/MainWindow.xaml index 59c5bbf..1eb3017 100644 --- a/AdamController/Views/MainWindow.xaml +++ b/AdamController/Views/MainWindow.xaml @@ -72,7 +72,7 @@ - + @@ -89,14 +89,14 @@ - + - + - + - - + + - + - + @@ -151,7 +151,7 @@ - + - + @@ -176,18 +176,18 @@ Label="Настройки" Command="{Binding ShowRegionCommand}" CommandParameter="{x:Static core:SubRegionNames.SubRegionVisualSettings}"/> - + - + - + - + @@ -197,8 +197,4 @@ - - - - diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index 18c6957..8472275 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -11,8 +11,6 @@ using AdamController.Services.Interfaces; using AdamController.Services.WebViewProviderDependency; using AdamController.WebApi.Client.v1; -using ControlzEx.Standard; -using MessageDialogManagerLib; using Newtonsoft.Json; using Prism.Commands; using Prism.Regions; @@ -26,6 +24,19 @@ namespace AdamController.Modules.ContentRegion.ViewModels { public class ScratchControlViewModel : RegionViewModelBase { + #region DelegateCommands + + public DelegateCommand ReloadWebViewDelegateCommand { get; } + public DelegateCommand ShowSaveFileDialogDelegateCommand { get; } + public DelegateCommand ShowOpenFileDialogDelegateCommand { get; } + public DelegateCommand ShowSaveFileSourceTextDialogDelegateCommand { get; } + public DelegateCommand CleanExecuteEditorDelegateCommand { get; } + public DelegateCommand RunPythonCodeDelegateCommand { get; } + public DelegateCommand StopPythonCodeExecuteDelegateCommand { get; } + public DelegateCommand SendCodeToExternalSourceEditorDelegateCommand { get; } + public DelegateCommand ToZeroPositionDelegateCommand { get; } + + #endregion #region Services @@ -33,6 +44,19 @@ public class ScratchControlViewModel : RegionViewModelBase private readonly IPythonRemoteRunnerService mPythonRemoteRunner; private readonly IStatusBarNotificationDeliveryService mStatusBarNotificationDelivery; private readonly IWebViewProvider mWebViewProvider; + private readonly IDialogManagerService mDialogManager; + + #endregion + + #region Const + + private const string cFilter = "XML documents (.xml) | *.xml"; + + #endregion + + #region Var + + private bool mIsWarningStackOwerflowAlreadyShow; #endregion @@ -42,19 +66,28 @@ public class ScratchControlViewModel : RegionViewModelBase #endregion - private readonly IMessageDialogManager IDialogManager; - private bool mIsWarningStackOwerflowAlreadyShow; - public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, - IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IWebViewProvider webViewProvider) : base(regionManager, dialogService) + #region ~ + + public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IWebViewProvider webViewProvider, IDialogManagerService dialogManager) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; mPythonRemoteRunner = pythonRemoteRunner; mStatusBarNotificationDelivery = statusBarNotificationDelivery; mWebViewProvider = webViewProvider; - - IDialogManager = new MessageDialogManagerMahapps(Application.Current); + mDialogManager = dialogManager; + + ReloadWebViewDelegateCommand = new DelegateCommand(ReloadWebView, ReloadWebViewCanExecute); + ShowSaveFileDialogDelegateCommand = new DelegateCommand(ShowSaveFileDialog, ShowSaveFileDialogCanExecute); + ShowOpenFileDialogDelegateCommand = new DelegateCommand(ShowOpenFileDialog, ShowOpenFileDialogCanExecute); + ShowSaveFileSourceTextDialogDelegateCommand = new DelegateCommand(ShowSaveFileSourceTextDialog, ShowSaveFileSourceTextDialogCanExecute); + CleanExecuteEditorDelegateCommand = new DelegateCommand(CleanExecuteEditor, CleanExecuteEditorCanExecute); + RunPythonCodeDelegateCommand = new DelegateCommand(RunPythonCode, RunPythonCodeCanExecute); + StopPythonCodeExecuteDelegateCommand = new DelegateCommand(StopPythonCodeExecute, StopPythonCodeExecuteCanExecute); + SendCodeToExternalSourceEditorDelegateCommand = new(SendCodeToExternalSourceEditor, SendCodeToExternalSourceEditorCanExecute); + ToZeroPositionDelegateCommand = new DelegateCommand(ToZeroPosition, ToZeroPositionCanExecute); } + #endregion #region Navigation @@ -64,6 +97,27 @@ public override void ConfirmNavigationRequest(NavigationContext navigationContex } public override void OnNavigatedTo(NavigationContext navigationContext) + { + Subscribe(); + + //#29 + mWebViewProvider.ReloadWebView(); + + base.OnNavigatedTo(navigationContext); + } + + public override void OnNavigatedFrom(NavigationContext navigationContext) + { + Unsubscribe(); + + base.OnNavigatedFrom(navigationContext); + } + + #endregion + + #region Subscribes + + private void Subscribe() { mCommunicationProvider.RaiseTcpServiceCientConnectedEvent += OnRaiseTcpServiceCientConnected; mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent += OnRaiseTcperviceClientDisconnect; @@ -74,37 +128,359 @@ public override void OnNavigatedTo(NavigationContext navigationContext) mWebViewProvider.RaiseWebViewMessageReceivedEvent += RaiseWebViewbMessageReceivedEvent; mWebViewProvider.RaiseWebViewNavigationCompleteEvent += RaiseWebViewNavigationCompleteEvent; + } + + private void Unsubscribe() + { + mCommunicationProvider.RaiseTcpServiceCientConnectedEvent -= OnRaiseTcpServiceCientConnected; + mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent -= OnRaiseTcperviceClientDisconnect; + + mPythonRemoteRunner.RaisePythonScriptExecuteStartEvent -= OnRaisePythonScriptExecuteStart; + mPythonRemoteRunner.RaisePythonStandartOutputEvent -= OnRaisePythonStandartOutput; + mPythonRemoteRunner.RaisePythonScriptExecuteFinishEvent -= OnRaisePythonScriptExecuteFinish; + + mWebViewProvider.RaiseWebViewMessageReceivedEvent -= RaiseWebViewbMessageReceivedEvent; + mWebViewProvider.RaiseWebViewNavigationCompleteEvent -= RaiseWebViewNavigationCompleteEvent; - base.OnNavigatedTo(navigationContext); } - private void RaiseWebViewNavigationCompleteEvent(object sender) + #endregion + + #region DelegateCommand methods + + private void ReloadWebView() { - InitBlockly(); - //throw new NotImplementedException(); + SourceTextEditor = string.Empty; + mWebViewProvider.ReloadWebView(); } - private void RaiseWebViewbMessageReceivedEvent(object sender, WebMessageJsonReceived webMessageReceived) + private bool ReloadWebViewCanExecute() { - if (webMessageReceived.Action == "sendSourceCode") + return true; + } + + private async void ShowSaveFileDialog() + { + string workspace = await mWebViewProvider.ExecuteJavaScript("getSavedWorkspace()"); + string xmlWorkspace = JsonConvert.DeserializeObject(workspace); + string dialogTitle = "Сохранить рабочую область"; + string initialPath = Settings.Default.SavedUserWorkspaceFolderPath; + string fileName = "workspace"; + string defaultExt = ".xml"; + //string filter = "XML documents (.xml)|*.xml"; + + if (mDialogManager.ShowSaveFileDialog(dialogTitle, initialPath, fileName, defaultExt, cFilter)) { - SourceTextEditor = webMessageReceived.Data; + string path = mDialogManager.FilePathToSave; + await FileHelper.WriteAsync(path, xmlWorkspace); + + mStatusBarNotificationDelivery.AppLogMessage = $"Файл {mDialogManager.FilePathToSave} сохранен"; + } + else + { + mStatusBarNotificationDelivery.AppLogMessage = "Файл не сохранен"; } } - public override void OnNavigatedFrom(NavigationContext navigationContext) + private bool ShowSaveFileDialogCanExecute() { - mCommunicationProvider.RaiseTcpServiceCientConnectedEvent -= OnRaiseTcpServiceCientConnected; - mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent -= OnRaiseTcperviceClientDisconnect; + bool isSourceNotEmpty = SourceTextEditor?.Length > 0; + return isSourceNotEmpty; + } - mPythonRemoteRunner.RaisePythonScriptExecuteStartEvent -= OnRaisePythonScriptExecuteStart; - mPythonRemoteRunner.RaisePythonStandartOutputEvent -= OnRaisePythonStandartOutput; - mPythonRemoteRunner.RaisePythonScriptExecuteFinishEvent -= OnRaisePythonScriptExecuteFinish; + private async void ShowOpenFileDialog() + { + string title = "Выберите сохранененную рабочую область"; + string initialPath = Settings.Default.SavedUserWorkspaceFolderPath; - mWebViewProvider.RaiseWebViewMessageReceivedEvent -= RaiseWebViewbMessageReceivedEvent; - mWebViewProvider.RaiseWebViewNavigationCompleteEvent -= RaiseWebViewNavigationCompleteEvent; + if (mDialogManager.ShowFileBrowser(title, initialPath, cFilter)) + { + string path = mDialogManager.FilePath; + if (path == "") return; - base.OnNavigatedFrom(navigationContext); + string xml = await FileHelper.ReadTextAsStringAsync(path); + _ = await ExecuteScriptFunctionAsync("loadSavedWorkspace", new object[] { xml }); + + mStatusBarNotificationDelivery.AppLogMessage = $"Файл {path} загружен"; + } + else + { + mStatusBarNotificationDelivery.AppLogMessage = "Файл рабочей области не выбран"; + } + } + + private bool ShowOpenFileDialogCanExecute() + { + return true; + } + + private async void ShowSaveFileSourceTextDialog() + { + string pythonProgram = SourceTextEditor; + string title = "Сохранить файл программы"; + string initialPath = Settings.Default.SavedUserScriptsFolderPath; + string fileName = "new_program"; + string defaultExt = ".py"; + string filter = "PythonScript file (.py)|*.py|Все файлы|*.*"; + + + if (mDialogManager.ShowSaveFileDialog(title, initialPath, fileName, defaultExt, filter)) + { + string path = mDialogManager.FilePathToSave; + await FileHelper.WriteAsync(path, pythonProgram); + + mStatusBarNotificationDelivery.AppLogMessage = $"Файл {mDialogManager.FilePathToSave} сохранен"; + } + else + { + mStatusBarNotificationDelivery.AppLogMessage = "Файл не сохранен"; + } + } + + private bool ShowSaveFileSourceTextDialogCanExecute() + { + bool isSourceNotEmpty = SourceTextEditor?.Length > 0; + return isSourceNotEmpty; + } + + private void CleanExecuteEditor() + { + ResultTextEditorError = string.Empty; + ResultTextEditor = string.Empty; + } + + private bool CleanExecuteEditorCanExecute() + { + var isResultNotEmpty = ResultTextEditor?.Length > 0; + return isResultNotEmpty; + } + + private async void RunPythonCode() + { + ResultTextEditorError = string.Empty; + WebApi.Client.v1.ResponseModel.ExtendedCommandExecuteResult executeResult = new(); + + try + { + var command = new WebApi.Client.v1.RequestModel.PythonCommand + { + Command = SourceTextEditor + }; + + executeResult = await BaseApi.PythonExecuteAsync(command); + } + catch (Exception ex) + { + ResultTextEditorError = ex.Message.ToString(); + } + + if (Settings.Default.ChangeExtendedExecuteReportToggleSwitchState) + { + ResultTextEditor += "Отчет о инициализации процесса программы\n" + + "======================\n" + + $"Начало инициализации: {executeResult.StartTime}\n" + + $"Завершение инициализации: {executeResult.EndTime}\n" + + $"Общее время инициализации: {executeResult.RunTime}\n" + + $"Код выхода: {executeResult.ExitCode}\n" + + $"Статус успешности инициализации: {executeResult.Succeesed}" + + "\n======================\n"; + } + + if (!string.IsNullOrEmpty(executeResult?.StandardError)) + ResultTextEditor += $"Ошибка: {executeResult.StandardError}" + + "\n======================"; + } + + private bool RunPythonCodeCanExecute() + { + bool isSourceNotEmpty = SourceTextEditor?.Length > 0; + bool isTcpConnected = IsTcpClientConnected; + bool isPythonCodeNotExecute = !IsPythonCodeExecute; + + return isSourceNotEmpty && isTcpConnected && isPythonCodeNotExecute; + } + + private async void StopPythonCodeExecute() + { + try + { + await BaseApi.StopPythonExecute(); + } + catch (Exception ex) + { + ResultTextEditorError = ex.Message.ToString(); + } + } + + private bool StopPythonCodeExecuteCanExecute() + { + bool isConnected = IsTcpClientConnected; + bool isPythonCodeExecute = IsPythonCodeExecute; + + return isConnected && isPythonCodeExecute; + } + + private void SendCodeToExternalSourceEditor() + { + NavigationParameters parameters = new() + { + { NavigationParametersKey.SourceCode, SourceTextEditor } + }; + + RegionManager.RequestNavigate(RegionNames.ContentRegion, SubRegionNames.SubRegionScriptEditor, parameters); + } + + private bool SendCodeToExternalSourceEditorCanExecute() + { + bool isSourceNotEmpty = SourceTextEditor?.Length > 0; + bool isTcpConnected = IsTcpClientConnected; + bool isPythonCodeNotExecute = !IsPythonCodeExecute; + + return isSourceNotEmpty && isTcpConnected && isPythonCodeNotExecute; + } + + private async void ToZeroPosition() + { + try + { + await BaseApi.StopPythonExecute(); + } + catch (Exception ex) + { + ResultTextEditorError = ex.Message.ToString(); + } + } + + private bool ToZeroPositionCanExecute() + { + bool isTcpConnected = IsTcpClientConnected; + bool isPythonCodeNotExecute = !IsPythonCodeExecute; + + return isTcpConnected && isPythonCodeNotExecute; + } + + + #endregion + + #region Public fields + + private bool isTcpClientConnected; + public bool IsTcpClientConnected + { + get => isTcpClientConnected; + set + { + bool isNewValue = SetProperty(ref isTcpClientConnected, value); + + if (isNewValue) + { + RunPythonCodeDelegateCommand.RaiseCanExecuteChanged(); + StopPythonCodeExecuteDelegateCommand.RaiseCanExecuteChanged(); + SendCodeToExternalSourceEditorDelegateCommand.RaiseCanExecuteChanged(); + ToZeroPositionDelegateCommand.RaiseCanExecuteChanged(); + } + } + } + + private bool isPythonCodeExecute; + public bool IsPythonCodeExecute + { + get => isPythonCodeExecute; + set + { + var isNewValue = SetProperty(ref isPythonCodeExecute, value); + + if (isNewValue) + { + RunPythonCodeDelegateCommand.RaiseCanExecuteChanged(); + StopPythonCodeExecuteDelegateCommand.RaiseCanExecuteChanged(); + SendCodeToExternalSourceEditorDelegateCommand.RaiseCanExecuteChanged(); + ToZeroPositionDelegateCommand.RaiseCanExecuteChanged(); + } + } + } + + + private string sourceTextEditor; + public string SourceTextEditor + { + get => sourceTextEditor; + set + { + bool isNewValue = SetProperty(ref sourceTextEditor, value); + + if (isNewValue) + { + ShowSaveFileDialogDelegateCommand.RaiseCanExecuteChanged(); + ShowSaveFileSourceTextDialogDelegateCommand.RaiseCanExecuteChanged(); + RunPythonCodeDelegateCommand.RaiseCanExecuteChanged(); + SendCodeToExternalSourceEditorDelegateCommand.RaiseCanExecuteChanged(); + } + + } + } + + private string resultTextEditor; + public string ResultTextEditor + { + get => resultTextEditor; + set + { + bool isNewValue = SetProperty(ref resultTextEditor, value); + + if (isNewValue) + ResultTextEditorLength = ResultTextEditor.Length; + } + } + + private int resultTextEditorLength; + public int ResultTextEditorLength + { + get => resultTextEditorLength; + set + { + bool isNewValue = SetProperty(ref resultTextEditorLength, value); + + if (isNewValue) + CleanExecuteEditorDelegateCommand.RaiseCanExecuteChanged(); + } + } + + private string resultTextEditorError; + public string ResultTextEditorError + { + get => resultTextEditorError; + set + { + bool isNewValue = SetProperty(ref resultTextEditorError, value); + + if (isNewValue) + { + if (ResultTextEditorError.Length > 0) + resultTextEditorError = $"Error: {ResultTextEditorError}"; + } + } + } + + private string pythonVersion; + public string PythonVersion + { + get => pythonVersion; + set => SetProperty(ref pythonVersion, value); + } + + private string pythonBinPath; + public string PythonBinPath + { + get => pythonBinPath; + set => SetProperty(ref pythonBinPath, value); + } + + private string pythonWorkDir; + public string PythonWorkDir + { + get => pythonWorkDir; + set => SetProperty(ref pythonWorkDir, value); } @@ -112,8 +488,23 @@ public override void OnNavigatedFrom(NavigationContext navigationContext) #region Event methods + private void RaiseWebViewNavigationCompleteEvent(object sender) + { + InitBlockly(); + } + + private void RaiseWebViewbMessageReceivedEvent(object sender, WebMessageJsonReceived webMessageReceived) + { + if (webMessageReceived.Action == "sendSourceCode") + { + SourceTextEditor = webMessageReceived.Data; + } + } + private async void OnRaiseTcpServiceCientConnected(object sender) { + IsTcpClientConnected = mCommunicationProvider.IsTcpClientConnected; + var pythonVersionResult = await BaseApi.GetPythonVersion(); var pythonBinPathResult = await BaseApi.GetPythonBinDir(); var pythonWorkDirResult = await BaseApi.GetPythonWorkDir(); @@ -127,12 +518,15 @@ private async void OnRaiseTcpServiceCientConnected(object sender) private void OnRaiseTcperviceClientDisconnect(object sender) { + IsTcpClientConnected = mCommunicationProvider.IsTcpClientConnected; + UpdatePythonInfo(); } - private void OnRaisePythonScriptExecuteStart(object sender) { + IsPythonCodeExecute = true; + mIsWarningStackOwerflowAlreadyShow = false; StartExecuteProgram(); } @@ -158,7 +552,9 @@ private void OnRaisePythonStandartOutput(object sender, string message) private void OnRaisePythonScriptExecuteFinish(object sender, string message) { - FinishExecuteProgram(); + IsPythonCodeExecute = false; + + OnStopExecuteProgram("Сеанс отладки закончен"); ResultTextEditor += message; } @@ -179,15 +575,11 @@ private void UpdatePythonInfo(string pythonVersion = "", string pythonBinPath = PythonWorkDir = $"Рабочая дирректория {pythonWorkDir}"; } - #region Execute program event - private async void StartExecuteProgram() { mStatusBarNotificationDelivery.CompileLogMessage = "Сеанс отладки запущен"; mStatusBarNotificationDelivery.ProgressRingStart = true; - IsEnabledShowOpenDialogButton = false; - IsEnabledStopExecuteButton = true; ResultTextEditor = string.Empty; @@ -196,14 +588,9 @@ private async void StartExecuteProgram() await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(async () => { await mWebViewProvider.ExecuteJavaScript(Scripts.ShadowEnable); - //await ScratchControlView.ExecuteScript(Scripts.ShadowEnable); })); } - private void FinishExecuteProgram() - { - OnStopExecuteProgram("Сеанс отладки закончен"); - } private async void OnStopExecuteProgram(string compileLogStatusBarAction) { @@ -214,31 +601,8 @@ private async void OnStopExecuteProgram(string compileLogStatusBarAction) mStatusBarNotificationDelivery.CompileLogMessage = compileLogStatusBarAction; mStatusBarNotificationDelivery.ProgressRingStart = false; - - IsEnabledShowOpenDialogButton = true; - IsEnabledStopExecuteButton = false; - } - - #endregion - - #region IsEnabled buttons field - - private bool isEnabledStopExecuteButton = false; - public bool IsEnabledStopExecuteButton - { - get => isEnabledStopExecuteButton; - set => SetProperty(ref isEnabledStopExecuteButton, value); - } - - private bool isEnabledShowOpenDialogButton = true; - public bool IsEnabledShowOpenDialogButton - { - get => isEnabledShowOpenDialogButton; - set => SetProperty(ref isEnabledShowOpenDialogButton, value); } - #endregion - #region Initialize Blockly private async void InitBlockly() @@ -247,22 +611,17 @@ private async void InitBlockly() try { - await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(async () => - { - await LoadBlocklySrc(); - await LoadBlocklyBlockLocalLangSrc(language); + await LoadBlocklySrc(); + await LoadBlocklyBlockLocalLangSrc(language); - await mWebViewProvider.ExecuteJavaScript(InitWorkspace()); - await mWebViewProvider.ExecuteJavaScript(Scripts.ListenerCreatePythonCode); - await mWebViewProvider.ExecuteJavaScript(Scripts.ListenerSavedBlocks); + await mWebViewProvider.ExecuteJavaScript(InitWorkspace()); + await mWebViewProvider.ExecuteJavaScript(Scripts.ListenerCreatePythonCode); + await mWebViewProvider.ExecuteJavaScript(Scripts.ListenerSavedBlocks); - if (Settings.Default.BlocklyRestoreBlockOnLoad) - { - await mWebViewProvider.ExecuteJavaScript(Scripts.RestoreSavedBlocks); - } - - - })); + if (Settings.Default.BlocklyRestoreBlockOnLoad) + { + await mWebViewProvider.ExecuteJavaScript(Scripts.RestoreSavedBlocks); + } mStatusBarNotificationDelivery.AppLogMessage = "Загрузка скретч редактора завершена"; } @@ -272,7 +631,7 @@ private async void InitBlockly() } } - private string InitWorkspace() + private static string InitWorkspace() { Toolbox toolbox = InitDefaultToolbox(Settings.Default.BlocklyToolboxLanguage); BlocklyGrid blocklyGrid = InitGrid(); @@ -291,7 +650,7 @@ private string InitWorkspace() return workspaceString; } - private BlocklyGrid InitGrid() + private static BlocklyGrid InitGrid() { BlocklyGrid blocklyGrid = new(); @@ -312,7 +671,7 @@ private BlocklyGrid InitGrid() return blocklyGrid; } - private Toolbox InitDefaultToolbox(BlocklyLanguage language) + private static Toolbox InitDefaultToolbox(BlocklyLanguage language) { Toolbox toolbox = new DefaultSimpleCategoryToolbox(language) { @@ -453,245 +812,6 @@ private async Task LoadBlocklyBlockLocalLangSrc(BlocklyLanguage language) #endregion - #region Result text editor - - private string resultTextEditor; - public string ResultTextEditor - { - get => resultTextEditor; - set - { - bool isNewValue = SetProperty(ref resultTextEditor, value); - - if (isNewValue) - ResultTextEditorLength = ResultTextEditor.Length; - } - } - - #endregion - - #region Result text editor length - - private int resultTextEditorLength; - public int ResultTextEditorLength - { - get => resultTextEditorLength; - set => SetProperty(ref resultTextEditorLength, value); - } - - #endregion - - #region Result text editor panel field - - private string resultTextEditorError; - public string ResultTextEditorError - { - get => resultTextEditorError; - set - { - - if (value == resultTextEditorError) return; - - if (value.Length > 0) - resultTextEditorError = $"Error: {value}"; - else - resultTextEditorError = value; - - SetProperty(ref resultTextEditorError, value); - } - } - - private string pythonVersion; - public string PythonVersion - { - get => pythonVersion; - set => SetProperty(ref pythonVersion, value); - } - - private string pythonBinPath; - public string PythonBinPath - { - get => pythonBinPath; - set => SetProperty(ref pythonBinPath, value); - } - - private string pythonWorkDir; - public string PythonWorkDir - { - get => pythonWorkDir; - set => SetProperty(ref pythonWorkDir, value); - } - - #endregion - - #region Source text editor - - private string sourceTextEditor; - public string SourceTextEditor - { - get => sourceTextEditor; - set => SetProperty(ref sourceTextEditor, value); - } - - #endregion - - #region Command - - private DelegateCommand reloadWebViewCommand; - public DelegateCommand ReloadWebViewCommand => reloadWebViewCommand ??= new DelegateCommand(() => - { - SourceTextEditor = string.Empty; - mWebViewProvider.ReloadWebView(); - }); - - private DelegateCommand sendToExternalSourceEditor; - public DelegateCommand SendToExternalSourceEditor => sendToExternalSourceEditor ??= new DelegateCommand(() => - { - SendSourceToScriptEditor(SourceTextEditor); - - }, () => SourceTextEditor?.Length > 0); - - private DelegateCommand showSaveFileDialogCommand; - public DelegateCommand ShowSaveFileDialogCommand => showSaveFileDialogCommand ??= new DelegateCommand(async () => - { - string workspace = await mWebViewProvider.ExecuteJavaScript("getSavedWorkspace()"); - string xmlWorkspace = JsonConvert.DeserializeObject(workspace); - - if (IDialogManager.ShowSaveFileDialog("Сохранить рабочую область", Settings.Default.SavedUserWorkspaceFolderPath, "workspace", ".xml", "XML documents (.xml)|*.xml")) - { - string path = IDialogManager.FilePathToSave; - await FileHelper.WriteAsync(path, xmlWorkspace); - - mStatusBarNotificationDelivery.AppLogMessage = $"Файл {IDialogManager.FilePathToSave} сохранен"; - } - else - { - mStatusBarNotificationDelivery.AppLogMessage = "Файл не сохранен"; - } - }); - - private DelegateCommand showOpenFileDialogCommand; - public DelegateCommand ShowOpenFileDialogCommand => showOpenFileDialogCommand ??= new DelegateCommand(async () => - { - if (IDialogManager.ShowFileBrowser("Выберите сохранененную рабочую область", Settings.Default.SavedUserWorkspaceFolderPath, "XML documents(.xml) | *.xml")) - { - string path = IDialogManager.FilePath; - if (path == "") return; - - string xml = await FileHelper.ReadTextAsStringAsync(path); - _ = await ExecuteScriptFunctionAsync("loadSavedWorkspace", new object[] { xml }); - - mStatusBarNotificationDelivery.AppLogMessage = $"Файл {path} загружен"; - } - else - { - mStatusBarNotificationDelivery.AppLogMessage = "Файл рабочей области не выбран"; - } - }); - - private DelegateCommand runCode; - public DelegateCommand RunCode => runCode ??= new DelegateCommand(async () => - { - ResultTextEditorError = string.Empty; - WebApi.Client.v1.ResponseModel.ExtendedCommandExecuteResult executeResult = new(); - - try - { - var command = new WebApi.Client.v1.RequestModel.PythonCommand - { - Command = SourceTextEditor - }; - - executeResult = await BaseApi.PythonExecuteAsync(command); - } - catch (Exception ex) - { - ResultTextEditorError = ex.Message.ToString(); - } - - if (Settings.Default.ChangeExtendedExecuteReportToggleSwitchState) - { - ResultTextEditor += "Отчет о инициализации процесса программы\n" + - "======================\n" + - $"Начало инициализации: {executeResult.StartTime}\n" + - $"Завершение инициализации: {executeResult.EndTime}\n" + - $"Общее время инициализации: {executeResult.RunTime}\n" + - $"Код выхода: {executeResult.ExitCode}\n" + - $"Статус успешности инициализации: {executeResult.Succeesed}" + - "\n======================\n"; - } - - if (!string.IsNullOrEmpty(executeResult?.StandardError)) - ResultTextEditor += $"Ошибка: {executeResult.StandardError}" + - "\n======================"; - - }, () => true/*!string.IsNullOrEmpty(SourceTextEditor)*/ && true /*mCommunicationProvider.IsTcpClientConnected*/); - - private DelegateCommand stopExecute; - public DelegateCommand StopExecute => stopExecute ??= new DelegateCommand( async () => - { - if (mCommunicationProvider.IsTcpClientConnected) - { - try - { - await BaseApi.StopPythonExecute(); - } - catch (Exception ex) - { - ResultTextEditorError = ex.Message.ToString(); - } - } - }); - - private DelegateCommand toZeroPositionCommand; - public DelegateCommand ToZeroPositionCommand => toZeroPositionCommand ??= new DelegateCommand(async () => - { - try - { - await BaseApi.StopPythonExecute(); - } - catch (Exception ex) - { - ResultTextEditorError = ex.Message.ToString(); - } - - }, () => mCommunicationProvider.IsTcpClientConnected); - - private DelegateCommand cleanExecuteEditor; - public DelegateCommand CleanExecuteEditor => cleanExecuteEditor ??= new DelegateCommand(async () => - { - await Task.Run(() => - { - ResultTextEditorError = string.Empty; - ResultTextEditor = string.Empty; - }); - }); - - #region ShowSaveFileDialogCommand - - private DelegateCommand showSaveFileSourceTextDialogCommand; - public DelegateCommand ShowSaveFileSourceTextDialogCommand => showSaveFileSourceTextDialogCommand ??= new DelegateCommand(async () => - { - string pythonProgram = SourceTextEditor; - - if (IDialogManager.ShowSaveFileDialog("Сохранить файл программы", Core.Properties.Settings.Default.SavedUserScriptsFolderPath, - "new_program", ".py", "PythonScript file (.py)|*.py|Все файлы|*.*")) - { - string path = IDialogManager.FilePathToSave; - await FileHelper.WriteAsync(path, pythonProgram); - - mStatusBarNotificationDelivery.AppLogMessage = $"Файл {IDialogManager.FilePathToSave} сохранен"; - } - else - { - mStatusBarNotificationDelivery.AppLogMessage = "Файл не сохранен"; - } - }, () => SourceTextEditor?.Length > 0); - - #endregion - - #endregion - #region ExecuteScripts private async Task ExecuteScriptFunctionAsync(string functionName, params object[] parameters) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs index a2374e3..33363c2 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs @@ -1,4 +1,5 @@ -using AdamController.Core.Helpers; +using AdamController.Core; +using AdamController.Core.Helpers; using AdamController.Core.Mvvm; using AdamController.Services.Interfaces; using AdamController.WebApi.Client.v1; @@ -52,6 +53,14 @@ public override void OnNavigatedTo(NavigationContext navigationContext) mPythonRemoteRunner.RaisePythonStandartOutputEvent += OnRaisePythonStandartOutput; mPythonRemoteRunner.RaisePythonScriptExecuteFinishEvent += OnRaisePythonScriptExecuteFinish; + var sourceCode = string.Empty; + navigationContext.Parameters.TryGetValue(NavigationParametersKey.SourceCode, out sourceCode); + + if(sourceCode != null) + { + SourceTextEditor = sourceCode; + } + base.OnNavigatedTo(navigationContext); } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index a704fcd..a05af51 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -5,6 +5,7 @@ using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Core.Properties; +using AdamController.Services.Interfaces; using ControlzEx.Theming; using Prism.Commands; using Prism.Regions; @@ -43,15 +44,17 @@ public class VisualSettingsControlViewModel : RegionViewModelBase #region Service - private IFlyoutManager FlyoutManager { get; } + private readonly IFlyoutManager mFlyoutManager; + private readonly IWebViewProvider mWebViewProvider; #endregion #region ~ - public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager) : base(regionManager, dialogService) + public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager, IWebViewProvider webViewProvider) : base(regionManager, dialogService) { - FlyoutManager = flyoutManager; + mFlyoutManager = flyoutManager; + mWebViewProvider = webViewProvider; OpenAdvancedBlocklySettingsDelegateCommand = new DelegateCommand(OpenAdvancedBlocklySettings, OpenAdvancedBlocklySettingsCanExecute); ChangeBaseThemeDelegateCommand = new DelegateCommand(ChangeBaseTheme, ChangeBaseThemeCanExecute); @@ -64,7 +67,7 @@ public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogServi private void OpenAdvancedBlocklySettings() { - FlyoutManager.OpenFlyout(FlyoutNames.FlyotAdvancedBlocklySettings); + mFlyoutManager.OpenFlyout(FlyoutNames.FlyotAdvancedBlocklySettings); } private bool OpenAdvancedBlocklySettingsCanExecute() diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml index 3cdbc5a..c4e23f8 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml @@ -23,6 +23,7 @@ + - - - + mah:ControlsHelper.ContentCharacterCasing="Normal" + mah:HeaderedControlHelper.HeaderForeground="{DynamicResource MahApps.Brushes.ThemeForeground}"> + @@ -74,36 +74,31 @@ - + @@ -209,7 +204,7 @@ Margin="5 0 5 0" Padding="3" - Command="{Binding ShowSaveFileSourceTextDialogCommand}" + Command="{Binding ShowSaveFileSourceTextDialogDelegateCommand}" Style="{DynamicResource MahApps.Styles.Button}"> @@ -236,7 +231,7 @@ - - @@ -222,8 +216,8 @@ + Background="{DynamicResource MahApps.Brushes.ThemeForeground}" + Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}"/> @@ -262,8 +256,7 @@ - @@ -417,7 +410,6 @@ private void DisposeServices() { + Container.Resolve().Dispose(); + Container.Resolve().Dispose(); + Container.Resolve().Dispose(); Container.Resolve().Dispose(); Container.Resolve().Dispose(); Container.Resolve().Dispose(); - Container.Resolve().Dispose(); - Container.Resolve().Dispose(); + Container.Resolve().Dispose(); Container.Resolve().Dispose(); diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index 7a7fb2e..b29cec9 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -45,6 +45,7 @@ public class ScratchControlViewModel : RegionViewModelBase private readonly IStatusBarNotificationDeliveryService mStatusBarNotificationDelivery; private readonly IWebViewProvider mWebViewProvider; private readonly IDialogManagerService mDialogManager; + private readonly IFileManagmentService mFileManagment; #endregion @@ -66,13 +67,14 @@ public class ScratchControlViewModel : RegionViewModelBase #region ~ - public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IWebViewProvider webViewProvider, IDialogManagerService dialogManager) : base(regionManager, dialogService) + public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IWebViewProvider webViewProvider, IDialogManagerService dialogManager, IFileManagmentService fileManagment) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; mPythonRemoteRunner = pythonRemoteRunner; mStatusBarNotificationDelivery = statusBarNotificationDelivery; mWebViewProvider = webViewProvider; mDialogManager = dialogManager; + mFileManagment = fileManagment; ReloadWebViewDelegateCommand = new DelegateCommand(ReloadWebView, ReloadWebViewCanExecute); ShowSaveFileDialogDelegateCommand = new DelegateCommand(ShowSaveFileDialog, ShowSaveFileDialogCanExecute); @@ -290,7 +292,7 @@ private async void ShowSaveFileDialog() if (mDialogManager.ShowSaveFileDialog(dialogTitle, initialPath, fileName, defaultExt, cFilter)) { string path = mDialogManager.FilePathToSave; - await FileHelper.WriteAsync(path, xmlWorkspace); + await mFileManagment.WriteAsync(path, xmlWorkspace); mStatusBarNotificationDelivery.AppLogMessage = $"Файл {mDialogManager.FilePathToSave} сохранен"; } @@ -318,7 +320,7 @@ private async void ShowOpenFileDialog() string path = mDialogManager.FilePath; if (path == "") return; - string xml = await FileHelper.ReadTextAsStringAsync(path); + string xml = await mFileManagment.ReadTextAsStringAsync(path); _ = await ExecuteScriptFunctionAsync("loadSavedWorkspace", new object[] { xml }); mStatusBarNotificationDelivery.AppLogMessage = $"Файл {path} загружен"; @@ -348,7 +350,7 @@ private async void ShowSaveFileSourceTextDialog() if (mDialogManager.ShowSaveFileDialog(title, initialPath, fileName, defaultExt, filter)) { string path = mDialogManager.FilePathToSave; - await FileHelper.WriteAsync(path, pythonProgram); + await mFileManagment.WriteAsync(path, pythonProgram); mStatusBarNotificationDelivery.AppLogMessage = $"Файл {mDialogManager.FilePathToSave} сохранен"; } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs index d4005d9..edd1cd6 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs @@ -1,5 +1,4 @@ using AdamController.Core; -using AdamController.Core.Helpers; using AdamController.Core.Mvvm; using AdamController.Services.Interfaces; using AdamController.Services.PythonRemoteRunnerDependency; @@ -22,23 +21,22 @@ public class ScriptEditorControlViewModel : RegionViewModelBase private readonly ICommunicationProviderService mCommunicationProvider; private readonly IPythonRemoteRunnerService mPythonRemoteRunner; private readonly IStatusBarNotificationDeliveryService mStatusBarNotificationDelivery; + private readonly IFileManagmentService mFileManagment; #endregion - //public static Action AppLogStatusBarAction { get; set; } - + private bool mIsWarningStackOwerflowAlreadyShow; private readonly IMessageDialogManager IDialogManager; - public ScriptEditorControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery) : base(regionManager, dialogService) + public ScriptEditorControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IFileManagmentService fileManagment) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; mPythonRemoteRunner = pythonRemoteRunner; mStatusBarNotificationDelivery = statusBarNotificationDelivery; + mFileManagment = fileManagment; IDialogManager = new MessageDialogManagerMahapps(Application.Current); - //InitAction(); - //PythonExecuteEvent(); } #region Navigation @@ -55,6 +53,7 @@ public override void OnNavigatedTo(NavigationContext navigationContext) mPythonRemoteRunner.RaisePythonScriptExecuteFinishEvent += OnRaisePythonScriptExecuteFinish; var sourceCode = string.Empty; + navigationContext.Parameters.TryGetValue(NavigationParametersKey.SourceCode, out sourceCode); if(sourceCode != null) @@ -180,17 +179,6 @@ public string SelectedText #endregion - #region SendSourceToScriptEditor Action - - //private void InitAction() - //{ - // if(ScratchControlViewModel.SendSourceToScriptEditor == null) - // { - // ScratchControlViewModel.SendSourceToScriptEditor = new Action(source => SourceTextEditor = source); - // } - //} - - #endregion #region Result text editor @@ -362,17 +350,14 @@ await Task.Run(() => string path = IDialogManager.FilePath; if (path == "") return; - string pythonProgram = await FileHelper.ReadTextAsStringAsync(path); + string pythonProgram = await mFileManagment.ReadTextAsStringAsync(path); SourceTextEditor = pythonProgram; mStatusBarNotificationDelivery.AppLogMessage = $"Файл {path} загружен"; - //AppLogStatusBarAction($"Файл {path} загружен"); } else { mStatusBarNotificationDelivery.AppLogMessage = "Файл c исходным кодом не выбран"; - //AppLogStatusBarAction("Файл c исходным кодом не выбран"); - } }); @@ -390,10 +375,9 @@ await Task.Run(() => "new_program", ".py", "PythonScript file (.py)|*.py|Все файлы|*.*")) { string path = IDialogManager.FilePathToSave; - await FileHelper.WriteAsync(path, pythonProgram); + await mFileManagment.WriteAsync(path, pythonProgram); mStatusBarNotificationDelivery.AppLogMessage = $"Файл {IDialogManager.FilePathToSave} сохранен"; - //AppLogStatusBarAction($"Файл {IDialogManager.FilePathToSave} сохранен"); } else { From c5f90255fff11f257a6e3de4c1dbf9dcadcb5834 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 20 Apr 2024 10:10:40 +1000 Subject: [PATCH 106/181] Close #36 --- AdamController.Core/AdamController.Core.csproj | 6 ++++++ .../{Helpers => Extensions}/SyslogParseMessage.cs | 15 ++++++++------- AdamController/App.xaml.cs | 1 - .../ViewModels/ContentRegionViewModel.cs | 5 +++-- .../Views/ComputerVisionControlView.xaml.cs | 3 +-- .../Views/ScratchControlView.xaml.cs | 1 - 6 files changed, 18 insertions(+), 13 deletions(-) rename AdamController.Core/{Helpers => Extensions}/SyslogParseMessage.cs (87%) diff --git a/AdamController.Core/AdamController.Core.csproj b/AdamController.Core/AdamController.Core.csproj index b784f98..b6dbcff 100644 --- a/AdamController.Core/AdamController.Core.csproj +++ b/AdamController.Core/AdamController.Core.csproj @@ -10,6 +10,12 @@ bin\x64\Release\ + + + + + + diff --git a/AdamController.Core/Helpers/SyslogParseMessage.cs b/AdamController.Core/Extensions/SyslogParseMessage.cs similarity index 87% rename from AdamController.Core/Helpers/SyslogParseMessage.cs rename to AdamController.Core/Extensions/SyslogParseMessage.cs index b9f56cb..13d6f53 100644 --- a/AdamController.Core/Helpers/SyslogParseMessage.cs +++ b/AdamController.Core/Extensions/SyslogParseMessage.cs @@ -2,9 +2,9 @@ using System; using System.Text.RegularExpressions; -namespace AdamController.Core.Helpers +namespace AdamController.Core.Extensions { - public class SyslogParseMessage + public static class SyslogParseMessage { private static readonly string mSyslogMsgHeaderPattern = @"\<(?\d{1,3})\>(?[1-9]{0,2}) (?(\S|\w)+) (?-|(\S|\w){1,255}) (?-|(\S|\w){1,48}) (?-|(\S|\w){1,128}) (?-|(\S|\w){1,32})"; private static readonly string mSyslogMsgStructuredDataPattern = @"(?-|\[[^\[\=\x22\]\x20]{1,32}( ([^\[\=\x22\]\x20]{1,32}=\x22.+\x22))?\])"; @@ -18,9 +18,10 @@ public class SyslogParseMessage /// /// /// - public static SyslogMessage Parse(string rawMessage) + public static SyslogMessage Parse(this string rawMessage) { - if (string.IsNullOrWhiteSpace(rawMessage)) { throw new ArgumentNullException(nameof(rawMessage)); } + if (string.IsNullOrWhiteSpace(rawMessage)) + { throw new ArgumentNullException(nameof(rawMessage)); } var match = mExpression.Match(rawMessage); if (match.Success) @@ -39,9 +40,9 @@ public static SyslogMessage Parse(string rawMessage) RawMessage = rawMessage }; } - else - { - throw new InvalidOperationException("Invalid message."); + else + { + throw new InvalidOperationException("Invalid message."); } } } diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 0d262fe..ff5a50f 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -22,7 +22,6 @@ using AdamController.Views; using AdamController.Modules.MenuRegion; using AdamController.Modules.ContentRegion; -using AdamController.Core.Helpers; using AdamController.Services; using AdamController.Modules.StatusBarRegion; using AdamController.Modules.FlayoutsRegion; diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs index 1b1e9e9..a72ca59 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs @@ -1,5 +1,5 @@ using AdamController.Core; -using AdamController.Core.Helpers; +using AdamController.Core.Extensions; using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Modules.ContentRegion.Views; @@ -85,7 +85,8 @@ private void ComunicateHelperOnAdamUdpReceived(string message) { try { - SyslogMessage syslogMessage = SyslogParseMessage.Parse(message); + SyslogMessage syslogMessage = message.Parse(); + // SyslogParseMessage.Parse(message); //CompileLogStatusBar = $"{syslogMessage.TimeStamp:T} {syslogMessage.Message}"; } catch (Exception ex) diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs b/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs index 75f7dbc..f02ee79 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs +++ b/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs @@ -1,5 +1,4 @@ -using AdamController.Core.Helpers; -using LibVLCSharp.Shared; +using LibVLCSharp.Shared; using LibVLCSharp.WPF; using System; using System.Windows; diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs index 950f950..d11cbe2 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs @@ -1,5 +1,4 @@  -using AdamController.Core.Helpers; using AdamController.Core.Properties; using AdamController.Services.Interfaces; using AdamController.Services.WebViewProviderDependency; From 19504e3dec51ab5532ed267c7ba327652406ae17 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 20 Apr 2024 10:27:26 +1000 Subject: [PATCH 107/181] Close issue #37 --- .../ViewModels/MainWindowViewModel.cs | 22 +++ .../ViewModels/ContentRegionViewModel.cs | 133 ------------------ 2 files changed, 22 insertions(+), 133 deletions(-) diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index c6a1018..1d769bf 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -1,4 +1,6 @@ using AdamController.Core; +using AdamController.Core.Extensions; +using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Core.Properties; using AdamController.Services.Interfaces; @@ -150,6 +152,20 @@ private void SaveFolderPathToSettings() } } + + private void ParseSyslogMessage(string message) + { + try + { + SyslogMessage syslogMessage = message.Parse(); + mStatusBarNotification.CompileLogMessage = $"{syslogMessage.TimeStamp:T} {syslogMessage.Message}"; + } + catch + { + // If you couldn't read the message, it's okay, no one needs to know about it. + } + } + #endregion #region Subscriptions @@ -161,6 +177,7 @@ private void Subscribe() { mSubRegionChangeAwareService.RaiseSubRegionChangeEvent += RaiseSubRegionChangeEvent; mCommunicationProviderService.RaiseTcpServiceCientConnectedEvent += RaiseTcpServiceCientConnectedEvent; + mCommunicationProviderService.RaiseUdpServiceServerReceivedEvent += RaiseUdpServiceServerReceivedEvent; Application.Current.MainWindow.Loaded += MainWindowLoaded; } @@ -208,6 +225,11 @@ private void RaiseTcpServiceCientConnectedEvent(object sender) _ = BaseApi.StopPythonExecute(); } + private void RaiseUdpServiceServerReceivedEvent(object sender, string message) + { + ParseSyslogMessage(message); + } + #endregion } } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs index a72ca59..52e7d99 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ContentRegionViewModel.cs @@ -1,6 +1,4 @@ using AdamController.Core; -using AdamController.Core.Extensions; -using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Modules.ContentRegion.Views; using AdamController.Services.Interfaces; @@ -78,136 +76,5 @@ private void SubRegionsRequestNavigate(string uri, NavigationParameters paramete } #endregion - - #region OLD - - private void ComunicateHelperOnAdamUdpReceived(string message) - { - try - { - SyslogMessage syslogMessage = message.Parse(); - // SyslogParseMessage.Parse(message); - //CompileLogStatusBar = $"{syslogMessage.TimeStamp:T} {syslogMessage.Message}"; - } - catch (Exception ex) - { - //CompileLogStatusBar = $"Error reading udp log with exception {ex.Message}"; - } - } - - #region Events TCP/IP clients - - private void OnTcpDisconnected() - { - //если центр уведомлений закрыт, обновляем счетчик уведомлений - //if (!NotificationFlayoutsIsOpen && Settings.Default.IsMessageShowOnAbortMainConnection) - //{ - //BadgeCounter++; - //FailConnectMessageVisibility = Visibility.Visible; - //} - - //TextOnConnectFlayotButton = mConnectButtonStatusDisconnected; - //TextOnStatusConnectToolbar = mToolbarStatusClientDisconnected; - - //ConnectIcon = PackIconModernKind.Connect; - //IconOnConnectFlayoutButton = PackIconMaterialKind.RobotDead; - } - - private void OnTcpConnected() - { - //_ = BaseApi.StopPythonExecute(); - - //TextOnConnectFlayotButton = mConnectButtonStatusConnected; - //TextOnStatusConnectToolbar = mToolbarStatusClientConnected; - - //ConnectIcon = PackIconModernKind.Disconnect; - //IconOnConnectFlayoutButton = PackIconMaterialKind.Robot; - } - - private void OnTcpReconnected(int reconnectCount) - { - //TextOnConnectFlayotButton = $"{mConnectButtonStatusReconnected} {reconnectCount}"; - //TextOnStatusConnectToolbar = $"{mToolbarStatusClientReconnected} {reconnectCount}"; - - //ConnectIcon = PackIconModernKind.TransitConnectionDeparture; - //IconOnConnectFlayoutButton = PackIconMaterialKind.RobotConfused; - } - - #endregion - - #region InitAction - - private void InitAction() - { - //move to page with selected index - //if (ScratchControlView.SetSelectedPageIndex == null) - //{ - // ScratchControlView.SetSelectedPageIndex = new Action(index => SelectedPageIndex = index); - //} - - //open flayout page - //if (VisualSettingsControlView.OpenAdvancedBlocklySettings == null) - //{ - // VisualSettingsControlView.OpenAdvancedBlocklySettings = new Action(open => AdvancedBlocklySettingsFlayoutsIsOpen = open); - //} - - //change toolbox lang settings - //if (VisualSettingsControlView.SetToolboxLanguage == null) - //{ - // VisualSettingsControlView.SetToolboxLanguage = new Action(model => SelectedBlocklyToolboxLanguage = model); - //} - - //settings blockly theme - //if (VisualSettingsControlView.SetBlocklyThemeAndGridColor == null) - //{ - // VisualSettingsControlView.SetBlocklyThemeAndGridColor = new Action - // (theme => - // { - // SelectedBlocklyTheme = theme; - // - // if (Settings.Default.ChangeGridColorSwitchToggleSwitchState) return; - // - // SelectGridColorDependingSelectedTheme(theme.BlocklyTheme); - // }); - //} - - //if (VisualSettingsControlView.ChangeNotificationOpacity == null) - //{ - //VisualSettingsControlView.ChangeNotificationOpacity = new Action - // (opacity => - // { - // Settings.Default.NotificationOpacity = opacity; - // NotificationOpacity = opacity; - // }); - //} - - //send message to status app log - //if (ScratchControlView.AppLogStatusBarAction == null) - //{ - //ScratchControlView.AppLogStatusBarAction = new Action(log => AppLogStatusBar = log); - //} - - //send message to status complile log - //if (ScratchControlView.CompileLogStatusBarAction == null) - //{ - //ScratchControlView.CompileLogStatusBarAction = new Action(log => CompileLogStatusBar = log); - //} - - //start process ring - //if (ScratchControlView.ProgressRingStartAction == null) - //{ - //ScratchControlView.ProgressRingStartAction = new Action(start => ProgressRingStart = start); - //} - - //if (ScriptEditorControlView.AppLogStatusBarAction == null) - //{ - //ScriptEditorControlView.AppLogStatusBarAction = new Action(log => AppLogStatusBar = log); - //} - } - - #endregion - - #endregion - } } From b49d5f58fd40d43976f98da0cb5eeb37ea6207d4 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 20 Apr 2024 11:18:21 +1000 Subject: [PATCH 108/181] Duplicates of data models for the results of the client's web API have been removed --- .../AdamController.Core.csproj | 2 - .../Model/CommandExecuteResult.cs | 38 -------- .../Model/ExtendedCommandExecuteResult.cs | 61 ------------- .../AdamController.Services.csproj | 5 ++ .../Interfaces/IPythonRemoteRunnerService.cs | 4 +- .../Extensions.cs | 31 ------- .../RemoteCommandExecuteResult.cs | 37 -------- .../PythonRemoteRunnerService.cs | 15 ++-- .../AdamController.WebApi.Client/ApiClient.cs | 3 +- .../Common/Extension.cs | 88 ++++++++----------- .../ViewModels/ScratchControlViewModel.cs | 4 +- .../ScriptEditorControlViewModel.cs | 3 +- 12 files changed, 54 insertions(+), 237 deletions(-) delete mode 100644 AdamController.Core/Model/CommandExecuteResult.cs delete mode 100644 AdamController.Core/Model/ExtendedCommandExecuteResult.cs delete mode 100644 AdamController.Services/PythonRemoteRunnerDependency/Extensions.cs delete mode 100644 AdamController.Services/PythonRemoteRunnerDependency/RemoteCommandExecuteResult.cs diff --git a/AdamController.Core/AdamController.Core.csproj b/AdamController.Core/AdamController.Core.csproj index b6dbcff..f34e159 100644 --- a/AdamController.Core/AdamController.Core.csproj +++ b/AdamController.Core/AdamController.Core.csproj @@ -28,8 +28,6 @@ - - diff --git a/AdamController.Core/Model/CommandExecuteResult.cs b/AdamController.Core/Model/CommandExecuteResult.cs deleted file mode 100644 index 8831b7f..0000000 --- a/AdamController.Core/Model/CommandExecuteResult.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; - -namespace AdamController.Core.Model -{ - [Obsolete] - public class CommandExecuteResult - { - /// - /// The succeeded status of an executable. - /// - public bool Succeeded { get; set; } - - /// - /// The exit code of an executable. - /// - public int ExitCode { get; set; } - - /// - /// The standard error of an executable. - /// - public string StandardError { get; set; } = string.Empty; - - /// - /// The start time of an executable. - /// - public DateTime StartTime { get; set; } - - /// - /// The end time of an executable. - /// - public DateTime EndTime { get; set; } - - /// - /// The run time of an executable. - /// - public TimeSpan RunTime { get; set; } - } -} diff --git a/AdamController.Core/Model/ExtendedCommandExecuteResult.cs b/AdamController.Core/Model/ExtendedCommandExecuteResult.cs deleted file mode 100644 index caa01a9..0000000 --- a/AdamController.Core/Model/ExtendedCommandExecuteResult.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; - -namespace AdamController.Core.Model -{ - public class ExtendedCommandExecuteResult - { - /// - /// The succeeded status of an executable. - /// - public bool Succesed { get; set; } - - /// - /// The exit code of an executable. - /// - public int ExitCode { get; set; } - - /// - /// The standard output of an executable. - /// - public string StandardOutput { get; set; } = string.Empty; - - /// - /// The standard error of an executable. - /// - public string StandardError { get; set; } = string.Empty; - - /// - /// The start time of an executable. - /// - public DateTime StartTime { get; set; } - - /// - /// The end time of an executable. - /// - public DateTime EndTime { get; set; } - - /// - /// The run time of an executable. - /// - public TimeSpan RunTime { get; set; } - } - - public static class Extension - { - public static CommandExecuteResult ToCommandExecuteResult(this ExtendedCommandExecuteResult extendedResult) - { - var result = new CommandExecuteResult() - { - Succeeded = extendedResult.Succesed, - ExitCode = extendedResult.ExitCode, - - StandardError = extendedResult.StandardError, - StartTime = extendedResult.StartTime, - EndTime = extendedResult.EndTime, - RunTime = extendedResult.RunTime - }; - - return result; - } - } -} diff --git a/AdamController.Services/AdamController.Services.csproj b/AdamController.Services/AdamController.Services.csproj index eade97b..9a0f9ae 100644 --- a/AdamController.Services/AdamController.Services.csproj +++ b/AdamController.Services/AdamController.Services.csproj @@ -22,4 +22,9 @@ + + + + + diff --git a/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs b/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs index 4326e7c..7137675 100644 --- a/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs +++ b/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs @@ -1,4 +1,4 @@ -using AdamController.Services.PythonRemoteRunnerDependency; +using AdamController.WebApi.Client.v1.ResponseModel; using System; namespace AdamController.Services.Interfaces @@ -7,7 +7,7 @@ namespace AdamController.Services.Interfaces public delegate void PythonStandartOutputEventHandler(object sender, string message); public delegate void PythonScriptExecuteStartEventHandler(object sender); - public delegate void PythonScriptExecuteFinishEventHandler(object sender, RemoteCommandExecuteResult remoteCommandExecuteResult); + public delegate void PythonScriptExecuteFinishEventHandler(object sender, CommandExecuteResult remoteCommandExecuteResult); #endregion diff --git a/AdamController.Services/PythonRemoteRunnerDependency/Extensions.cs b/AdamController.Services/PythonRemoteRunnerDependency/Extensions.cs deleted file mode 100644 index 0e4ae28..0000000 --- a/AdamController.Services/PythonRemoteRunnerDependency/Extensions.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Text.Json; - -namespace AdamController.Services.PythonRemoteRunnerDependency -{ - public static class Extensions - { - /// - /// Deserealize jsonString to CommandExecuteResult - /// - /// JSON string with CommandExecuteResult object - /// Returns the CommandExecuteResult object with the result, if deserialization is successful, or a new CommandExecuteResult object otherwise - public static RemoteCommandExecuteResult ToCommandResult(this string jsonString) - { - if (jsonString == null) - return new RemoteCommandExecuteResult(); - - RemoteCommandExecuteResult executeResult = new(); - - try - { - executeResult = JsonSerializer.Deserialize(jsonString); - } - catch - { - - } - - return executeResult; - } - } -} diff --git a/AdamController.Services/PythonRemoteRunnerDependency/RemoteCommandExecuteResult.cs b/AdamController.Services/PythonRemoteRunnerDependency/RemoteCommandExecuteResult.cs deleted file mode 100644 index d31f3df..0000000 --- a/AdamController.Services/PythonRemoteRunnerDependency/RemoteCommandExecuteResult.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; - -namespace AdamController.Services.PythonRemoteRunnerDependency -{ - public class RemoteCommandExecuteResult : EventArgs - { - /// - /// The succeeded status of an executable. - /// - public bool Succeeded { get; set; } - - /// - /// The exit code of an executable. - /// - public int ExitCode { get; set; } - - /// - /// The standard error of an executable. - /// - public string StandardError { get; set; } = string.Empty; - - /// - /// The start time of an executable. - /// - public DateTime StartTime { get; set; } - - /// - /// The end time of an executable. - /// - public DateTime EndTime { get; set; } - - /// - /// The run time of an executable. - /// - public TimeSpan RunTime { get; set; } - } -} diff --git a/AdamController.Services/PythonRemoteRunnerService.cs b/AdamController.Services/PythonRemoteRunnerService.cs index b96df40..9ddd1ec 100644 --- a/AdamController.Services/PythonRemoteRunnerService.cs +++ b/AdamController.Services/PythonRemoteRunnerService.cs @@ -1,10 +1,10 @@ using AdamController.Services.Interfaces; -using AdamController.Services.PythonRemoteRunnerDependency; using AdamController.Services.UdpClientServiceDependency; +using AdamController.WebApi.Client.v1.ResponseModel; +using AdamController.WebApi.Client.Common; using System.Linq; -using System.Text; using System.Text.RegularExpressions; -using System.Threading; + namespace AdamController.Services { @@ -81,8 +81,9 @@ private void ParseEvents(Match match, string message) case cFinishMessage: { - var cleanMessage = message.Remove(0, 6); - RemoteCommandExecuteResult executeResult = cleanMessage.ToCommandResult(); + string cleanMessage = message.Remove(0, 6); + + CommandExecuteResult executeResult = cleanMessage.ToCommandResult(); OnRaisePythonScriptExecuteFinishEvent(executeResult); break; } @@ -146,14 +147,12 @@ protected virtual void OnRaisePythonScriptExecuteStartEvent() raiseEvent?.Invoke(this); } - protected virtual void OnRaisePythonScriptExecuteFinishEvent(RemoteCommandExecuteResult remoteCommandExecuteResult) + protected virtual void OnRaisePythonScriptExecuteFinishEvent(CommandExecuteResult remoteCommandExecuteResult) { PythonScriptExecuteFinishEventHandler raiseEvent = RaisePythonScriptExecuteFinishEvent; raiseEvent?.Invoke(this, remoteCommandExecuteResult); } - - #endregion } } diff --git a/Legacy/AdamController.WebApi.Client/ApiClient.cs b/Legacy/AdamController.WebApi.Client/ApiClient.cs index bec04a2..50198d9 100644 --- a/Legacy/AdamController.WebApi.Client/ApiClient.cs +++ b/Legacy/AdamController.WebApi.Client/ApiClient.cs @@ -1,5 +1,4 @@ -using AdamController.WebApi.Client.v1; -using System.Net.Http.Headers; +using System.Net.Http.Headers; using System.Text; namespace AdamController.WebApi.Client diff --git a/Legacy/AdamController.WebApi.Client/Common/Extension.cs b/Legacy/AdamController.WebApi.Client/Common/Extension.cs index b88b08c..cc4d5f6 100644 --- a/Legacy/AdamController.WebApi.Client/Common/Extension.cs +++ b/Legacy/AdamController.WebApi.Client/Common/Extension.cs @@ -7,61 +7,65 @@ namespace AdamController.WebApi.Client.Common { public static class Extension { - #region public extensions - - [Obsolete] - /// - /// Deserealize jsonString to CommandExecuteResult - /// - /// JSON string with CommandExecuteResult object - /// Returns the CommandExecuteResult object with the result, if deserialization is successful, or a new CommandExecuteResult object otherwise - public static CommandExecuteResult ToCommandResult(this string jsonString) + public async static Task ToExtendedCommandResult(this HttpResponseMessage? response) + { + if (response == null) + return new ExtendedCommandExecuteResult(); + + var jsonString = await response.Content.ReadAsStringAsync(); + var result = jsonString.ToExtendedCommandResult(); + return result; + } + + public async static Task ToCommandResult(this HttpResponseMessage? response) { - if (jsonString == null) + if (response == null) return new CommandExecuteResult(); - CommandExecuteResult executeResult = new(); + string jsonString = await response.Content.ReadAsStringAsync(); + + var result = jsonString.ToCommandResult(); + return result; + } + + public static CommandExecuteResult ToCommandResult(this string jsonString) + { + CommandExecuteResult result = new(); try { - executeResult = JsonSerializer.Deserialize(jsonString); + CommandExecuteResult? deleserialize = JsonSerializer.Deserialize(jsonString); + + if (deleserialize != null) + result = deleserialize; + + return result; } catch { - + return result; } - - return executeResult; } - /// - /// Deserealize jsonString to ExtendedCommandExecuteResult - /// - /// JSON string with ExtendedCommandExecuteResult object - /// Returns the ExtendedCommandExecuteResult object with the result, if deserialization is successful, or a new ExtendedCommandExecuteResult object otherwise public static ExtendedCommandExecuteResult ToExtendedCommandResult(this string jsonString) { - if (jsonString == null) - return new ExtendedCommandExecuteResult(); - - ExtendedCommandExecuteResult executeResult = new(); + ExtendedCommandExecuteResult result = new(); try { - - executeResult = JsonSerializer.Deserialize(jsonString); - //executeResult = JsonConvert.DeserializeObject(jsonString); + ExtendedCommandExecuteResult? deleserialize = JsonSerializer.Deserialize(jsonString); + + if (deleserialize != null) + result = deleserialize; + + return result; } catch { - + return result; } - - return executeResult; } - #endregion - #region internal extension internal static string FromBase64ToString(this string base64string) @@ -92,26 +96,6 @@ internal static string FromUrlEncodeToString(this string @string) return encodedToUrlEncodeString; } - internal async static Task ToExtendedCommandResult(this HttpResponseMessage? response) - { - if(response == null) - return new ExtendedCommandExecuteResult(); - - var jsonString = await response.Content.ReadAsStringAsync(); - ExtendedCommandExecuteResult result = JsonSerializer.Deserialize(jsonString); - return result; - } - - internal async static Task ToCommandResult(this HttpResponseMessage? response) - { - if(response == null) - return new CommandExecuteResult(); - - var jsonString = await response.Content.ReadAsStringAsync(); - CommandExecuteResult result = JsonSerializer.Deserialize(jsonString); - return result; - } - #endregion } } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index b29cec9..1b4268b 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -8,9 +8,9 @@ using AdamController.Core.Mvvm; using AdamController.Core.Properties; using AdamController.Services.Interfaces; -using AdamController.Services.PythonRemoteRunnerDependency; using AdamController.Services.WebViewProviderDependency; using AdamController.WebApi.Client.v1; +using AdamController.WebApi.Client.v1.ResponseModel; using Newtonsoft.Json; using Prism.Commands; using Prism.Regions; @@ -622,7 +622,7 @@ private void OnRaisePythonStandartOutput(object sender, string message) ResultTextEditor += message; } - private void OnRaisePythonScriptExecuteFinish(object sender, RemoteCommandExecuteResult remoteCommandExecuteResult) + private void OnRaisePythonScriptExecuteFinish(object sender, CommandExecuteResult remoteCommandExecuteResult) { IsPythonCodeExecute = false; diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs index edd1cd6..75b2d86 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs @@ -1,7 +1,6 @@ using AdamController.Core; using AdamController.Core.Mvvm; using AdamController.Services.Interfaces; -using AdamController.Services.PythonRemoteRunnerDependency; using AdamController.WebApi.Client.v1; using AdamController.WebApi.Client.v1.ResponseModel; using MessageDialogManagerLib; @@ -104,7 +103,7 @@ private void OnRaisePythonStandartOutput(object sender, string message) ResultTextEditor += message; } - private void OnRaisePythonScriptExecuteFinish(object sender, RemoteCommandExecuteResult remoteCommandExecuteResult) + private void OnRaisePythonScriptExecuteFinish(object sender, CommandExecuteResult remoteCommandExecuteResult) { IsCodeExecuted = false; //ResultTextEditor += message; From 9e7819030dc08ac5b4c0b1c5e9521e2760e62fe2 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sat, 20 Apr 2024 11:55:51 +1000 Subject: [PATCH 109/181] Close #38 --- .../Interfaces/IPythonRemoteRunnerService.cs | 2 +- .../PythonRemoteRunnerService.cs | 4 ++-- .../Common/Extension.cs | 20 ++++++++++++------- .../v1/ResponseModel/CommandExecuteResult.cs | 4 ++-- .../ViewModels/ScratchControlViewModel.cs | 7 +++++-- .../ScriptEditorControlViewModel.cs | 2 +- 6 files changed, 24 insertions(+), 15 deletions(-) diff --git a/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs b/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs index 7137675..53acd50 100644 --- a/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs +++ b/AdamController.Services/Interfaces/IPythonRemoteRunnerService.cs @@ -7,7 +7,7 @@ namespace AdamController.Services.Interfaces public delegate void PythonStandartOutputEventHandler(object sender, string message); public delegate void PythonScriptExecuteStartEventHandler(object sender); - public delegate void PythonScriptExecuteFinishEventHandler(object sender, CommandExecuteResult remoteCommandExecuteResult); + public delegate void PythonScriptExecuteFinishEventHandler(object sender, ExtendedCommandExecuteResult remoteCommandExecuteResult); #endregion diff --git a/AdamController.Services/PythonRemoteRunnerService.cs b/AdamController.Services/PythonRemoteRunnerService.cs index 9ddd1ec..1eec389 100644 --- a/AdamController.Services/PythonRemoteRunnerService.cs +++ b/AdamController.Services/PythonRemoteRunnerService.cs @@ -83,7 +83,7 @@ private void ParseEvents(Match match, string message) { string cleanMessage = message.Remove(0, 6); - CommandExecuteResult executeResult = cleanMessage.ToCommandResult(); + ExtendedCommandExecuteResult executeResult = cleanMessage.ToExtendedCommandResult(); OnRaisePythonScriptExecuteFinishEvent(executeResult); break; } @@ -147,7 +147,7 @@ protected virtual void OnRaisePythonScriptExecuteStartEvent() raiseEvent?.Invoke(this); } - protected virtual void OnRaisePythonScriptExecuteFinishEvent(CommandExecuteResult remoteCommandExecuteResult) + protected virtual void OnRaisePythonScriptExecuteFinishEvent(ExtendedCommandExecuteResult remoteCommandExecuteResult) { PythonScriptExecuteFinishEventHandler raiseEvent = RaisePythonScriptExecuteFinishEvent; raiseEvent?.Invoke(this, remoteCommandExecuteResult); diff --git a/Legacy/AdamController.WebApi.Client/Common/Extension.cs b/Legacy/AdamController.WebApi.Client/Common/Extension.cs index cc4d5f6..f3eb003 100644 --- a/Legacy/AdamController.WebApi.Client/Common/Extension.cs +++ b/Legacy/AdamController.WebApi.Client/Common/Extension.cs @@ -7,6 +7,11 @@ namespace AdamController.WebApi.Client.Common { public static class Extension { + private static JsonSerializerOptions mJsonSerializerOptions = new() + { + PropertyNameCaseInsensitive = true + }; + public async static Task ToExtendedCommandResult(this HttpResponseMessage? response) { if (response == null) @@ -17,7 +22,7 @@ public async static Task ToExtendedCommandResult(t return result; } - public async static Task ToCommandResult(this HttpResponseMessage? response) + /*public async static Task ToCommandResult(this HttpResponseMessage? response) { if (response == null) return new CommandExecuteResult(); @@ -45,7 +50,7 @@ public static CommandExecuteResult ToCommandResult(this string jsonString) { return result; } - } + }*/ public static ExtendedCommandExecuteResult ToExtendedCommandResult(this string jsonString) { @@ -53,7 +58,8 @@ public static ExtendedCommandExecuteResult ToExtendedCommandResult(this string j try { - ExtendedCommandExecuteResult? deleserialize = JsonSerializer.Deserialize(jsonString); + + ExtendedCommandExecuteResult? deleserialize = JsonSerializer.Deserialize(jsonString, mJsonSerializerOptions); if (deleserialize != null) result = deleserialize; @@ -68,13 +74,13 @@ public static ExtendedCommandExecuteResult ToExtendedCommandResult(this string j #region internal extension - internal static string FromBase64ToString(this string base64string) + /*internal static string FromBase64ToString(this string base64string) { byte[] base64EncodedBytes = Convert.FromBase64String(base64string); string decodedString = Encoding.UTF8.GetString(base64EncodedBytes); return decodedString; - } + }*/ internal static string FromStringToBase64String(this string @string) { @@ -90,11 +96,11 @@ internal static string FromStringToUrlEncodeString(this string @string) return encodedToUrlEncodeString; } - internal static string FromUrlEncodeToString(this string @string) + /*internal static string FromUrlEncodeToString(this string @string) { string encodedToUrlEncodeString = HttpUtility.UrlDecode(@string); return encodedToUrlEncodeString; - } + }*/ #endregion } diff --git a/Legacy/AdamController.WebApi.Client/v1/ResponseModel/CommandExecuteResult.cs b/Legacy/AdamController.WebApi.Client/v1/ResponseModel/CommandExecuteResult.cs index 4b4b7d8..ab851e1 100644 --- a/Legacy/AdamController.WebApi.Client/v1/ResponseModel/CommandExecuteResult.cs +++ b/Legacy/AdamController.WebApi.Client/v1/ResponseModel/CommandExecuteResult.cs @@ -1,6 +1,6 @@ namespace AdamController.WebApi.Client.v1.ResponseModel { - public class CommandExecuteResult + /*public class CommandExecuteResult { /// /// The succeeded status of an executable. @@ -31,5 +31,5 @@ public class CommandExecuteResult /// The run time of an executable. /// public TimeSpan RunTime { get; set; } - } + }*/ } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index 1b4268b..e05ce8d 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -622,7 +622,7 @@ private void OnRaisePythonStandartOutput(object sender, string message) ResultTextEditor += message; } - private void OnRaisePythonScriptExecuteFinish(object sender, CommandExecuteResult remoteCommandExecuteResult) + private void OnRaisePythonScriptExecuteFinish(object sender, ExtendedCommandExecuteResult remoteCommandExecuteResult) { IsPythonCodeExecute = false; @@ -639,7 +639,10 @@ private void OnRaisePythonScriptExecuteFinish(object sender, CommandExecuteResul $"Завершение выполнения: {remoteCommandExecuteResult.EndTime}\n" + $"Общее время выполнения: {remoteCommandExecuteResult.RunTime}\n" + $"Код выхода: {remoteCommandExecuteResult.ExitCode}\n" + - $"Статус успешности завершения: {remoteCommandExecuteResult.Succeeded}" + + $"Статус успешности завершения: {remoteCommandExecuteResult.ExitCode == 0}" + + + //The server returns an incorrect value, so the completion success status is determined by the exit code + //$"Статус успешности завершения: {remoteCommandExecuteResult.Succeesed}" + $"\n======================\n"; if (!string.IsNullOrEmpty(remoteCommandExecuteResult.StandardError)) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs index 75b2d86..b9aed0d 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs @@ -103,7 +103,7 @@ private void OnRaisePythonStandartOutput(object sender, string message) ResultTextEditor += message; } - private void OnRaisePythonScriptExecuteFinish(object sender, CommandExecuteResult remoteCommandExecuteResult) + private void OnRaisePythonScriptExecuteFinish(object sender, ExtendedCommandExecuteResult remoteCommandExecuteResult) { IsCodeExecuted = false; //ResultTextEditor += message; From d1282afd1399126f2f4d8abe167b9f5c9ead13e2 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 21 Apr 2024 12:54:34 +1000 Subject: [PATCH 110/181] Clean WebAPI legacy project. Close #39 --- .../Interfaces/IWebApiService.cs | 18 ++ AdamController.Services/WebApiService.cs | 72 ++++++ AdamController/App.xaml.cs | 45 +--- .../ViewModels/MainWindowViewModel.cs | 13 +- .../AdamController.WebApi.Client/ApiClient.cs | 85 ------- .../AdamController.WebApi.Client/BaseApi.cs | 30 +++ .../Common/Extension.cs | 79 +------ .../v1/AdamSdk.cs | 40 +++- .../v1/ApiClient.cs | 65 ++++++ .../v1/BaseApi.cs | 209 ------------------ .../v1/BashCommand.cs | 83 ------- .../v1/ComunicationManagment.cs | 34 --- .../v1/FileManager.cs | 171 -------------- .../v1/LoggerConfiguration.cs | 24 -- .../v1/PythonCommand.cs | 87 ++++---- .../v1/RequestModel/CameraResolution.cs | 10 - .../v1/RequestModel/ComunicationStatus.cs | 8 - ...PythonCommand.cs => PythonCommandModel.cs} | 5 +- .../v1/RequestModel/ServerCommand.cs | 9 - .../v1/ResponseModel/CommandExecuteResult.cs | 35 --- .../v1/SystemInfo.cs | 134 ++++++----- .../ComputerVisionControlViewModel.cs | 9 +- .../ViewModels/ScratchControlViewModel.cs | 21 +- .../ScriptEditorControlViewModel.cs | 11 +- .../AdvancedBlocklySettingsViewModel.cs | 4 +- .../ViewModels/NotificationViewModel.cs | 8 +- 26 files changed, 417 insertions(+), 892 deletions(-) create mode 100644 AdamController.Services/Interfaces/IWebApiService.cs create mode 100644 AdamController.Services/WebApiService.cs delete mode 100644 Legacy/AdamController.WebApi.Client/ApiClient.cs create mode 100644 Legacy/AdamController.WebApi.Client/BaseApi.cs create mode 100644 Legacy/AdamController.WebApi.Client/v1/ApiClient.cs delete mode 100644 Legacy/AdamController.WebApi.Client/v1/BaseApi.cs delete mode 100644 Legacy/AdamController.WebApi.Client/v1/BashCommand.cs delete mode 100644 Legacy/AdamController.WebApi.Client/v1/ComunicationManagment.cs delete mode 100644 Legacy/AdamController.WebApi.Client/v1/FileManager.cs delete mode 100644 Legacy/AdamController.WebApi.Client/v1/LoggerConfiguration.cs delete mode 100644 Legacy/AdamController.WebApi.Client/v1/RequestModel/CameraResolution.cs delete mode 100644 Legacy/AdamController.WebApi.Client/v1/RequestModel/ComunicationStatus.cs rename Legacy/AdamController.WebApi.Client/v1/RequestModel/{PythonCommand.cs => PythonCommandModel.cs} (76%) delete mode 100644 Legacy/AdamController.WebApi.Client/v1/RequestModel/ServerCommand.cs delete mode 100644 Legacy/AdamController.WebApi.Client/v1/ResponseModel/CommandExecuteResult.cs diff --git a/AdamController.Services/Interfaces/IWebApiService.cs b/AdamController.Services/Interfaces/IWebApiService.cs new file mode 100644 index 0000000..87f45ba --- /dev/null +++ b/AdamController.Services/Interfaces/IWebApiService.cs @@ -0,0 +1,18 @@ +using AdamController.WebApi.Client.v1.RequestModel; +using AdamController.WebApi.Client.v1.ResponseModel; +using System; +using System.Threading.Tasks; + +namespace AdamController.Services.Interfaces +{ + public interface IWebApiService : IDisposable + { + public Task StopPythonExecute(); + public Task GetPythonVersion(); + public Task GetPythonBinDir(); + public Task GetPythonWorkDir(); + public Task PythonExecuteAsync(PythonCommandModel command); + public Task MoveToZeroPosition(); + + } +} diff --git a/AdamController.Services/WebApiService.cs b/AdamController.Services/WebApiService.cs new file mode 100644 index 0000000..1216655 --- /dev/null +++ b/AdamController.Services/WebApiService.cs @@ -0,0 +1,72 @@ +using AdamController.Services.Interfaces; +using AdamController.WebApi.Client; +using AdamController.WebApi.Client.v1.RequestModel; +using AdamController.WebApi.Client.v1.ResponseModel; +using System; +using System.Threading.Tasks; + +namespace AdamController.Services +{ + public class WebApiService : IWebApiService + { + + #region Var + + private readonly BaseApi mBaseApi; + + #endregion + + #region ~ + + public WebApiService(string ip, int port, string login, string password) + { + Uri defaultUri = new($"http://{ip}:{port}"); + mBaseApi = new BaseApi(defaultUri, login, password); + + } + + #endregion + + #region Public methods + + public Task GetPythonBinDir() + { + return mBaseApi.PythonCommand.GetPythonBinDir(); + } + + public Task GetPythonVersion() + { + return mBaseApi.PythonCommand.GetVersion(); + } + + public Task GetPythonWorkDir() + { + return mBaseApi.PythonCommand.GetPythonWorkDir(); + } + + public Task PythonExecuteAsync(PythonCommandModel command) + { + return mBaseApi.PythonCommand.ExecuteAsync(command); + } + + + public Task StopPythonExecute() + { + return mBaseApi.PythonCommand.StopExecuteAsync(); + } + + public Task MoveToZeroPosition() + { + return mBaseApi.AdamSdk.MoveToZeroPosition(); + } + + public void Dispose() + { + mBaseApi.Dispose(); + } + + #endregion + } + + +} diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index ff5a50f..d26ffb9 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -76,22 +76,12 @@ protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); - //_ = FolderHelper.CreateAppDataFolder(); - //TODO check theme before ChangeTheme _ = ThemeManager.Current.ChangeTheme(this, $"{Settings.Default.BaseTheme}.{Settings.Default.ThemeColorScheme}", false); LoadHighlighting(); } - protected override void OnInitialized() - { - base.OnInitialized(); - - StartServices(); - StartWebApi(); - } - protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterSingleton(containerRegistry => @@ -127,8 +117,6 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return new FlyoutManager(container, regionManager); }); - - containerRegistry.RegisterSingleton(containerRegistry => { TcpClientOption option = new() @@ -185,6 +173,17 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) WebSocketClientService client = new(uri); return client; + }); + + containerRegistry.RegisterSingleton(containerRegistry => + { + string ip = Settings.Default.ServerIP; + int port = Settings.Default.ApiPort; + string login = Settings.Default.ApiLogin; + string password = Settings.Default.ApiPassword; + + WebApiService client = new(ip, port, login, password); + return client; }); @@ -211,26 +210,6 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) RegisterDialogs(containerRegistry); } - private void StartServices() - { - if (Settings.Default.AutoStartTcpConnect) - Container.Resolve().ConnectAllAsync(); - } - - private void StartWebApi() - { - string ip = Settings.Default.ServerIP; - int port = Settings.Default.ApiPort; - - Uri DefaultUri = new($"http://{ip}:{port}"); - WebApi.Client.v1.BaseApi.SetApiClientUri(DefaultUri); - - string login = Settings.Default.ApiLogin; - string password = Settings.Default.ApiPassword; - - WebApi.Client.v1.BaseApi.SetAuthenticationHeader(login, password); - } - private static void RegisterDialogs(IContainerRegistry containerRegistry) { containerRegistry.RegisterDialog(); @@ -241,7 +220,6 @@ private static void RegisterDialogs(IContainerRegistry containerRegistry) var app = Current; return new DialogManager(app); }); - } protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings) @@ -312,6 +290,7 @@ private void DisposeServices() Container.Resolve().Dispose(); Container.Resolve().Dispose(); + Container.Resolve().Dispose(); } #region Intercepting Unhandled Exception diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index 1d769bf..797d027 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -4,7 +4,6 @@ using AdamController.Core.Mvvm; using AdamController.Core.Properties; using AdamController.Services.Interfaces; -using AdamController.WebApi.Client.v1; using Prism.Commands; using Prism.Regions; using System.Reflection; @@ -27,20 +26,25 @@ public class MainWindowViewModel : ViewModelBase private readonly IStatusBarNotificationDeliveryService mStatusBarNotification; private readonly ICommunicationProviderService mCommunicationProviderService; private readonly IFolderManagmentService mFolderManagment; + private readonly IWebApiService mWebApiService; + #endregion #region ~ public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService, IStatusBarNotificationDeliveryService statusBarNotification, - ICommunicationProviderService communicationProviderService, IFolderManagmentService folderManagment) + ICommunicationProviderService communicationProviderService, IFolderManagmentService folderManagment, IWebApiService webApiService) { RegionManager = regionManager; + mWebApiService = webApiService; mSubRegionChangeAwareService = subRegionChangeAwareService; mStatusBarNotification = statusBarNotification; mCommunicationProviderService = communicationProviderService; mFolderManagment = folderManagment; + + ShowRegionCommand = new DelegateCommand(ShowRegion); Subscribe(); } @@ -204,6 +208,9 @@ private void MainWindowLoaded(object sender, RoutedEventArgs e) SaveFolderPathToSettings(); ShowRegionCommand.Execute(SubRegionNames.SubRegionScratch); mStatusBarNotification.CompileLogMessage = "Загрузка приложения завершена"; + + if (Settings.Default.AutoStartTcpConnect) + mCommunicationProviderService.ConnectAllAsync(); } /// @@ -222,7 +229,7 @@ private void RaiseSubRegionChangeEvent(object sender) /// private void RaiseTcpServiceCientConnectedEvent(object sender) { - _ = BaseApi.StopPythonExecute(); + mWebApiService.StopPythonExecute(); } private void RaiseUdpServiceServerReceivedEvent(object sender, string message) diff --git a/Legacy/AdamController.WebApi.Client/ApiClient.cs b/Legacy/AdamController.WebApi.Client/ApiClient.cs deleted file mode 100644 index 50198d9..0000000 --- a/Legacy/AdamController.WebApi.Client/ApiClient.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System.Net.Http.Headers; -using System.Text; - -namespace AdamController.WebApi.Client -{ - public class ApiClient - { - private static readonly HttpClient mClient = new(); - private static readonly MediaTypeWithQualityHeaderValue mMediaTypeHeader = new("application/json"); - private const string cDefaultApiPath = "api/"; - - static ApiClient() - { - mClient.DefaultRequestHeaders.Accept.Clear(); - mClient.DefaultRequestHeaders.Add("X-Version", "1"); - mClient.DefaultRequestHeaders.Accept.Add(mMediaTypeHeader); - } - - internal static void SetAuthenticationHeaderValue(string login, string password) - { - AuthenticationHeaderValue defaultAutentificationHeader = new("Basic", - Convert.ToBase64String(Encoding.UTF8.GetBytes($"{login}:{password}"))); - - mClient.DefaultRequestHeaders.Authorization = defaultAutentificationHeader; - } - - internal static void SetUri(Uri uri) - { - mClient.BaseAddress = uri; - } - - internal static void SetUri(string uri) - { - mClient.BaseAddress = new($"{uri}"); - } - - internal static void SetUri(string ip, int port) - { - mClient.BaseAddress = new($"http://{ip}:{port}"); - } - - internal static async Task Put(string path) - { - HttpResponseMessage? responseMessage = await mClient.PutAsync($"{cDefaultApiPath}{path}", null); - responseMessage.EnsureSuccessStatusCode(); - - return responseMessage; - } - - internal static async Task Get(string path) - { - HttpResponseMessage? responseMessage = await mClient.GetAsync($"{cDefaultApiPath}{path}"); - responseMessage.EnsureSuccessStatusCode(); - - return responseMessage; - } - - internal static async Task Post(string path, string command) - { - StringContent content = new(command); - var result = await mClient.PostAsync($"{cDefaultApiPath}{path}", content); - return result; - } - - internal static async Task Post(string path, v1.RequestModel.PythonCommand command) - { - var result = await mClient.PostAsJsonAsync($"{cDefaultApiPath}{path}", command); - return result; - } - - internal static async Task Post(string path, string filePath, string name, string fileName) - { - - using (var content = new MultipartFormDataContent("Upload--------------------" + DateTime.Now.ToString())) - { - var fileStreamContent = new StreamContent(File.OpenRead(filePath)); - content.Add(fileStreamContent, name, fileName); - var result = await mClient.PostAsync($"{cDefaultApiPath}{path}", content); - - return result; - } - - } - } -} \ No newline at end of file diff --git a/Legacy/AdamController.WebApi.Client/BaseApi.cs b/Legacy/AdamController.WebApi.Client/BaseApi.cs new file mode 100644 index 0000000..514c4c8 --- /dev/null +++ b/Legacy/AdamController.WebApi.Client/BaseApi.cs @@ -0,0 +1,30 @@ +using AdamController.WebApi.Client.v1; + +namespace AdamController.WebApi.Client +{ + public class BaseApi : IDisposable + { + private readonly ApiClient mApiClient; + private readonly IAdamSdk mAdamSdk; + private readonly IPythonCommand mPythonCommand; + private readonly ISystemInfo mSystemInfo; + + public BaseApi(Uri uri, string login, string password) + { + mApiClient = new ApiClient(uri, login, password); + + mAdamSdk = new AdamSdk(mApiClient); + mPythonCommand = new PythonCommand(mApiClient); + mSystemInfo = new SystemInfo(mApiClient); + } + + public IAdamSdk AdamSdk { get { return mAdamSdk; } } + public ISystemInfo SystemInfo { get { return mSystemInfo; } } + public IPythonCommand PythonCommand { get { return mPythonCommand; } } + public void Dispose() + { + mApiClient.Dispose(); + } + + } +} diff --git a/Legacy/AdamController.WebApi.Client/Common/Extension.cs b/Legacy/AdamController.WebApi.Client/Common/Extension.cs index f3eb003..2e37de4 100644 --- a/Legacy/AdamController.WebApi.Client/Common/Extension.cs +++ b/Legacy/AdamController.WebApi.Client/Common/Extension.cs @@ -1,64 +1,37 @@ using AdamController.WebApi.Client.v1.ResponseModel; -using System.Text; using System.Text.Json; -using System.Web; namespace AdamController.WebApi.Client.Common { public static class Extension { - private static JsonSerializerOptions mJsonSerializerOptions = new() + private static readonly JsonSerializerOptions mJsonSerializerOptions = new() { PropertyNameCaseInsensitive = true }; - public async static Task ToExtendedCommandResult(this HttpResponseMessage? response) + internal static Task ToExtendedCommandResultAsync(this Task response) { if (response == null) - return new ExtendedCommandExecuteResult(); + return Task.FromResult(new ExtendedCommandExecuteResult()); - var jsonString = await response.Content.ReadAsStringAsync(); - var result = jsonString.ToExtendedCommandResult(); - return result; - } - - /*public async static Task ToCommandResult(this HttpResponseMessage? response) - { - if (response == null) - return new CommandExecuteResult(); - - string jsonString = await response.Content.ReadAsStringAsync(); + Task result = Task.Run(async () => + { + var responseMessage = await response; + var jsonString = await responseMessage.Content.ReadAsStringAsync(); + var result = jsonString.ToExtendedCommandResult(); + return result; + }); - var result = jsonString.ToCommandResult(); return result; } - public static CommandExecuteResult ToCommandResult(this string jsonString) - { - CommandExecuteResult result = new(); - - try - { - CommandExecuteResult? deleserialize = JsonSerializer.Deserialize(jsonString); - - if (deleserialize != null) - result = deleserialize; - - return result; - } - catch - { - return result; - } - }*/ - public static ExtendedCommandExecuteResult ToExtendedCommandResult(this string jsonString) { ExtendedCommandExecuteResult result = new(); try { - ExtendedCommandExecuteResult? deleserialize = JsonSerializer.Deserialize(jsonString, mJsonSerializerOptions); if (deleserialize != null) @@ -71,37 +44,5 @@ public static ExtendedCommandExecuteResult ToExtendedCommandResult(this string j return result; } } - - #region internal extension - - /*internal static string FromBase64ToString(this string base64string) - { - byte[] base64EncodedBytes = Convert.FromBase64String(base64string); - string decodedString = Encoding.UTF8.GetString(base64EncodedBytes); - - return decodedString; - }*/ - - internal static string FromStringToBase64String(this string @string) - { - byte[] plainTextBytes = Encoding.UTF8.GetBytes(@string); - string encodedToBase64String = Convert.ToBase64String(plainTextBytes); - - return encodedToBase64String; - } - - internal static string FromStringToUrlEncodeString(this string @string) - { - string encodedToUrlEncodeString = HttpUtility.UrlEncode(@string); - return encodedToUrlEncodeString; - } - - /*internal static string FromUrlEncodeToString(this string @string) - { - string encodedToUrlEncodeString = HttpUtility.UrlDecode(@string); - return encodedToUrlEncodeString; - }*/ - - #endregion } } diff --git a/Legacy/AdamController.WebApi.Client/v1/AdamSdk.cs b/Legacy/AdamController.WebApi.Client/v1/AdamSdk.cs index f455826..f58140f 100644 --- a/Legacy/AdamController.WebApi.Client/v1/AdamSdk.cs +++ b/Legacy/AdamController.WebApi.Client/v1/AdamSdk.cs @@ -3,15 +3,47 @@ namespace AdamController.WebApi.Client.v1 { - internal class AdamSdk + #region Interface + + public interface IAdamSdk + { + public Task MoveToZeroPosition(); + } + + #endregion + + internal class AdamSdk : IAdamSdk { + #region Const + private const string cApiPath = "AdamSdk"; - internal static async Task MoveToZeroPosition() + #endregion + + #region Var + + private readonly ApiClient mClient; + + #endregion + + #region ~ + + internal AdamSdk(ApiClient client) + { + mClient = client; + } + + #endregion + + #region Public methods + + public Task MoveToZeroPosition() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/MoveToZeroPosition"); - var result = await responseMessage.ToExtendedCommandResult(); + Task responseMessage = mClient.Get($"{cApiPath}/MoveToZeroPosition"); + Task result = responseMessage.ToExtendedCommandResultAsync(); return result; } + + #endregion } } diff --git a/Legacy/AdamController.WebApi.Client/v1/ApiClient.cs b/Legacy/AdamController.WebApi.Client/v1/ApiClient.cs new file mode 100644 index 0000000..899fc05 --- /dev/null +++ b/Legacy/AdamController.WebApi.Client/v1/ApiClient.cs @@ -0,0 +1,65 @@ +using System.Net.Http.Headers; +using System.Text; + +namespace AdamController.WebApi.Client.v1 +{ + internal class ApiClient + { + #region Const + + private const string cDefaultApiPath = "api/"; + + #endregion + + #region Var + + private readonly HttpClient mClient; + private readonly MediaTypeWithQualityHeaderValue mMediaTypeHeader = new("application/json"); + + #endregion + + #region ~ + + internal ApiClient(Uri uri, string login, string password) + { + mClient = new(); + mClient.DefaultRequestHeaders.Accept.Clear(); + mClient.DefaultRequestHeaders.Add("X-Version", "1"); + mClient.DefaultRequestHeaders.Accept.Add(mMediaTypeHeader); + + AuthenticationHeaderValue defaultAutentificationHeader = new("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{login}:{password}"))); + + mClient.BaseAddress = uri; + mClient.DefaultRequestHeaders.Authorization = defaultAutentificationHeader; + } + + #endregion + + #region Methods + + internal Task Put(string path) + { + var responseMessage = mClient.PutAsync($"{cDefaultApiPath}{path}", null); + return responseMessage; + } + + internal Task Get(string path) + { + var responseMessage = mClient.GetAsync($"{cDefaultApiPath}{path}"); + return responseMessage; + } + + internal Task Post(string path, RequestModel.PythonCommandModel command) + { + var result = mClient.PostAsJsonAsync($"{cDefaultApiPath}{path}", command); + return result; + } + + internal void Dispose() + { + mClient.Dispose(); + } + + #endregion + } +} \ No newline at end of file diff --git a/Legacy/AdamController.WebApi.Client/v1/BaseApi.cs b/Legacy/AdamController.WebApi.Client/v1/BaseApi.cs deleted file mode 100644 index ded8d89..0000000 --- a/Legacy/AdamController.WebApi.Client/v1/BaseApi.cs +++ /dev/null @@ -1,209 +0,0 @@ -using AdamController.WebApi.Client.v1.RequestModel; -using AdamController.WebApi.Client.v1.ResponseModel; - -namespace AdamController.WebApi.Client.v1 -{ - public static class BaseApi - { - #region Api Client Settings (is not api call) - - public static void SetApiClientUri(Uri uri) => ApiClient.SetUri(uri); - public static void SetApiClientUri(string uri) => ApiClient.SetUri(uri); - public static void SetApiClientUri(string ip, int port) => ApiClient.SetUri(ip, port); - public static void SetAuthenticationHeader(string login, string password) => ApiClient.SetAuthenticationHeaderValue(login, password); - - #endregion - - - #region AdamSdk - - public static async Task MoveToZeroPosition() => await AdamSdk.MoveToZeroPosition(); - - #endregion - - #region BashCommand - - /// - /// Execute with waiting and return json result to http api. - /// Command canceled after 30 second automatic. - /// - /// Bash command or programm - /// JSON object ExtendedShellCommandExecuteResult - public static async Task BashExecute(string command) => await BashCommand.Execute(command); - - /// - /// Execute with waiting and return json result to http api - /// - /// Bash command or programm - /// Command canceled after 30 second automatic if null - /// JSON object ExtendedShellCommandExecuteResult as http response - public static async Task BashExecute(string command, int cancelAfterSeconds) => await BashCommand.Execute(command, cancelAfterSeconds); - - /// - /// Execute without waiting. Return execute result in udp stream - /// - /// Python command or programm - /// ExtendedShellCommandExecuteResult as http-response with report about running process - /// and UDP stream by message client with result running process - public static async Task BashExecuteAsync(string command) => await BashCommand.ExecuteAsync(command); - - /// - /// Execute without waiting. With cancelation timer. Return execute result in udp stream. - /// - /// Bash command or programm - /// Task canceled after this time in seconds - /// ExtendedShellCommandExecuteResult as http-response with report about running process - /// and UDP stream by message client with result running process - public static async Task BashExecuteAsyncWithCancelTimer(string command, int cancelAfterSeconds) => await BashCommand.ExecuteAsyncWithCancelTimer(command, cancelAfterSeconds); - - /// - /// Stopped running process - /// - public static async Task BashPythonExecute() => await BashCommand.StopExecuteAsync(); - - /// - /// Returned bash version - /// - /// ExtendedShellCommandExecuteResult with bash version in standart output - public static async Task GetBashVersion() => await BashCommand.GetVersion(); - - #endregion - - #region ComunicationManagment - - public static Task GetServersStatus() => ComunicationManagment.GetServersStatus(); - public static Task GetServerStatus(string serverName) => ComunicationManagment.GetServerStatus(serverName); - public static Task SendCommand(ServerCommand command, string serverName) => ComunicationManagment.SendCommand(command, serverName); - - #endregion - - #region FileManager - - /// - /// Listing dirrectory - /// - public static Task GetFileList() => FileManager.GetFileList(); - - /// - /// Listing dirrectory - /// - /// Exiting dirrectory path - public static Task GetFileList(string path) => FileManager.GetFileList(path); - - /// - /// Extended listing dirrectory - /// - public static Task GetExtendedFileList() => FileManager.GetExtendedFileList(); - - /// - /// Extended listing dirrectory - /// - /// Exiting dirrectory path - public static Task GetExtendedFileList(string path) => FileManager.GetExtendedFileList(path); - - /// - /// Cat file - /// - /// Exiting file path - public static Task GetFileContent(string path) => FileManager.GetFileContent(path); - - /// - /// Calculate the checksum for file - /// - /// Exiting file path - public static Task GetCheckSum(string path) => FileManager.GetCheckSum(path); - - /// - /// Calculate the SHA-1 checksum for file - /// - /// Exiting file path - public static Task GetSha1Sum(string path) => FileManager.GetSha1Sum(path); - - /// - /// Calculate the SHA-256 checksum for file - /// - /// Exiting file path - public static Task GetSha256Sum(string path) => FileManager.GetSha256Sum(path); - - /// - /// Simple file uploaded - /// - /// sha1sum in standart output field is success upload - public static Task UploadFile(string filePath, string name, string fileName) => FileManager.UploadFile(filePath, name, fileName); - - /// - /// Simple file uploaded - /// - /// sha1sum in standart output field is success upload - //public static Task UploadFile(string file, string name, string fileName) => FileManager.UploadFile(file, name, fileName); - - - #endregion - - #region LoggerConfiguration - - public static Task DisableUdpSyslog() => LoggerConfiguration.DisableUdpSyslog(); - public static Task EnableUdpSyslog(string ip) => LoggerConfiguration.EnableUdpSyslog(ip); - - #endregion - - #region PythonCommand - - /// - /// Execute with waiting and return json result to http api. - /// Command canceled after 30 second automatic. - /// - /// Python command or programm - /// JSON object ExtendedShellCommandExecuteResult - public static async Task PythonExecute(RequestModel.PythonCommand command) => await PythonCommand.Execute(command); - - /// - /// Execute with waiting and return json result to http api - /// - /// Python command or programm - /// Command canceled after 30 second automatic if null - /// JSON object ExtendedShellCommandExecuteResult as http response - //public static async Task PythonExecute(string command, int cancelAfterSeconds) => await PythonCommand.Execute(command, cancelAfterSeconds); - - /// - /// Execute without waiting. Return execute result in udp stream - /// - /// Python command or programm in JSON structure - /// ExtendedShellCommandExecuteResult as http-response with report about running process - /// and UDP stream by message client with result running process - public static async Task PythonExecuteAsync(RequestModel.PythonCommand command) => await PythonCommand.ExecuteAsync(command); - - /// - /// Execute without waiting. Return execute result in udp stream - /// - /// Python command or programm - /// ExtendedShellCommandExecuteResult as http-response with report about running process - /// and UDP stream by message client with result running process - public static async Task PythonExecuteAsync(string command) => await PythonCommand.ExecuteAsync(command); - - /// - /// Stopped running process - /// - public static async Task StopPythonExecute() => await PythonCommand.StopExecuteAsync(); - - /// - /// Returned python version - /// - /// ExtendedShellCommandExecuteResult with python version in standart output - public static async Task GetPythonVersion() => await PythonCommand.GetVersion(); - - /// - /// Returned python bin dirrectory - /// - /// ExtendedShellCommandExecuteResult with python version in standart output - public static async Task GetPythonBinDir() => await PythonCommand.GetPythonBinDir(); - - /// - /// Returned python work dirrectory - /// - /// ExtendedShellCommandExecuteResult with python version in standart output - public static async Task GetPythonWorkDir() => await PythonCommand.GetPythonWorkDir(); - - #endregion - } -} diff --git a/Legacy/AdamController.WebApi.Client/v1/BashCommand.cs b/Legacy/AdamController.WebApi.Client/v1/BashCommand.cs deleted file mode 100644 index edec82a..0000000 --- a/Legacy/AdamController.WebApi.Client/v1/BashCommand.cs +++ /dev/null @@ -1,83 +0,0 @@ -using AdamController.WebApi.Client.Common; -using AdamController.WebApi.Client.v1.ResponseModel; - -namespace AdamController.WebApi.Client.v1 -{ - internal class BashCommand - { - private const string cApiPath = "BashCommand"; - - /// - /// Execute with waiting and return json result to http api. - /// Command canceled after 30 second automatic. - /// - /// Bash command or programm - /// JSON object ExtendedShellCommandExecuteResult - internal static async Task Execute(string command) - { - HttpResponseMessage? responseMessage = await ApiClient.Put($"{cApiPath}/Execute/{command.FromStringToUrlEncodeString()}/cancelAfter?cancelAfterSeconds=-1"); - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - /// - /// Execute with waiting and return json result to http api - /// - /// Bash command or programm - /// Command canceled after 30 second automatic if null - /// JSON object ExtendedShellCommandExecuteResult as http response - internal static async Task Execute(string command, int cancelAfterSeconds) - { - HttpResponseMessage? responseMessage = await ApiClient.Put($"{cApiPath}/Execute/{command.FromStringToUrlEncodeString()}/cancelAfter?cancelAfterSeconds={cancelAfterSeconds}"); - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - /// - /// Execute without waiting. Return execute result in udp stream - /// - /// Bash command or programm - /// ExtendedShellCommandExecuteResult as http-response with report about running process - /// and UDP stream by message client with result running process - internal static async Task ExecuteAsync(string command) - { - HttpResponseMessage? responseMessage = await ApiClient.Put($"{cApiPath}/ExecuteAsync/{command.FromStringToUrlEncodeString()}"); - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - /// - /// Execute without waiting. With cancelation timer. Return execute result in udp stream. - /// - /// Bash command or programm - /// Task canceled after this time in seconds - /// ExtendedShellCommandExecuteResult as http-response with report about running process - /// and UDP stream by message client with result running process - internal static async Task ExecuteAsyncWithCancelTimer(string command, int cancelAfterSeconds) - { - HttpResponseMessage? responseMessage = await ApiClient.Put($"{cApiPath}/ExecuteAsyncWithCancelTimer/{command.FromStringToUrlEncodeString()}/{cancelAfterSeconds}"); - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - /// - /// Stopped running process - /// - internal static async Task StopExecuteAsync() - { - HttpResponseMessage? responseMessage = await ApiClient.Put($"{cApiPath}/StopExecuteAsync"); - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - /// - /// Returned bash version - /// - /// ExtendedShellCommandExecuteResult with bash version in standart output - internal static async Task GetVersion() - { - ExtendedCommandExecuteResult? responseValue = await Execute("bash --version"); - return responseValue; - } - } -} \ No newline at end of file diff --git a/Legacy/AdamController.WebApi.Client/v1/ComunicationManagment.cs b/Legacy/AdamController.WebApi.Client/v1/ComunicationManagment.cs deleted file mode 100644 index b924849..0000000 --- a/Legacy/AdamController.WebApi.Client/v1/ComunicationManagment.cs +++ /dev/null @@ -1,34 +0,0 @@ -using AdamController.WebApi.Client.v1.RequestModel; - -namespace AdamController.WebApi.Client.v1 -{ - internal class ComunicationManagment - { - private const string cApiPath = "ComunicationManagment"; - - internal static async Task GetServersStatus() - { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetServersStatus"); - - ComunicationStatus responseValue = await responseMessage.Content.ReadAsAsync(); - return responseValue; - } - - internal static async Task GetServerStatus(string serverName) - { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetServerStatus/{serverName}"); - - string responseValue = await responseMessage.Content.ReadAsAsync(); - return responseValue; - } - - internal static async Task SendCommand(ServerCommand command, string serverName) - { - HttpResponseMessage? responseMessage = await ApiClient.Put($"{cApiPath}/SendCommand/{serverName}/{command}"); - - bool responseValue = await responseMessage.Content.ReadAsAsync(); - return responseValue; - } - - } -} diff --git a/Legacy/AdamController.WebApi.Client/v1/FileManager.cs b/Legacy/AdamController.WebApi.Client/v1/FileManager.cs deleted file mode 100644 index c4d52d8..0000000 --- a/Legacy/AdamController.WebApi.Client/v1/FileManager.cs +++ /dev/null @@ -1,171 +0,0 @@ -using AdamController.WebApi.Client.Common; -using AdamController.WebApi.Client.v1.ResponseModel; - -namespace AdamController.WebApi.Client.v1 -{ - internal class FileManager - { - private const string cApiPath = "FileManager"; - - #region Listing dirrectory - - /// - /// Listing dirrectory - /// - internal static async Task GetFileList() - { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetFileList"); - - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - /// - /// Listing dirrectory - /// - /// Exiting dirrectory path - /// - internal static async Task GetFileList(string path) - { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetFileList/{path.FromStringToBase64String()}"); - - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - #endregion - - #region Extended listing dirrectory - - /// - /// Extended listing dirrectory - /// - internal static async Task GetExtendedFileList() - { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetExtendedFileList"); - - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - /// - /// Extended listing dirrectory - /// - /// Exiting dirrectory path - /// - internal static async Task GetExtendedFileList(string path) - { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetExtendedFileList/{path.FromStringToBase64String()}"); - - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - #endregion - - #region GetFileContent - - /// - /// Cat file - /// - /// Exiting file path - internal static async Task GetFileContent(string path) - { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetFileContent/{path.FromStringToBase64String()}"); - - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - #endregion - - #region CheckSum - - /// - /// Calculate the checksum for file - /// - internal static async Task GetCheckSum(string path) - { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetCheckSum/{path.FromStringToBase64String()}"); - - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - /// - /// Calculate the SHA-1 checksum for file - /// - internal static async Task GetSha1Sum(string path) - { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetSha1Sum/{path.FromStringToBase64String()}"); - - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - /// - /// Calculate the SHA-256 checksum for file - /// - internal static async Task GetSha256Sum(string path) - { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetSha256Sum/{path.FromStringToBase64String()}"); - - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - #endregion - - #region Upload File - - /// - /// Simple file uploaded - /// - /// sha1sum in standart output field is success upload - internal static async Task UploadFile(string filePath, string name, string fileName) - { - HttpResponseMessage? responseMessage = await ApiClient.Post($"{cApiPath}/UploadFile", filePath, name, fileName); - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - /// - /// Simple file uploaded - /// - /// sha1sum in standart output field is success upload - /*internal static async Task UploadFile(string filePath, string name, string fileName) - { - byte[] file; - DateTime startTime = DateTime.Now; - - try - { - file = File.ReadAllBytes(filePath); - } - catch(Exception ex) - { - DateTime endTime = DateTime.Now; - - return new ExtendedCommandExecuteResult() - { - StartTime = startTime, - EndTime = endTime, - RunTime = endTime - startTime, - - StandardOutput = "", - StandardError = ex.Message, - - ExitCode = -1, - Succeesed = false - }; - } - - HttpResponseMessage? responseMessage = await ApiClient.Post($"{cApiPath}/UploadFile", file, name, fileName); - ExtendedCommandExecuteResult responseValue = await responseMessage?.Content.ReadAsAsync(); - - return responseValue; - }*/ - - #endregion - } -} \ No newline at end of file diff --git a/Legacy/AdamController.WebApi.Client/v1/LoggerConfiguration.cs b/Legacy/AdamController.WebApi.Client/v1/LoggerConfiguration.cs deleted file mode 100644 index ad584d9..0000000 --- a/Legacy/AdamController.WebApi.Client/v1/LoggerConfiguration.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace AdamController.WebApi.Client.v1 -{ - internal static class LoggerConfiguration - { - private const string cApiPath = "LoggerConfiguration"; - - internal static async Task DisableUdpSyslog() - { - HttpResponseMessage? responseMessage = await ApiClient.Put($"{cApiPath}/DisableUdpSyslog"); - - bool responseValue = await responseMessage.Content.ReadAsAsync(); - return responseValue; - - } - - internal static async Task EnableUdpSyslog(string ip) - { - HttpResponseMessage? responseMessage = await ApiClient.Put($"{cApiPath}/EnableUdpSyslog/{ip}"); - - bool responseValue = await responseMessage.Content.ReadAsAsync(); - return responseValue; - } - } -} diff --git a/Legacy/AdamController.WebApi.Client/v1/PythonCommand.cs b/Legacy/AdamController.WebApi.Client/v1/PythonCommand.cs index a500c02..b839c56 100644 --- a/Legacy/AdamController.WebApi.Client/v1/PythonCommand.cs +++ b/Legacy/AdamController.WebApi.Client/v1/PythonCommand.cs @@ -3,54 +3,63 @@ namespace AdamController.WebApi.Client.v1 { - internal class PythonCommand + #region Interface + + public interface IPythonCommand { + public Task ExecuteAsync(RequestModel.PythonCommandModel command); + public Task StopExecuteAsync(); + public Task GetVersion(); + public Task GetPythonWorkDir(); + public Task GetPythonBinDir(); + } + + #endregion + + internal class PythonCommand : IPythonCommand + { + #region Const + private const string cApiPath = "PythonCommand"; - /// - /// Execute with waiting and return json result to http api - /// - /// - /// - internal static async Task Execute(RequestModel.PythonCommand command) + #endregion + + #region Var + + private readonly ApiClient mApiClient; + + #endregion + + #region ~ + + internal PythonCommand(ApiClient apiClient) { - HttpResponseMessage? responseMessage = await ApiClient.Post($"{cApiPath}/Execute/", command); - var result = await responseMessage.ToExtendedCommandResult(); - return result; + mApiClient = apiClient; } + #endregion + + #region Public methods + /// /// Execute without waiting. Return execute result in udp stream /// /// /// - internal static async Task ExecuteAsync(RequestModel.PythonCommand command) - { - HttpResponseMessage? responseMessage = await ApiClient.Post($"{cApiPath}/ExecuteAsync/", command); - var result = await responseMessage.ToExtendedCommandResult(); - return result; - } - - /// - /// Execute without waiting. Return execute result in udp stream - /// - /// Python command or programm - /// ExtendedShellCommandExecuteResult as http-response with report about running process - /// and UDP stream by message client with result running process - internal static async Task ExecuteAsync(string command) + public Task ExecuteAsync(RequestModel.PythonCommandModel command) { - HttpResponseMessage? responseMessage = await ApiClient.Put($"{cApiPath}/ExecuteAsync/{command.FromStringToUrlEncodeString()}"); - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Post($"{cApiPath}/ExecuteAsync/", command); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } /// /// Stopped running process /// - internal static async Task StopExecuteAsync() + public Task StopExecuteAsync() { - HttpResponseMessage? responseMessage = await ApiClient.Put($"{cApiPath}/StopExecuteAsync"); - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Put($"{cApiPath}/StopExecuteAsync"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } @@ -58,10 +67,10 @@ internal static async Task StopExecuteAsync() /// Returned python version /// /// ExtendedShellCommandExecuteResult with python version in standart output - internal static async Task GetVersion() + public Task GetVersion() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetVersion"); - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetVersion"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } @@ -69,10 +78,10 @@ internal static async Task GetVersion() /// Returned python work dir /// /// ExtendedShellCommandExecuteResult with python version in standart output - internal static async Task GetPythonWorkDir() + public Task GetPythonWorkDir() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetPythonWorkDir"); - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetPythonWorkDir"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } @@ -80,11 +89,13 @@ internal static async Task GetPythonWorkDir() /// Returned python bin dir /// /// ExtendedShellCommandExecuteResult with python version in standart output - internal static async Task GetPythonBinDir() + public Task GetPythonBinDir() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetPythonBinDir"); - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetPythonBinDir"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } + + #endregion } } diff --git a/Legacy/AdamController.WebApi.Client/v1/RequestModel/CameraResolution.cs b/Legacy/AdamController.WebApi.Client/v1/RequestModel/CameraResolution.cs deleted file mode 100644 index 99472b5..0000000 --- a/Legacy/AdamController.WebApi.Client/v1/RequestModel/CameraResolution.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace AdamController.WebApi.Client.v1.RequestModel -{ - public enum CameraResolution - { - FullRes, - MiddleRes, - LowRes, - LowestRes - } -} diff --git a/Legacy/AdamController.WebApi.Client/v1/RequestModel/ComunicationStatus.cs b/Legacy/AdamController.WebApi.Client/v1/RequestModel/ComunicationStatus.cs deleted file mode 100644 index 59dcfb2..0000000 --- a/Legacy/AdamController.WebApi.Client/v1/RequestModel/ComunicationStatus.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace AdamController.WebApi.Client.v1.RequestModel -{ - public class ComunicationStatus - { - internal string ServerName { get; set; } = string.Empty; - internal string ServerStatus { get; set; } = string.Empty; - } -} diff --git a/Legacy/AdamController.WebApi.Client/v1/RequestModel/PythonCommand.cs b/Legacy/AdamController.WebApi.Client/v1/RequestModel/PythonCommandModel.cs similarity index 76% rename from Legacy/AdamController.WebApi.Client/v1/RequestModel/PythonCommand.cs rename to Legacy/AdamController.WebApi.Client/v1/RequestModel/PythonCommandModel.cs index ed8239e..d4fad21 100644 --- a/Legacy/AdamController.WebApi.Client/v1/RequestModel/PythonCommand.cs +++ b/Legacy/AdamController.WebApi.Client/v1/RequestModel/PythonCommandModel.cs @@ -1,7 +1,6 @@ - -namespace AdamController.WebApi.Client.v1.RequestModel +namespace AdamController.WebApi.Client.v1.RequestModel { - public class PythonCommand + public class PythonCommandModel { /// /// Python command or programm diff --git a/Legacy/AdamController.WebApi.Client/v1/RequestModel/ServerCommand.cs b/Legacy/AdamController.WebApi.Client/v1/RequestModel/ServerCommand.cs deleted file mode 100644 index 81fa1e1..0000000 --- a/Legacy/AdamController.WebApi.Client/v1/RequestModel/ServerCommand.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace AdamController.WebApi.Client.v1.RequestModel -{ - public enum ServerCommand - { - Stop, - Start, - Restart - } -} diff --git a/Legacy/AdamController.WebApi.Client/v1/ResponseModel/CommandExecuteResult.cs b/Legacy/AdamController.WebApi.Client/v1/ResponseModel/CommandExecuteResult.cs deleted file mode 100644 index ab851e1..0000000 --- a/Legacy/AdamController.WebApi.Client/v1/ResponseModel/CommandExecuteResult.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace AdamController.WebApi.Client.v1.ResponseModel -{ - /*public class CommandExecuteResult - { - /// - /// The succeeded status of an executable. - /// - public bool Succeeded { get; set; } - - /// - /// The exit code of an executable. - /// - public int ExitCode { get; set; } - - /// - /// The standard error of an executable. - /// - public string StandardError { get; set; } = string.Empty; - - /// - /// The start time of an executable. - /// - public DateTime StartTime { get; set; } - - /// - /// The end time of an executable. - /// - public DateTime EndTime { get; set; } - - /// - /// The run time of an executable. - /// - public TimeSpan RunTime { get; set; } - }*/ -} diff --git a/Legacy/AdamController.WebApi.Client/v1/SystemInfo.cs b/Legacy/AdamController.WebApi.Client/v1/SystemInfo.cs index 27dfb43..a99a821 100644 --- a/Legacy/AdamController.WebApi.Client/v1/SystemInfo.cs +++ b/Legacy/AdamController.WebApi.Client/v1/SystemInfo.cs @@ -1,34 +1,72 @@ - - -using AdamController.WebApi.Client.Common; +using AdamController.WebApi.Client.Common; using AdamController.WebApi.Client.v1.ResponseModel; namespace AdamController.WebApi.Client.v1 { - internal class SystemInfo + #region Interface + + public interface ISystemInfo + { + public Task GetExtendedUptimeAndLoadAverage(); + public Task GetUptimeAndLoadAverage(); + public Task GetLoadAverage(); + public Task GetOsReleaseVersion(); + public Task GetDebianOsVersion(); + public Task GetArchitectureOsVersion(); + public Task GetKernelVersion(); + public Task GetGpuTemp(); + public Task GetCpuTemp(); + public Task GetNetworkInfo(); + public Task GetIpInfo(); + public Task GetWiFiSsids(); + public Task GetAdamServerVersion(); + } + + #endregion + + internal class SystemInfo : ISystemInfo { + #region Const + private const string cApiPath = "SystemInfo"; + #endregion + + #region Var + + private readonly ApiClient mApiClient; + + #endregion + + #region ~ + + internal SystemInfo(ApiClient apiClient) + { + mApiClient = apiClient; + } + + #endregion + #region System average - internal static async Task GetExtendedUptimeAndLoadAverage() + public Task GetExtendedUptimeAndLoadAverage() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetExtendedUptimeAndLoadAverage"); - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetExtendedUptimeAndLoadAverage"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } - internal static async Task GetUptimeAndLoadAverage() + public Task GetUptimeAndLoadAverage() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetUptimeAndLoadAverage"); - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetUptimeAndLoadAverage"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } - internal static async Task GetLoadAverage() + public Task GetLoadAverage() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetLoadAverage"); - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetLoadAverage"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } @@ -36,35 +74,31 @@ internal static async Task GetLoadAverage() #region OS version - internal static async Task GetOsReleaseVersion() + public Task GetOsReleaseVersion() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetOsReleaseVersion"); - - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetOsReleaseVersion"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } - internal static async Task GetDebianOsVersion() + public Task GetDebianOsVersion() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetDebianOsVersion"); - - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetDebianOsVersion"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } - internal static async Task GetArchitectureOsVersion() + public Task GetArchitectureOsVersion() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetArchitectureOsVersion"); - - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetArchitectureOsVersion"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } - internal static async Task GetKernelVersion() + public Task GetKernelVersion() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetKernelVersion"); - - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetKernelVersion"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } @@ -72,19 +106,17 @@ internal static async Task GetKernelVersion() #region CPU/GPU temperature - internal static async Task GetGpuTemp() + public Task GetGpuTemp() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetGpuTemp"); - - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetGpuTemp"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } - internal static async Task GetCpuTemp() + public Task GetCpuTemp() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetCpuTemp"); - - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetCpuTemp"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } @@ -92,27 +124,24 @@ internal static async Task GetCpuTemp() #region Network info - internal static async Task GetNetworkInfo() + public Task GetNetworkInfo() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetNetworkInfo"); - - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetNetworkInfo"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } - internal static async Task GetIpInfo() + public Task GetIpInfo() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetIpInfo"); - - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetIpInfo"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } - internal static async Task GetWiFiSsids() + public Task GetWiFiSsids() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetWiFiSsids"); - - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetWiFiSsids"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } @@ -120,11 +149,10 @@ internal static async Task GetWiFiSsids() #region AdamServer info - internal static async Task GetAdamServerVersion() + public Task GetAdamServerVersion() { - HttpResponseMessage? responseMessage = await ApiClient.Get($"{cApiPath}/GetAdamServerVersion"); - - var result = await responseMessage.ToExtendedCommandResult(); + var responseMessage = mApiClient.Get($"{cApiPath}/GetAdamServerVersion"); + var result = responseMessage.ToExtendedCommandResultAsync(); return result; } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs index 6324c00..3a3f326 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ComputerVisionControlViewModel.cs @@ -1,7 +1,6 @@ using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Services.Interfaces; -using AdamController.WebApi.Client.v1; using Newtonsoft.Json; using Prism.Commands; using Prism.Regions; @@ -15,6 +14,7 @@ public class ComputerVisionControlViewModel : RegionViewModelBase #region Services private readonly ICommunicationProviderService mCommunicationProvider; + private readonly IWebApiService mWebApiService; #endregion @@ -27,9 +27,10 @@ public class ComputerVisionControlViewModel : RegionViewModelBase #region ~ - public ComputerVisionControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider) : base(regionManager, dialogService) + public ComputerVisionControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IWebApiService webApiService) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; + mWebApiService = webApiService; } #endregion @@ -119,8 +120,8 @@ public override void OnNavigatedFrom(NavigationContext navigationContext) { try { - await BaseApi.StopPythonExecute(); - await BaseApi.MoveToZeroPosition(); + await mWebApiService.StopPythonExecute(); + await mWebApiService.MoveToZeroPosition(); } catch { diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index e05ce8d..6c8330d 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -46,6 +46,7 @@ public class ScratchControlViewModel : RegionViewModelBase private readonly IWebViewProvider mWebViewProvider; private readonly IDialogManagerService mDialogManager; private readonly IFileManagmentService mFileManagment; + private readonly IWebApiService mWebApiService; #endregion @@ -67,7 +68,7 @@ public class ScratchControlViewModel : RegionViewModelBase #region ~ - public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IWebViewProvider webViewProvider, IDialogManagerService dialogManager, IFileManagmentService fileManagment) : base(regionManager, dialogService) + public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IWebViewProvider webViewProvider, IDialogManagerService dialogManager, IFileManagmentService fileManagment, IWebApiService webApiService) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; mPythonRemoteRunner = pythonRemoteRunner; @@ -75,6 +76,7 @@ public ScratchControlViewModel(IRegionManager regionManager, IDialogService dial mWebViewProvider = webViewProvider; mDialogManager = dialogManager; mFileManagment = fileManagment; + mWebApiService = webApiService; ReloadWebViewDelegateCommand = new DelegateCommand(ReloadWebView, ReloadWebViewCanExecute); ShowSaveFileDialogDelegateCommand = new DelegateCommand(ShowSaveFileDialog, ShowSaveFileDialogCanExecute); @@ -85,6 +87,7 @@ public ScratchControlViewModel(IRegionManager regionManager, IDialogService dial StopPythonCodeExecuteDelegateCommand = new DelegateCommand(StopPythonCodeExecute, StopPythonCodeExecuteCanExecute); SendCodeToExternalSourceEditorDelegateCommand = new(SendCodeToExternalSourceEditor, SendCodeToExternalSourceEditorCanExecute); ToZeroPositionDelegateCommand = new DelegateCommand(ToZeroPosition, ToZeroPositionCanExecute); + ; } #endregion @@ -383,16 +386,16 @@ private bool CleanExecuteEditorCanExecute() private async void RunPythonCode() { ResultTextEditorError = string.Empty; - WebApi.Client.v1.ResponseModel.ExtendedCommandExecuteResult executeResult = new(); + ExtendedCommandExecuteResult executeResult = new(); try { - var command = new WebApi.Client.v1.RequestModel.PythonCommand + var command = new WebApi.Client.v1.RequestModel.PythonCommandModel { Command = SourceTextEditor }; - executeResult = await BaseApi.PythonExecuteAsync(command); + executeResult = await mWebApiService.PythonExecuteAsync(command); } catch (Exception ex) { @@ -435,7 +438,7 @@ private async void StopPythonCodeExecute() try { - await BaseApi.StopPythonExecute(); + await mWebApiService.StopPythonExecute(); } catch (Exception ex) { @@ -474,7 +477,7 @@ private async void ToZeroPosition() { try { - await BaseApi.StopPythonExecute(); + await mWebApiService.StopPythonExecute(); } catch (Exception ex) { @@ -580,9 +583,9 @@ private async void OnRaiseTcpServiceCientConnected(object sender) { IsTcpClientConnected = mCommunicationProvider.IsTcpClientConnected; - var pythonVersionResult = await BaseApi.GetPythonVersion(); - var pythonBinPathResult = await BaseApi.GetPythonBinDir(); - var pythonWorkDirResult = await BaseApi.GetPythonWorkDir(); + var pythonVersionResult = await mWebApiService.GetPythonVersion(); + var pythonBinPathResult = await mWebApiService.GetPythonBinDir(); + var pythonWorkDirResult = await mWebApiService.GetPythonWorkDir(); string pythonVersion = pythonVersionResult?.StandardOutput?.Replace("\n", ""); string pythonBinPath = pythonBinPathResult?.StandardOutput?.Replace("\n", ""); diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs index b9aed0d..b19c840 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs @@ -21,6 +21,7 @@ public class ScriptEditorControlViewModel : RegionViewModelBase private readonly IPythonRemoteRunnerService mPythonRemoteRunner; private readonly IStatusBarNotificationDeliveryService mStatusBarNotificationDelivery; private readonly IFileManagmentService mFileManagment; + private readonly IWebApiService mWebApiService; #endregion @@ -28,14 +29,16 @@ public class ScriptEditorControlViewModel : RegionViewModelBase private bool mIsWarningStackOwerflowAlreadyShow; private readonly IMessageDialogManager IDialogManager; - public ScriptEditorControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IFileManagmentService fileManagment) : base(regionManager, dialogService) + public ScriptEditorControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IFileManagmentService fileManagment, IWebApiService webApiService) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; mPythonRemoteRunner = pythonRemoteRunner; mStatusBarNotificationDelivery = statusBarNotificationDelivery; mFileManagment = fileManagment; + mWebApiService = webApiService; IDialogManager = new MessageDialogManagerMahapps(Application.Current); + } #region Navigation @@ -255,11 +258,11 @@ public string ResultTextEditorError { if(mCommunicationProvider.IsTcpClientConnected) { - var command = new WebApi.Client.v1.RequestModel.PythonCommand + var command = new WebApi.Client.v1.RequestModel.PythonCommandModel { Command = SourceTextEditor }; - executeResult = await BaseApi.PythonExecuteAsync(command); + executeResult = await mWebApiService.PythonExecuteAsync(command); } } @@ -319,7 +322,7 @@ public string ResultTextEditorError { try { - await BaseApi.StopPythonExecute(); + await mWebApiService.StopPythonExecute(); } catch(Exception ex) { diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs index b7e4e96..48d7165 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs @@ -38,6 +38,7 @@ protected override void OnChanging(bool isOpening) UpdatePublicFields(); Subscribe(); CreateDelegateCommand(); + return; } @@ -46,9 +47,10 @@ protected override void OnChanging(bool isOpening) ClearPublicFields(); Unsubscribe(); ResetDelegateCommand(); + return; } - base.OnChanging(isOpening); + //base.OnChanging(isOpening); } #endregion diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index aa1824b..3ade326 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -57,6 +57,8 @@ protected override void OnChanging(bool isOpening) { Subscribe(); UpdateStatusConnection(mCommunicationProvider.IsTcpClientConnected); + + return; } @@ -67,12 +69,12 @@ protected override void OnChanging(bool isOpening) ConnectButtonDelegateCommand = null; ReconnectNotificationButtonDelegateCommand = null; ResetNotificationsDelegateCommand = null; - } - - base.OnChanging(isOpening); + return; + } } + #endregion #region Public field From e1fa04ea0b55bce632c117855bc719227a02e5d2 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 21 Apr 2024 13:10:16 +1000 Subject: [PATCH 111/181] Remove unused code --- .../Behaviors/ActivateBehavior.cs | 57 --- .../PutCursorAtEndTextBoxBehavior.cs | 21 - .../Behaviors/SelectionChangedBehavior.cs | 136 ------ .../Collections/CollectionUtils.cs | 53 --- .../Collections/TrulyObservableCoolection.cs | 58 --- .../ItemChangedEventArgs.cs | 14 - ...sage.cs => SyslogParseMessageExtension.cs} | 6 +- ...SyslogMessage.cs => SyslogMessageModel.cs} | 4 +- AdamController/Commands/EventToCommand.cs | 415 ------------------ .../ViewModels/MainWindowViewModel.cs | 2 +- 10 files changed, 6 insertions(+), 760 deletions(-) delete mode 100644 AdamController.Core/Behaviors/ActivateBehavior.cs delete mode 100644 AdamController.Core/Behaviors/PutCursorAtEndTextBoxBehavior.cs delete mode 100644 AdamController.Core/Behaviors/SelectionChangedBehavior.cs delete mode 100644 AdamController.Core/Collections/CollectionUtils.cs delete mode 100644 AdamController.Core/Collections/TrulyObservableCoolection.cs delete mode 100644 AdamController.Core/ExtendedComponentModel/ItemChangedEventArgs.cs rename AdamController.Core/Extensions/{SyslogParseMessage.cs => SyslogParseMessageExtension.cs} (93%) rename AdamController.Core/Model/{SyslogMessage.cs => SyslogMessageModel.cs} (84%) delete mode 100644 AdamController/Commands/EventToCommand.cs diff --git a/AdamController.Core/Behaviors/ActivateBehavior.cs b/AdamController.Core/Behaviors/ActivateBehavior.cs deleted file mode 100644 index a96cef7..0000000 --- a/AdamController.Core/Behaviors/ActivateBehavior.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace AdamController.Core.Behaviors -{ - //[Obsolete] - /*public class ActivateBehavior : Behavior - { - private bool isActivated; - - public static readonly DependencyProperty ActivatedProperty = DependencyProperty.Register("Activated", - typeof(bool), - typeof(ActivateBehavior), - new PropertyMetadata(OnActivatedChanged) - ); - - public bool Activated - { - get => (bool)GetValue(ActivatedProperty); - set => SetValue(ActivatedProperty, value); - } - - static void OnActivatedChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) - { - ActivateBehavior behavior = (ActivateBehavior)dependencyObject; - if (!behavior.Activated || behavior.isActivated) return; - - // The Activated property is set to true but the Activated event (tracked by the - // isActivated field) hasn't been fired. Go ahead and activate the window. - if (behavior.AssociatedObject.WindowState == WindowState.Minimized) - behavior.AssociatedObject.WindowState = WindowState.Normal; - _ = behavior.AssociatedObject.Activate(); - } - - protected override void OnAttached() - { - AssociatedObject.Activated += OnActivated; - AssociatedObject.Deactivated += OnDeactivated; - } - - protected override void OnDetaching() - { - AssociatedObject.Activated -= OnActivated; - AssociatedObject.Deactivated -= OnDeactivated; - } - - private void OnActivated(object sender, EventArgs eventArgs) - { - isActivated = true; - Activated = true; - } - - private void OnDeactivated(object sender, EventArgs eventArgs) - { - isActivated = false; - Activated = false; - } - - }*/ -} diff --git a/AdamController.Core/Behaviors/PutCursorAtEndTextBoxBehavior.cs b/AdamController.Core/Behaviors/PutCursorAtEndTextBoxBehavior.cs deleted file mode 100644 index 116446a..0000000 --- a/AdamController.Core/Behaviors/PutCursorAtEndTextBoxBehavior.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace AdamController.Core.Behaviors -{ - /*[Obsolete] - public class PutCursorAtEndTextBoxBehavior : Behavior - { - protected override void OnAttached() - { - AssociatedObject.TextChanged += AssociatedObject_TextChanged; - } - - protected override void OnDetaching() - { - AssociatedObject.TextChanged -= AssociatedObject_TextChanged; - } - - void AssociatedObject_TextChanged(object sender, TextChangedEventArgs e) - { - AssociatedObject.ScrollToEnd(); - } - }*/ -} diff --git a/AdamController.Core/Behaviors/SelectionChangedBehavior.cs b/AdamController.Core/Behaviors/SelectionChangedBehavior.cs deleted file mode 100644 index 360b3a0..0000000 --- a/AdamController.Core/Behaviors/SelectionChangedBehavior.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Controls.Primitives; -using System.Windows.Input; - -//TODO refactor this -namespace AdamController.Core.Behaviors -{ - /// - /// Attached behaviour to implement a selection changed command on a Selector (combobox). - /// The Selector (combobox) generates a SelectionChanged event which in turn generates a - /// Command (in this behavior), which in turn is, when bound, invoked on the viewmodel. - /// - /*[Obsolete("Remove if dont`t need")] - public static class SelectionChangedCommand - { - // Field of attached ICommand property - private static readonly DependencyProperty ChangedCommandProperty = DependencyProperty.RegisterAttached("ChangedCommand", - typeof(ICommand), - typeof(SelectionChangedCommand), - new PropertyMetadata(null, OnSelectionChangedCommandChange)); - - /// - /// Setter method of the attached DropCommand property - /// - /// - /// - public static void SetChangedCommand(DependencyObject source, ICommand value) - { - source.SetValue(ChangedCommandProperty, value); - } - - /// - /// Getter method of the attached DropCommand property - /// - /// - /// - public static ICommand GetChangedCommand(DependencyObject source) - { - return (ICommand)source.GetValue(ChangedCommandProperty); - } - - /// - /// This method is hooked in the definition of the . - /// It is called whenever the attached property changes - in our case the event of binding - /// and unbinding the property to a sink is what we are looking for. - /// - /// - /// - private static void OnSelectionChangedCommandChange(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - Selector uiElement = d as Selector; // Remove the handler if it exist to avoid memory leaks - - if (uiElement != null) - { - uiElement.SelectionChanged -= Selection_Changed; - uiElement.KeyUp -= uiElement_KeyUp; - - if (e.NewValue is ICommand command) - { - // the property is attached so we attach the Drop event handler - uiElement.SelectionChanged += Selection_Changed; - uiElement.KeyUp += uiElement_KeyUp; - } - } - } - - private static void uiElement_KeyUp(object sender, KeyEventArgs e) - { - if (e == null) - return; - - // Forward key event only if user has hit the return, BackSlash, or Slash key - if (e.Key != Key.Return) - return; - - - // Sanity check just in case this was somehow send by something else - if (sender is not ComboBox uiElement) - return; - - ICommand changedCommand = GetChangedCommand(uiElement); - - // There may not be a command bound to this after all - if (changedCommand == null) - return; - - // Check whether this attached behaviour is bound to a RoutedCommand - if (changedCommand is RoutedCommand) - { - // Execute the routed command - (changedCommand as RoutedCommand).Execute(uiElement.Text, uiElement); - } - else - { - // Execute the Command as bound delegate - changedCommand.Execute(uiElement.Text); - } - } - - /// - /// This method is called when the selection changed event occurs. The sender should be the control - /// on which this behaviour is attached - so we convert the sender into a - /// and receive the Command through the getter listed above. - /// - /// This implementation supports binding of delegate commands and routed commands. - /// - /// - /// - private static void Selection_Changed(object sender, SelectionChangedEventArgs e) - { - // Sanity check just in case this was somehow send by something else - if (sender is not Selector uiElement) - return; - - ICommand changedCommand = GetChangedCommand(uiElement); - - // There may not be a command bound to this after all - if (changedCommand == null) - return; - - // Check whether this attached behaviour is bound to a RoutedCommand - if (changedCommand is RoutedCommand) - { - // Execute the routed command - (changedCommand as RoutedCommand).Execute(e.AddedItems, uiElement); - } - else - { - // Execute the Command as bound delegate - changedCommand.Execute(e.AddedItems); - } - } - }*/ -} diff --git a/AdamController.Core/Collections/CollectionUtils.cs b/AdamController.Core/Collections/CollectionUtils.cs deleted file mode 100644 index e76c5ed..0000000 --- a/AdamController.Core/Collections/CollectionUtils.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace AdamController.Core.Collections -{ - public static class CollectionUtils - { - /// - /// Складывает два массива - /// - public static byte[] Combine(this byte[] firstByteArray, byte[] secondByteArray) - { - byte[] ret = new byte[firstByteArray.Length + secondByteArray.Length]; - Buffer.BlockCopy(firstByteArray, 0, ret, 0, firstByteArray.Length); - Buffer.BlockCopy(secondByteArray, 0, ret, firstByteArray.Length, secondByteArray.Length); - return ret; - } - - /// - /// Добаваляет @string в начало массива bytes - /// - public static byte[] AddStringAsByteArray(this byte[] bytes, string @string) - { - if (string.IsNullOrEmpty(@string)) - return bytes; - - byte[] servoStringBytes = Encoding.ASCII.GetBytes(@string); - byte[] combineBytes = servoStringBytes.Combine(bytes); - - return combineBytes; - } - - /// - /// Convert to byte[] - /// - public static byte[] ConvertToByteArray(this List arrays) - { - byte[] ret = new byte[arrays.Sum(x => x.Length)]; - int offset = 0; - - foreach (byte[] data in arrays) - { - Buffer.BlockCopy(data, 0, ret, offset, data.Length); - offset += data.Length; - } - - return ret; - } - - } -} diff --git a/AdamController.Core/Collections/TrulyObservableCoolection.cs b/AdamController.Core/Collections/TrulyObservableCoolection.cs deleted file mode 100644 index 93f5412..0000000 --- a/AdamController.Core/Collections/TrulyObservableCoolection.cs +++ /dev/null @@ -1,58 +0,0 @@ - -using AdamController.Core.ExtendedComponentModel; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; - - -namespace AdamController.Core.Collections -{ - public sealed class TrulyObservableCollection : ObservableCollection, ICollectionItemPropertyChanged where T : INotifyPropertyChanged - { - public event EventHandler> ItemChanged; - - public TrulyObservableCollection() - { - CollectionChanged += FullObservableCollectionCollectionChanged; - } - - public TrulyObservableCollection(IEnumerable pItems) : this() - { - foreach (T item in pItems) - { - Add(item); - } - } - - private void FullObservableCollectionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) - { - if (e.NewItems != null) - { - foreach (object item in e.NewItems) - { - (item as INotifyPropertyChanged).PropertyChanged += ItemPropertyChanged; - } - } - if (e.OldItems != null) - { - foreach (object item in e.OldItems) - { - (item as INotifyPropertyChanged).PropertyChanged -= ItemPropertyChanged; - } - } - } - - private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e) - { - ItemChangedEventArgs args = new((T)sender, e.PropertyName); - ItemChanged?.Invoke(this, args); - } - } - - public interface ICollectionItemPropertyChanged - { - event EventHandler> ItemChanged; - } -} diff --git a/AdamController.Core/ExtendedComponentModel/ItemChangedEventArgs.cs b/AdamController.Core/ExtendedComponentModel/ItemChangedEventArgs.cs deleted file mode 100644 index e20ee18..0000000 --- a/AdamController.Core/ExtendedComponentModel/ItemChangedEventArgs.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace AdamController.Core.ExtendedComponentModel -{ - public class ItemChangedEventArgs - { - public T ChangedItem { get; } - public string PropertyName { get; } - - public ItemChangedEventArgs(T item, string propertyName) - { - ChangedItem = item; - PropertyName = propertyName; - } - } -} diff --git a/AdamController.Core/Extensions/SyslogParseMessage.cs b/AdamController.Core/Extensions/SyslogParseMessageExtension.cs similarity index 93% rename from AdamController.Core/Extensions/SyslogParseMessage.cs rename to AdamController.Core/Extensions/SyslogParseMessageExtension.cs index 13d6f53..969be47 100644 --- a/AdamController.Core/Extensions/SyslogParseMessage.cs +++ b/AdamController.Core/Extensions/SyslogParseMessageExtension.cs @@ -4,7 +4,7 @@ namespace AdamController.Core.Extensions { - public static class SyslogParseMessage + public static class SyslogParseMessageExtension { private static readonly string mSyslogMsgHeaderPattern = @"\<(?\d{1,3})\>(?[1-9]{0,2}) (?(\S|\w)+) (?-|(\S|\w){1,255}) (?-|(\S|\w){1,48}) (?-|(\S|\w){1,128}) (?-|(\S|\w){1,32})"; private static readonly string mSyslogMsgStructuredDataPattern = @"(?-|\[[^\[\=\x22\]\x20]{1,32}( ([^\[\=\x22\]\x20]{1,32}=\x22.+\x22))?\])"; @@ -18,7 +18,7 @@ public static class SyslogParseMessage /// /// /// - public static SyslogMessage Parse(this string rawMessage) + public static SyslogMessageModel Parse(this string rawMessage) { if (string.IsNullOrWhiteSpace(rawMessage)) { throw new ArgumentNullException(nameof(rawMessage)); } @@ -26,7 +26,7 @@ public static SyslogMessage Parse(this string rawMessage) var match = mExpression.Match(rawMessage); if (match.Success) { - return new SyslogMessage + return new SyslogMessageModel { Prival = Convert.ToInt32(match.Groups["PRIVAL"].Value), Version = Convert.ToInt32(match.Groups["VERSION"].Value), diff --git a/AdamController.Core/Model/SyslogMessage.cs b/AdamController.Core/Model/SyslogMessageModel.cs similarity index 84% rename from AdamController.Core/Model/SyslogMessage.cs rename to AdamController.Core/Model/SyslogMessageModel.cs index ab40964..4272ee1 100644 --- a/AdamController.Core/Model/SyslogMessage.cs +++ b/AdamController.Core/Model/SyslogMessageModel.cs @@ -4,7 +4,7 @@ namespace AdamController.Core.Model { - public class SyslogMessage + public class SyslogMessageModel { public int Prival { get; set; } public int Version { get; set; } @@ -19,7 +19,7 @@ public class SyslogMessage public override string ToString() { - var message = new StringBuilder($@"<{Prival:###}>{Version:##} {TimeStamp.ToString("yyyy-MM-ddTHH:mm:ss.fffK")} {HostName} {AppName} {ProcId} {MessageId} {StructuredData}"); + var message = new StringBuilder($@"<{Prival:###}>{Version:##} {TimeStamp:yyyy-MM-ddTHH:mm:ss.fffK} {HostName} {AppName} {ProcId} {MessageId} {StructuredData}"); if (!string.IsNullOrWhiteSpace(Message)) { diff --git a/AdamController/Commands/EventToCommand.cs b/AdamController/Commands/EventToCommand.cs deleted file mode 100644 index e183474..0000000 --- a/AdamController/Commands/EventToCommand.cs +++ /dev/null @@ -1,415 +0,0 @@ -using Microsoft.Xaml.Behaviors; -using System; -using System.Windows; -using System.Windows.Input; - -namespace AdamController.Commands -{ - - /// - /// This can be - /// used to bind any event on any FrameworkElement to an . - /// Typically, this element is used in XAML to connect the attached element - /// to a command located in a ViewModel. This trigger can only be attached - /// to a FrameworkElement or a class deriving from FrameworkElement. - /// To access the EventArgs of the fired event, use a RelayCommand<EventArgs> - /// and leave the CommandParameter and CommandParameterValue empty! - /// - ////[ClassInfo(typeof(EventToCommand), - //// VersionString = "5.2.8", - //// DateString = "201504252130", - //// Description = "A Trigger used to bind any event to an ICommand.", - //// UrlContacts = "http://www.galasoft.ch/contact_en.html", - //// Email = "laurent@galasoft.ch")] - /*public class EventToCommand : TriggerAction - { - /// - /// Identifies the dependency property - /// - public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register( - "CommandParameter", - typeof(object), - typeof(EventToCommand), - new PropertyMetadata( - null, - (s, e) => - { - var sender = s as EventToCommand; - - if (sender?.AssociatedObject == null) - { - return; - } - - sender.EnableDisableElement(); - })); - - /// - /// Identifies the dependency property - /// - public static readonly DependencyProperty CommandProperty = DependencyProperty.Register( - "Command", - typeof(ICommand), - typeof(EventToCommand), - new PropertyMetadata( - null, - (s, e) => OnCommandChanged(s as EventToCommand, e))); - - /// - /// Identifies the dependency property - /// - public static readonly DependencyProperty MustToggleIsEnabledProperty = DependencyProperty.Register( - "MustToggleIsEnabled", - typeof(bool), - typeof(EventToCommand), - new PropertyMetadata( - false, - (s, e) => - { - var sender = s as EventToCommand; - - if (sender?.AssociatedObject == null) - { - return; - } - - sender.EnableDisableElement(); - })); - - private object _commandParameterValue; - - private bool? _mustToggleValue; - - /// - /// Gets or sets the ICommand that this trigger is bound to. This - /// is a DependencyProperty. - /// - public ICommand Command - { - get - { - return (ICommand)GetValue(CommandProperty); - } - - set - { - SetValue(CommandProperty, value); - } - } - - /// - /// Gets or sets an object that will be passed to the - /// attached to this trigger. This is a DependencyProperty. - /// - public object CommandParameter - { - get - { - return GetValue(CommandParameterProperty); - } - - set - { - SetValue(CommandParameterProperty, value); - } - } - - /// - /// Gets or sets an object that will be passed to the - /// attached to this trigger. This property is here for compatibility - /// with the Silverlight version. This is NOT a DependencyProperty. - /// For databinding, use the property. - /// - public object CommandParameterValue - { - get - { - return _commandParameterValue ?? CommandParameter; - } - - set - { - _commandParameterValue = value; - EnableDisableElement(); - } - } - - /// - /// Gets or sets a value indicating whether the attached element must be - /// disabled when the property CanExecuteChanged - /// event fires. If this property is true, and the command CanExecute - /// method returns false, the element will be disabled. If this property - /// is false, the element will not be disabled when the command's - /// CanExecute method changes. This is a DependencyProperty. - /// - public bool MustToggleIsEnabled - { - get - { - return (bool)GetValue(MustToggleIsEnabledProperty); - } - - set - { - SetValue(MustToggleIsEnabledProperty, value); - } - } - - /// - /// Gets or sets a value indicating whether the attached element must be - /// disabled when the property CanExecuteChanged - /// event fires. If this property is true, and the command CanExecute - /// method returns false, the element will be disabled. This property is here for - /// compatibility with the Silverlight version. This is NOT a DependencyProperty. - /// For databinding, use the property. - /// - public bool MustToggleIsEnabledValue - { - get - { - return _mustToggleValue ?? MustToggleIsEnabled; - } - - set - { - _mustToggleValue = value; - EnableDisableElement(); - } - } - - /// - /// Called when this trigger is attached to a FrameworkElement. - /// - protected override void OnAttached() - { - base.OnAttached(); - EnableDisableElement(); - } - - /// - /// This method is here for compatibility - /// with the Silverlight version. - /// - /// The FrameworkElement to which this trigger - /// is attached. - private FrameworkElement GetAssociatedObject() - { - return AssociatedObject as FrameworkElement; - } - - /// - /// This method is here for compatibility - /// with the Silverlight 3 version. - /// - /// The command that must be executed when - /// this trigger is invoked. - private ICommand GetCommand() - { - return Command; - } - - /// - /// Specifies whether the EventArgs of the event that triggered this - /// action should be passed to the bound RelayCommand. If this is true, - /// the command should accept arguments of the corresponding - /// type (for example RelayCommand<MouseButtonEventArgs>). - /// - public bool PassEventArgsToCommand - { - get; - set; - } - - /// - /// Gets or sets a converter used to convert the EventArgs when using - /// . If PassEventArgsToCommand is false, - /// this property is never used. - /// - public IEventArgsConverter EventArgsConverter - { - get; - set; - } - - /// - /// The dependency property name. - /// - public const string EventArgsConverterParameterPropertyName = "EventArgsConverterParameter"; - - /// - /// Gets or sets a parameters for the converter used to convert the EventArgs when using - /// . If PassEventArgsToCommand is false, - /// this property is never used. This is a dependency property. - /// - public object EventArgsConverterParameter - { - get - { - return GetValue(EventArgsConverterParameterProperty); - } - set - { - SetValue(EventArgsConverterParameterProperty, value); - } - } - - /// - /// Identifies the dependency property. - /// - public static readonly DependencyProperty EventArgsConverterParameterProperty = DependencyProperty.Register( - EventArgsConverterParameterPropertyName, - typeof(object), - typeof(EventToCommand), - new PropertyMetadata(null)); - - /// - /// The dependency property name. - /// - public const string AlwaysInvokeCommandPropertyName = "AlwaysInvokeCommand"; - - /// - /// Gets or sets a value indicating if the command should be invoked even - /// if the attached control is disabled. This is a dependency property. - /// - public bool AlwaysInvokeCommand - { - get - { - return (bool)GetValue(AlwaysInvokeCommandProperty); - } - set - { - SetValue(AlwaysInvokeCommandProperty, value); - } - } - - /// - /// Identifies the dependency property. - /// - public static readonly DependencyProperty AlwaysInvokeCommandProperty = DependencyProperty.Register( - AlwaysInvokeCommandPropertyName, - typeof(bool), - typeof(EventToCommand), - new PropertyMetadata(false)); - - - /// - /// Provides a simple way to invoke this trigger programatically - /// without any EventArgs. - /// - public void Invoke() - { - Invoke(null); - } - - /// - /// Executes the trigger. - /// To access the EventArgs of the fired event, use a RelayCommand<EventArgs> - /// and leave the CommandParameter and CommandParameterValue empty! - /// - /// The EventArgs of the fired event. - protected override void Invoke(object parameter) - { - if (AssociatedElementIsDisabled() - && !AlwaysInvokeCommand) - { - return; - } - - var command = GetCommand(); - var commandParameter = CommandParameterValue; - - if (commandParameter == null - && PassEventArgsToCommand) - { - commandParameter = EventArgsConverter == null - ? parameter - : EventArgsConverter.Convert(parameter, EventArgsConverterParameter); - } - - if (command != null - && command.CanExecute(commandParameter)) - { - command.Execute(commandParameter); - } - } - - private static void OnCommandChanged( - EventToCommand element, - DependencyPropertyChangedEventArgs e) - { - if (element == null) - { - return; - } - - if (e.OldValue != null) - { - ((ICommand)e.OldValue).CanExecuteChanged -= element.OnCommandCanExecuteChanged; - } - - var command = (ICommand)e.NewValue; - - if (command != null) - { - command.CanExecuteChanged += element.OnCommandCanExecuteChanged; - } - - element.EnableDisableElement(); - } - - private bool AssociatedElementIsDisabled() - { - var element = GetAssociatedObject(); - - return AssociatedObject == null - || (element != null - && !element.IsEnabled); - } - - private void EnableDisableElement() - { - var element = GetAssociatedObject(); - - if (element == null) - { - return; - } - - var command = GetCommand(); - - if (MustToggleIsEnabledValue - && command != null) - { - element.IsEnabled = command.CanExecute(CommandParameterValue); - } - } - - private void OnCommandCanExecuteChanged(object sender, EventArgs e) - { - EnableDisableElement(); - } - } - - /// - /// The definition of the converter used to convert an EventArgs - /// in the class, if the - /// property is true. - /// Set an instance of this class to the - /// property of the EventToCommand instance. - /// - ////[ClassInfo(typeof(EventToCommand))] - public interface IEventArgsConverter - { - /// - /// The method used to convert the EventArgs instance. - /// - /// An instance of EventArgs passed by the - /// event that the EventToCommand instance is handling. - /// An optional parameter used for the conversion. Use - /// the property - /// to set this value. This may be null. - /// The converted value. - object Convert(object value, object parameter); - }*/ -} diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index 797d027..2c250b6 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -161,7 +161,7 @@ private void ParseSyslogMessage(string message) { try { - SyslogMessage syslogMessage = message.Parse(); + SyslogMessageModel syslogMessage = message.Parse(); mStatusBarNotification.CompileLogMessage = $"{syslogMessage.TimeStamp:T} {syslogMessage.Message}"; } catch From c68facbc8593567c67255007a68364a1efe66e37 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 21 Apr 2024 13:42:18 +1000 Subject: [PATCH 112/181] Prepare works #41 --- AdamController.Services/AvalonEditService.cs | 19 +++++++++++++++++++ .../Interfaces/IAvalonEditService.cs | 14 ++++++++++++++ AdamController/App.xaml.cs | 4 ++-- 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 AdamController.Services/AvalonEditService.cs create mode 100644 AdamController.Services/Interfaces/IAvalonEditService.cs diff --git a/AdamController.Services/AvalonEditService.cs b/AdamController.Services/AvalonEditService.cs new file mode 100644 index 0000000..8d68a39 --- /dev/null +++ b/AdamController.Services/AvalonEditService.cs @@ -0,0 +1,19 @@ +using AdamController.Services.Interfaces; +using ICSharpCode.AvalonEdit.Highlighting; +using System; + +namespace AdamController.Services +{ + public class AvalonEditService : IAvalonEditService + { + public void Dispose() + { + //throw new NotImplementedException(); + } + + public void RegisterHighlighting(string name, string[] extensions, IHighlightingDefinition highlighting) + { + throw new NotImplementedException(); + } + } +} diff --git a/AdamController.Services/Interfaces/IAvalonEditService.cs b/AdamController.Services/Interfaces/IAvalonEditService.cs new file mode 100644 index 0000000..79c3bfa --- /dev/null +++ b/AdamController.Services/Interfaces/IAvalonEditService.cs @@ -0,0 +1,14 @@ +using ICSharpCode.AvalonEdit.Highlighting; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AdamController.Services.Interfaces +{ + public interface IAvalonEditService : IDisposable + { + public void RegisterHighlighting(string name, string[] extensions, IHighlightingDefinition highlighting); + } +} diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index d26ffb9..a6972da 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -48,6 +48,7 @@ using System.Threading.Tasks; using System.Net; using AdamController.Services.TcpClientDependency; +using ICSharpCode.AvalonEdit.Highlighting.Xshd; #endregion @@ -243,8 +244,7 @@ private static void LoadHighlighting() { using var stream = new MemoryStream(Resource.AdamPython); using var reader = new XmlTextReader(stream); - HighlightingManager.Instance.RegisterHighlighting("AdamPython", Array.Empty(), - ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader, HighlightingManager.Instance)); + HighlightingManager.Instance.RegisterHighlighting("AdamPython", Array.Empty(), HighlightingLoader.Load(reader, HighlightingManager.Instance)); } catch { From 09fde80903d7cf1c88299f78480ff5ff1af59168 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 21 Apr 2024 18:11:22 +1000 Subject: [PATCH 113/181] Prepare works #41 --- AdamController.Services/AvalonEditService.cs | 25 ++++++++++--- .../FileManagmentService.cs | 9 +++++ .../Interfaces/IAvalonEditService.cs | 6 +--- .../Interfaces/IFileManagmentService.cs | 3 ++ AdamController/App.xaml.cs | 36 +++++++++++-------- .../ViewModels/MainWindowViewModel.cs | 8 ++--- 6 files changed, 59 insertions(+), 28 deletions(-) diff --git a/AdamController.Services/AvalonEditService.cs b/AdamController.Services/AvalonEditService.cs index 8d68a39..3e57174 100644 --- a/AdamController.Services/AvalonEditService.cs +++ b/AdamController.Services/AvalonEditService.cs @@ -1,19 +1,34 @@ -using AdamController.Services.Interfaces; +using AdamBlocklyLibrary.Properties; +using AdamController.Services.Interfaces; using ICSharpCode.AvalonEdit.Highlighting; +using ICSharpCode.AvalonEdit.Highlighting.Xshd; using System; namespace AdamController.Services { public class AvalonEditService : IAvalonEditService { - public void Dispose() + private readonly IFileManagmentService mFileManagmentService; + private readonly HighlightingManager mHighlightingManager; + + public AvalonEditService(IFileManagmentService fileManagmentService) + { + mFileManagmentService = fileManagmentService; + mHighlightingManager = new HighlightingManager(); + } + + + public void RegisterHighlighting(string highlightingName, byte[] xmlByteArray) { - //throw new NotImplementedException(); + var xml = mFileManagmentService.ReadTextAsXml(xmlByteArray); + var definition = HighlightingLoader.Load(xml, HighlightingManager.Instance); + + mHighlightingManager.RegisterHighlighting(highlightingName, Array.Empty(), definition); } - public void RegisterHighlighting(string name, string[] extensions, IHighlightingDefinition highlighting) + public void Dispose() { - throw new NotImplementedException(); } + } } diff --git a/AdamController.Services/FileManagmentService.cs b/AdamController.Services/FileManagmentService.cs index 869d16a..fd83e42 100644 --- a/AdamController.Services/FileManagmentService.cs +++ b/AdamController.Services/FileManagmentService.cs @@ -3,6 +3,7 @@ using System.IO; using System.Text; using System.Threading.Tasks; +using System.Xml; namespace AdamController.Services { @@ -22,6 +23,14 @@ public FileManagmentService() { } #region Public methods + public XmlTextReader ReadTextAsXml(byte[] xmlByteArray) + { + MemoryStream stream = new(xmlByteArray); + XmlTextReader reader = new(stream); + + return reader; + } + public async Task ReadTextAsByteArray(string path) { using var fs = OpenFileStreamAsync(path); diff --git a/AdamController.Services/Interfaces/IAvalonEditService.cs b/AdamController.Services/Interfaces/IAvalonEditService.cs index 79c3bfa..06f5949 100644 --- a/AdamController.Services/Interfaces/IAvalonEditService.cs +++ b/AdamController.Services/Interfaces/IAvalonEditService.cs @@ -1,14 +1,10 @@ using ICSharpCode.AvalonEdit.Highlighting; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace AdamController.Services.Interfaces { public interface IAvalonEditService : IDisposable { - public void RegisterHighlighting(string name, string[] extensions, IHighlightingDefinition highlighting); + public void RegisterHighlighting(string highlightingName, byte[] xmlByteArray); } } diff --git a/AdamController.Services/Interfaces/IFileManagmentService.cs b/AdamController.Services/Interfaces/IFileManagmentService.cs index 4b65a79..97fce96 100644 --- a/AdamController.Services/Interfaces/IFileManagmentService.cs +++ b/AdamController.Services/Interfaces/IFileManagmentService.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using System.Xml; namespace AdamController.Services.Interfaces { @@ -13,6 +14,8 @@ public interface IFileManagmentService : IDisposable public Task ReadTextAsByteArray(string path); + public XmlTextReader ReadTextAsXml(byte[] xml); + #endregion } } diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index a6972da..23b2a7d 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -80,7 +80,7 @@ protected override void OnStartup(StartupEventArgs e) //TODO check theme before ChangeTheme _ = ThemeManager.Current.ChangeTheme(this, $"{Settings.Default.BaseTheme}.{Settings.Default.ThemeColorScheme}", false); - LoadHighlighting(); + //LoadHighlighting(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) @@ -95,6 +95,13 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return new FolderManagmentService(); }); + containerRegistry.RegisterSingleton(containerRegistry => + { + IFileManagmentService fileManagment = containerRegistry.Resolve(); + AvalonEditService avalonService = new(fileManagment); + return avalonService; + }); + containerRegistry.RegisterSingleton(containerRegistry => { return new WebViewProvider(); @@ -238,19 +245,19 @@ protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) moduleCatalog.AddModule(); } - private static void LoadHighlighting() - { - try - { - using var stream = new MemoryStream(Resource.AdamPython); - using var reader = new XmlTextReader(stream); - HighlightingManager.Instance.RegisterHighlighting("AdamPython", Array.Empty(), HighlightingLoader.Load(reader, HighlightingManager.Instance)); - } - catch - { - - } - } + //private static void LoadHighlighting() + //{ + // try + // { + // using MemoryStream stream = new MemoryStream(Resource.AdamPython); + // using XmlTextReader reader = new XmlTextReader(stream); + // HighlightingManager.Instance.RegisterHighlighting("AdamPython", Array.Empty(), HighlightingLoader.Load(reader, HighlightingManager.Instance)); + // } + // catch + // { + // + // } + //} protected override void OnExit(ExitEventArgs e) { @@ -281,6 +288,7 @@ private void DisposeServices() { Container.Resolve().Dispose(); Container.Resolve().Dispose(); + Container.Resolve().Dispose(); Container.Resolve().Dispose(); Container.Resolve().Dispose(); diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index 2c250b6..0e69137 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -27,14 +27,14 @@ public class MainWindowViewModel : ViewModelBase private readonly ICommunicationProviderService mCommunicationProviderService; private readonly IFolderManagmentService mFolderManagment; private readonly IWebApiService mWebApiService; - + private readonly IAvalonEditService mAvalonEditService; #endregion #region ~ public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService, IStatusBarNotificationDeliveryService statusBarNotification, - ICommunicationProviderService communicationProviderService, IFolderManagmentService folderManagment, IWebApiService webApiService) + ICommunicationProviderService communicationProviderService, IFolderManagmentService folderManagment, IWebApiService webApiService, IAvalonEditService avalonEditService) { RegionManager = regionManager; mWebApiService = webApiService; @@ -42,8 +42,7 @@ public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareSe mStatusBarNotification = statusBarNotification; mCommunicationProviderService = communicationProviderService; mFolderManagment = folderManagment; - - + mAvalonEditService = avalonEditService; ShowRegionCommand = new DelegateCommand(ShowRegion); Subscribe(); @@ -208,6 +207,7 @@ private void MainWindowLoaded(object sender, RoutedEventArgs e) SaveFolderPathToSettings(); ShowRegionCommand.Execute(SubRegionNames.SubRegionScratch); mStatusBarNotification.CompileLogMessage = "Загрузка приложения завершена"; + mAvalonEditService.RegisterHighlighting("AdamPython", Resource.AdamPython); if (Settings.Default.AutoStartTcpConnect) mCommunicationProviderService.ConnectAllAsync(); From c62f91e1972f227763f60dc7d793494811d72b4e Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 21 Apr 2024 18:37:51 +1000 Subject: [PATCH 114/181] Prepare works #41 --- AdamController.Core/HighlightingName.cs | 9 +++++++++ AdamController.Services/AvalonEditService.cs | 8 +++++--- AdamController/ViewModels/MainWindowViewModel.cs | 2 +- .../Views/ScratchControlView.xaml | 3 ++- .../Views/ScriptEditorControlView.xaml | 3 ++- 5 files changed, 19 insertions(+), 6 deletions(-) create mode 100644 AdamController.Core/HighlightingName.cs diff --git a/AdamController.Core/HighlightingName.cs b/AdamController.Core/HighlightingName.cs new file mode 100644 index 0000000..a866f53 --- /dev/null +++ b/AdamController.Core/HighlightingName.cs @@ -0,0 +1,9 @@ +using AdamController.Core.Properties; + +namespace AdamController.Core +{ + public class HighlightingName + { + public const string AdamPython = nameof(Resource.AdamPython); + } +} diff --git a/AdamController.Services/AvalonEditService.cs b/AdamController.Services/AvalonEditService.cs index 3e57174..0e7e496 100644 --- a/AdamController.Services/AvalonEditService.cs +++ b/AdamController.Services/AvalonEditService.cs @@ -9,12 +9,12 @@ namespace AdamController.Services public class AvalonEditService : IAvalonEditService { private readonly IFileManagmentService mFileManagmentService; - private readonly HighlightingManager mHighlightingManager; + //private readonly HighlightingManager mHighlightingManager; public AvalonEditService(IFileManagmentService fileManagmentService) { mFileManagmentService = fileManagmentService; - mHighlightingManager = new HighlightingManager(); + //mHighlightingManager = new HighlightingManager(); } @@ -22,8 +22,10 @@ public void RegisterHighlighting(string highlightingName, byte[] xmlByteArray) { var xml = mFileManagmentService.ReadTextAsXml(xmlByteArray); var definition = HighlightingLoader.Load(xml, HighlightingManager.Instance); + + HighlightingManager.Instance.RegisterHighlighting(highlightingName, Array.Empty(), definition); - mHighlightingManager.RegisterHighlighting(highlightingName, Array.Empty(), definition); + //mHighlightingManager.RegisterHighlighting(highlightingName, Array.Empty(), definition); } public void Dispose() diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index 0e69137..2b33df4 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -207,7 +207,7 @@ private void MainWindowLoaded(object sender, RoutedEventArgs e) SaveFolderPathToSettings(); ShowRegionCommand.Execute(SubRegionNames.SubRegionScratch); mStatusBarNotification.CompileLogMessage = "Загрузка приложения завершена"; - mAvalonEditService.RegisterHighlighting("AdamPython", Resource.AdamPython); + mAvalonEditService.RegisterHighlighting(HighlightingName.AdamPython, Resource.AdamPython); if (Settings.Default.AutoStartTcpConnect) mCommunicationProviderService.ConnectAllAsync(); diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml index 0963982..92f1d9e 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml @@ -9,6 +9,7 @@ xmlns:i="http://schemas.microsoft.com/xaml/behaviors" xmlns:behaviors="clr-namespace:AdamController.Core.Behaviors;assembly=AdamController.Core" xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit" + xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True"> @@ -267,7 +268,7 @@ HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" ScrollViewer.PanningMode="HorizontalOnly" - SyntaxHighlighting="AdamPython" + SyntaxHighlighting="{DynamicResource core:HighlightingName.AdamPython}" IsEnabled="{Binding IsPythonCodeExecute, Converter={StaticResource InverseBooleanConverter}}" Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}" LineNumbersForeground="{DynamicResource MahApps.Brushes.ThemeForeground}" diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScriptEditorControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ScriptEditorControlView.xaml index 3dd0b8a..f3882ff 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScriptEditorControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScriptEditorControlView.xaml @@ -261,6 +261,7 @@ + Date: Mon, 22 Apr 2024 09:07:06 +1000 Subject: [PATCH 115/181] Close #41 #30 --- AdamController.Services/AvalonEditService.cs | 40 +++++++++++++++---- .../Interfaces/IAvalonEditService.cs | 6 +++ AdamController/App.xaml.cs | 16 +------- .../ViewModels/MainWindowViewModel.cs | 13 +++++- .../ViewModels/ScratchControlViewModel.cs | 15 ++++++- .../ScriptEditorControlViewModel.cs | 34 +++++++++++----- .../Views/ScratchControlView.xaml | 2 +- .../Views/ScriptEditorControlView.xaml | 9 ++--- 8 files changed, 92 insertions(+), 43 deletions(-) diff --git a/AdamController.Services/AvalonEditService.cs b/AdamController.Services/AvalonEditService.cs index 0e7e496..91f12fa 100644 --- a/AdamController.Services/AvalonEditService.cs +++ b/AdamController.Services/AvalonEditService.cs @@ -3,34 +3,60 @@ using ICSharpCode.AvalonEdit.Highlighting; using ICSharpCode.AvalonEdit.Highlighting.Xshd; using System; +using System.Collections.ObjectModel; namespace AdamController.Services { public class AvalonEditService : IAvalonEditService { + #region Var + private readonly IFileManagmentService mFileManagmentService; - //private readonly HighlightingManager mHighlightingManager; + private readonly HighlightingManager mHighlightingManager; + + #endregion + + #region ~ public AvalonEditService(IFileManagmentService fileManagmentService) - { + { mFileManagmentService = fileManagmentService; - //mHighlightingManager = new HighlightingManager(); + mHighlightingManager = HighlightingManager.Instance; } - + #endregion + + #region Public field + + public ReadOnlyCollection HighlightingDefinitions + { + get => mHighlightingManager.HighlightingDefinitions; + } + + #endregion + + #region Public methods + public void RegisterHighlighting(string highlightingName, byte[] xmlByteArray) { var xml = mFileManagmentService.ReadTextAsXml(xmlByteArray); - var definition = HighlightingLoader.Load(xml, HighlightingManager.Instance); + var definition = HighlightingLoader.Load(xml, mHighlightingManager); + mHighlightingManager.RegisterHighlighting(highlightingName, Array.Empty(), definition); - HighlightingManager.Instance.RegisterHighlighting(highlightingName, Array.Empty(), definition); + } - //mHighlightingManager.RegisterHighlighting(highlightingName, Array.Empty(), definition); + public IHighlightingDefinition GetDefinition(string name) + { + IHighlightingDefinition definition = mHighlightingManager.GetDefinition(name); + return definition; } public void Dispose() { + } + #endregion + } } diff --git a/AdamController.Services/Interfaces/IAvalonEditService.cs b/AdamController.Services/Interfaces/IAvalonEditService.cs index 06f5949..f71cc99 100644 --- a/AdamController.Services/Interfaces/IAvalonEditService.cs +++ b/AdamController.Services/Interfaces/IAvalonEditService.cs @@ -1,10 +1,16 @@ using ICSharpCode.AvalonEdit.Highlighting; using System; +using System.Collections.ObjectModel; namespace AdamController.Services.Interfaces { public interface IAvalonEditService : IDisposable { + /// + /// Register highlighting for AvalonEdit. You need to call before loading the regions + /// public void RegisterHighlighting(string highlightingName, byte[] xmlByteArray); + public ReadOnlyCollection HighlightingDefinitions { get; } + public IHighlightingDefinition GetDefinition(string name); } } diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 23b2a7d..72c41f5 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -49,6 +49,7 @@ using System.Net; using AdamController.Services.TcpClientDependency; using ICSharpCode.AvalonEdit.Highlighting.Xshd; +using AdamController.Core; #endregion @@ -80,7 +81,6 @@ protected override void OnStartup(StartupEventArgs e) //TODO check theme before ChangeTheme _ = ThemeManager.Current.ChangeTheme(this, $"{Settings.Default.BaseTheme}.{Settings.Default.ThemeColorScheme}", false); - //LoadHighlighting(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) @@ -245,20 +245,6 @@ protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) moduleCatalog.AddModule(); } - //private static void LoadHighlighting() - //{ - // try - // { - // using MemoryStream stream = new MemoryStream(Resource.AdamPython); - // using XmlTextReader reader = new XmlTextReader(stream); - // HighlightingManager.Instance.RegisterHighlighting("AdamPython", Array.Empty(), HighlightingLoader.Load(reader, HighlightingManager.Instance)); - // } - // catch - // { - // - // } - //} - protected override void OnExit(ExitEventArgs e) { OnAppCrashOrExit(); diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index 2b33df4..d6cbcff 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -155,7 +155,6 @@ private void SaveFolderPathToSettings() } } - private void ParseSyslogMessage(string message) { try @@ -169,6 +168,14 @@ private void ParseSyslogMessage(string message) } } + /// + /// Register highlighting for AvalonEdit. You need to call before loading the regions + /// + private void LoadCustomAvalonEditHighlighting() + { + mAvalonEditService.RegisterHighlighting(HighlightingName.AdamPython, Resource.AdamPython); + } + #endregion #region Subscriptions @@ -205,9 +212,11 @@ private void Unsubscribe() private void MainWindowLoaded(object sender, RoutedEventArgs e) { SaveFolderPathToSettings(); + LoadCustomAvalonEditHighlighting(); + ShowRegionCommand.Execute(SubRegionNames.SubRegionScratch); mStatusBarNotification.CompileLogMessage = "Загрузка приложения завершена"; - mAvalonEditService.RegisterHighlighting(HighlightingName.AdamPython, Resource.AdamPython); + if (Settings.Default.AutoStartTcpConnect) mCommunicationProviderService.ConnectAllAsync(); diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index 6c8330d..7e5b2f5 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -11,11 +11,13 @@ using AdamController.Services.WebViewProviderDependency; using AdamController.WebApi.Client.v1; using AdamController.WebApi.Client.v1.ResponseModel; +using ICSharpCode.AvalonEdit.Highlighting; using Newtonsoft.Json; using Prism.Commands; using Prism.Regions; using Prism.Services.Dialogs; using System; +using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; @@ -68,7 +70,9 @@ public class ScratchControlViewModel : RegionViewModelBase #region ~ - public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IWebViewProvider webViewProvider, IDialogManagerService dialogManager, IFileManagmentService fileManagment, IWebApiService webApiService) : base(regionManager, dialogService) + public ScratchControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, + IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IWebViewProvider webViewProvider, IDialogManagerService dialogManager, + IFileManagmentService fileManagment, IWebApiService webApiService, IAvalonEditService avalonEditService) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; mPythonRemoteRunner = pythonRemoteRunner; @@ -87,7 +91,8 @@ public ScratchControlViewModel(IRegionManager regionManager, IDialogService dial StopPythonCodeExecuteDelegateCommand = new DelegateCommand(StopPythonCodeExecute, StopPythonCodeExecuteCanExecute); SendCodeToExternalSourceEditorDelegateCommand = new(SendCodeToExternalSourceEditor, SendCodeToExternalSourceEditorCanExecute); ToZeroPositionDelegateCommand = new DelegateCommand(ToZeroPosition, ToZeroPositionCanExecute); - ; + + HighlightingDefinition = avalonEditService.GetDefinition(HighlightingName.AdamPython); } #endregion @@ -233,6 +238,12 @@ public string PythonWorkDir set => SetProperty(ref pythonWorkDir, value); } + private IHighlightingDefinition highlightingDefinition; + public IHighlightingDefinition HighlightingDefinition + { + get => highlightingDefinition; + set => SetProperty(ref highlightingDefinition, value); + } #endregion diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs index b19c840..d1ee7f3 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs @@ -3,6 +3,7 @@ using AdamController.Services.Interfaces; using AdamController.WebApi.Client.v1; using AdamController.WebApi.Client.v1.ResponseModel; +using ICSharpCode.AvalonEdit.Highlighting; using MessageDialogManagerLib; using Prism.Commands; using Prism.Regions; @@ -22,23 +23,24 @@ public class ScriptEditorControlViewModel : RegionViewModelBase private readonly IStatusBarNotificationDeliveryService mStatusBarNotificationDelivery; private readonly IFileManagmentService mFileManagment; private readonly IWebApiService mWebApiService; + private readonly IDialogManagerService mDialogManager; #endregion - private bool mIsWarningStackOwerflowAlreadyShow; - private readonly IMessageDialogManager IDialogManager; - public ScriptEditorControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IFileManagmentService fileManagment, IWebApiService webApiService) : base(regionManager, dialogService) + public ScriptEditorControlViewModel(IRegionManager regionManager, IDialogService dialogService, ICommunicationProviderService communicationProvider, + IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, + IFileManagmentService fileManagment, IWebApiService webApiService, IAvalonEditService avalonEditService, IDialogManagerService dialogManager) : base(regionManager, dialogService) { mCommunicationProvider = communicationProvider; mPythonRemoteRunner = pythonRemoteRunner; mStatusBarNotificationDelivery = statusBarNotificationDelivery; mFileManagment = fileManagment; mWebApiService = webApiService; + mDialogManager = dialogManager; - IDialogManager = new MessageDialogManagerMahapps(Application.Current); - + HighlightingDefinition = avalonEditService.GetDefinition(HighlightingName.AdamPython); } #region Navigation @@ -114,6 +116,17 @@ private void OnRaisePythonScriptExecuteFinish(object sender, ExtendedCommandExec #endregion + #region Public fields + + private IHighlightingDefinition highlightingDefinition; + public IHighlightingDefinition HighlightingDefinition + { + get => highlightingDefinition; + set => SetProperty(ref highlightingDefinition, value); + } + + #endregion + #region Python execute event private void PythonExecuteEvent() @@ -181,7 +194,6 @@ public string SelectedText #endregion - #region Result text editor private string resultTextEditor; @@ -346,10 +358,10 @@ await Task.Run(() => private DelegateCommand showOpenFileDialogCommand; public DelegateCommand ShowOpenFileDialogCommand => showOpenFileDialogCommand ??= new DelegateCommand(async () => { - if (IDialogManager.ShowFileBrowser("Выберите файл с исходным кодом программы", + if (mDialogManager.ShowFileBrowser("Выберите файл с исходным кодом программы", Core.Properties.Settings.Default.SavedUserScriptsFolderPath, "PythonScript file (.py)|*.py|Все файлы|*.*")) { - string path = IDialogManager.FilePath; + string path = mDialogManager.FilePath; if (path == "") return; string pythonProgram = await mFileManagment.ReadTextAsStringAsync(path); @@ -373,13 +385,13 @@ await Task.Run(() => { string pythonProgram = SourceTextEditor; - if (IDialogManager.ShowSaveFileDialog("Сохранить файл программы", Core.Properties.Settings.Default.SavedUserScriptsFolderPath, + if (mDialogManager.ShowSaveFileDialog("Сохранить файл программы", Core.Properties.Settings.Default.SavedUserScriptsFolderPath, "new_program", ".py", "PythonScript file (.py)|*.py|Все файлы|*.*")) { - string path = IDialogManager.FilePathToSave; + string path = mDialogManager.FilePathToSave; await mFileManagment.WriteAsync(path, pythonProgram); - mStatusBarNotificationDelivery.AppLogMessage = $"Файл {IDialogManager.FilePathToSave} сохранен"; + mStatusBarNotificationDelivery.AppLogMessage = $"Файл {mDialogManager.FilePathToSave} сохранен"; } else { diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml index 92f1d9e..70985e4 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml @@ -268,7 +268,7 @@ HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" ScrollViewer.PanningMode="HorizontalOnly" - SyntaxHighlighting="{DynamicResource core:HighlightingName.AdamPython}" + SyntaxHighlighting="{Binding HighlightingDefinition, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding IsPythonCodeExecute, Converter={StaticResource InverseBooleanConverter}}" Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}" LineNumbersForeground="{DynamicResource MahApps.Brushes.ThemeForeground}" diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScriptEditorControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ScriptEditorControlView.xaml index f3882ff..b467106 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScriptEditorControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScriptEditorControlView.xaml @@ -272,14 +272,13 @@ FontStretch="Medium" FontWeight="SemiBold" ShowLineNumbers="True" - SyntaxHighlighting="{DynamicResource core:HighlightingName.AdamPython}" + HorizontalScrollBarVisibility="Auto" + VerticalScrollBarVisibility="Auto" + SyntaxHighlighting="{Binding HighlightingDefinition, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}" LineNumbersForeground="{DynamicResource MahApps.Brushes.ThemeForeground}" Background="{DynamicResource MahApps.Brushes.ThemeBackground}" - BorderBrush="{DynamicResource MahApps.Brushes.ThemeForeground}" - - HorizontalScrollBarVisibility="Auto" - VerticalScrollBarVisibility="Auto"> + BorderBrush="{DynamicResource MahApps.Brushes.ThemeForeground}"> From d22c3b35691704d986357b0f8b6aef61844e8c83 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 22 Apr 2024 09:20:44 +1000 Subject: [PATCH 116/181] Clean using --- .../ViewModels/ScriptEditorControlViewModel.cs | 2 -- .../Views/ComputerVisionControlView.xaml.cs | 15 ++++++++++++--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs index d1ee7f3..3a1529a 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScriptEditorControlViewModel.cs @@ -1,10 +1,8 @@ using AdamController.Core; using AdamController.Core.Mvvm; using AdamController.Services.Interfaces; -using AdamController.WebApi.Client.v1; using AdamController.WebApi.Client.v1.ResponseModel; using ICSharpCode.AvalonEdit.Highlighting; -using MessageDialogManagerLib; using Prism.Commands; using Prism.Regions; using Prism.Services.Dialogs; diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs b/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs index f02ee79..5dfb756 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs +++ b/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml.cs @@ -1,4 +1,5 @@ -using LibVLCSharp.Shared; +using AdamController.Services.Interfaces; +using LibVLCSharp.Shared; using LibVLCSharp.WPF; using System; using System.Windows; @@ -9,13 +10,21 @@ namespace AdamController.Modules.ContentRegion.Views public partial class ComputerVisionControlView : UserControl, IDisposable { + #region Service + + private readonly IWebSocketClientService mWebSocketClient; + + #endregion + private LibVLC mLibVLC; private MediaPlayer mMediaPlayer; - public ComputerVisionControlView() + public ComputerVisionControlView(IWebSocketClientService webSocketClient) { InitializeComponent(); + mWebSocketClient = webSocketClient; + VideoView.Loaded += VideoView_Loaded; Unloaded += UserControlUnloaded; } @@ -77,7 +86,7 @@ public void Dispose() private void Button_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { - //There is no solution for this situation + mWebSocketClient.SendTextAsync(DownRightDirection); //ComunicateHelper.WebSocketSendTextMessage(DownRightDirection); } } From 2665f9b6e3dd02876f5193232137bd946d00f3da Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 22 Apr 2024 13:02:56 +1000 Subject: [PATCH 117/181] Close #24 p1 --- .../DataSource/LanguagesCollection.cs | 21 -- AdamController.Core/Model/EditorModel.cs | 27 --- .../Enum/BlocklyLanguage.cs | 3 +- .../ViewModels/ScratchControlViewModel.cs | 5 - .../VisualSettingsControlViewModel.cs | 214 +++++++----------- .../Views/VisualSettingsControlView.xaml | 1 + .../AdvancedBlocklySettingsViewModel.cs | 19 +- 7 files changed, 103 insertions(+), 187 deletions(-) delete mode 100644 AdamController.Core/DataSource/LanguagesCollection.cs delete mode 100644 AdamController.Core/Model/EditorModel.cs diff --git a/AdamController.Core/DataSource/LanguagesCollection.cs b/AdamController.Core/DataSource/LanguagesCollection.cs deleted file mode 100644 index ca34719..0000000 --- a/AdamController.Core/DataSource/LanguagesCollection.cs +++ /dev/null @@ -1,21 +0,0 @@ -using AdamBlocklyLibrary.Enum; -using AdamController.Core.Model; -using System.Collections.ObjectModel; - -namespace AdamController.Core.DataSource -{ - public class LanguagesCollection - { - public static ObservableCollection AppLanguageCollection { get; private set; } = new ObservableCollection - { - new AppLanguageModel { AppLanguage = "ru", LanguageName = "Русский" } - }; - - public static ObservableCollection BlocklyLanguageCollection { get; private set; } = new ObservableCollection - { - new BlocklyLanguageModel { BlocklyLanguage = BlocklyLanguage.ru, LanguageName = "Русский" }, - new BlocklyLanguageModel { BlocklyLanguage = BlocklyLanguage.zh, LanguageName = "Китайский" }, - new BlocklyLanguageModel { BlocklyLanguage = BlocklyLanguage.en, LanguageName = "Английский" } - }; - } -} diff --git a/AdamController.Core/Model/EditorModel.cs b/AdamController.Core/Model/EditorModel.cs deleted file mode 100644 index 529ae80..0000000 --- a/AdamController.Core/Model/EditorModel.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace AdamController.Core.Model -{ - //TODO Rename this (as Autocomplete or etc) - /*public class EditorModel : ICompletionData - { - public EditorModel(string text) - { - Text = text; - } - - public System.Windows.Media.ImageSource Image => null; - - public string Text { get; private set; } - - // Use this property if you want to show a fancy UIElement in the drop down list. - public object Content => Text; - - public object Description => "Description for " + Text; - - public double Priority { get { return 0; } } - - public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) - { - textArea.Document.Replace(completionSegment, Text); - } - }*/ -} diff --git a/Legacy/AdamBlocklyLibrary/Enum/BlocklyLanguage.cs b/Legacy/AdamBlocklyLibrary/Enum/BlocklyLanguage.cs index 609a534..368bfa0 100644 --- a/Legacy/AdamBlocklyLibrary/Enum/BlocklyLanguage.cs +++ b/Legacy/AdamBlocklyLibrary/Enum/BlocklyLanguage.cs @@ -3,7 +3,6 @@ public enum BlocklyLanguage { ru, - en, - zh + en } } diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index 7e5b2f5..59c057c 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -862,11 +862,6 @@ private async Task LoadBlocklyBlockLocalLangSrc(BlocklyLanguage language) _ = await ExecuteScriptFunctionAsync("loadSrc", Scripts.BlockLanguageRu); break; } - case BlocklyLanguage.zh: - { - _ = await ExecuteScriptFunctionAsync("loadSrc", Scripts.BlockLanguageZnHans); - break; - } case BlocklyLanguage.en: { _ = await ExecuteScriptFunctionAsync("loadSrc", Scripts.BlockLanguageEn); diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index a05af51..229c24a 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -23,29 +23,13 @@ public class VisualSettingsControlViewModel : RegionViewModelBase #region DelegateCommands public DelegateCommand OpenAdvancedBlocklySettingsDelegateCommand { get; } - public DelegateCommand ChangeBaseThemeDelegateCommand { get; } - //public DelegateCommand ChangeThemeColorSchemeDelegateCommand { get; } - - #endregion - - #region Action - - //public static Action ChangeBaseTheme { get; set; } - - public static Action ChangeNotificationOpacity { get; set; } - //public static Action ChangeThemeColorScheme { get; set; } - //public static Action OpenAdvancedBlocklySettings { get; set; } - public static Action SetToolboxLanguage { get; set; } - public static Action SetBlocklyThemeAndGridColor { get; set; } - #endregion - #region Service + #region Services - private readonly IFlyoutManager mFlyoutManager; - private readonly IWebViewProvider mWebViewProvider; + private readonly IFlyoutManager mFlyoutManager; #endregion @@ -54,11 +38,9 @@ public class VisualSettingsControlViewModel : RegionViewModelBase public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager, IWebViewProvider webViewProvider) : base(regionManager, dialogService) { mFlyoutManager = flyoutManager; - mWebViewProvider = webViewProvider; OpenAdvancedBlocklySettingsDelegateCommand = new DelegateCommand(OpenAdvancedBlocklySettings, OpenAdvancedBlocklySettingsCanExecute); ChangeBaseThemeDelegateCommand = new DelegateCommand(ChangeBaseTheme, ChangeBaseThemeCanExecute); - //ChangeThemeColorScheme = new DelegateCommand() } #endregion @@ -97,6 +79,27 @@ public override void ConfirmNavigationRequest(NavigationContext navigationContex public override void OnNavigatedTo(NavigationContext navigationContext) { base.OnNavigatedTo(navigationContext); + + LanguageApp = new ObservableCollection + { + new AppLanguageModel { AppLanguage = "ru", LanguageName = "Русский" } + }; + + + BlocklyLanguageCollection = new ObservableCollection + { + new BlocklyLanguageModel { BlocklyLanguage = BlocklyLanguage.ru, LanguageName = "Русский" }, + new BlocklyLanguageModel { BlocklyLanguage = BlocklyLanguage.en, LanguageName = "Английский" } + }; + + BlocklyThemes = ThemesCollection.BlocklyThemes; + ColorScheme = ThemeManager.Current.ColorSchemes; + + //SelectedLanguageApp = LanguageApp.FirstOrDefault(x => x.AppLanguage == Settings.Default.AppLanguage); + //SelectedBlocklyWorkspaceLanguage = BlocklyLanguageCollection.FirstOrDefault(x => x.BlocklyLanguage == Settings.Default.BlocklyWorkspaceLanguage); + + SelectedColorScheme = ThemeManager.Current.DetectTheme(Application.Current).ColorScheme; + NotificationOpacity = Settings.Default.NotificationOpacity; } public override void OnNavigatedFrom(NavigationContext navigationContext) @@ -107,40 +110,37 @@ public override void OnNavigatedFrom(NavigationContext navigationContext) #endregion - #region Private methods + #region Public fields - private void ChangeTheme(string newTheme) + private ObservableCollection languageApp; + public ObservableCollection LanguageApp { - _ = ThemeManager.Current.ChangeThemeBaseColor(Application.Current, newTheme); - - if (!Settings.Default.ChangeBlocklyThemeToggleSwitchState) - { - if (newTheme == "Dark") - { - Settings.Default.BlocklyTheme = BlocklyTheme.Dark; - Settings.Default.BlocklyGridColour = Colors.White.ToString(); - } - - if (newTheme == "Light") - { - Settings.Default.BlocklyTheme = BlocklyTheme.Classic; - Settings.Default.BlocklyGridColour = Colors.Black.ToString(); - } - } + get => languageApp; + private set => SetProperty(ref languageApp, value); } - private void ChangeThemeColorScheme(string colorScheme) + private ObservableCollection blocklyLanguageCollection; + public ObservableCollection BlocklyLanguageCollection { - ThemeManager.Current.ChangeThemeColorScheme(Application.Current, colorScheme); + get => blocklyLanguageCollection; + private set => SetProperty(ref blocklyLanguageCollection, value); } - #endregion - - public static ObservableCollection BlocklyThemes { get; private set; } = ThemesCollection.BlocklyThemes; + private ObservableCollection blocklyThemes; + public ObservableCollection BlocklyThemes + { + get => blocklyThemes; + private set => SetProperty(ref blocklyThemes, value); + } - public static ObservableCollection LanguageApp { get; private set; } = LanguagesCollection.AppLanguageCollection; + private ReadOnlyObservableCollection colorScheme; + public ReadOnlyObservableCollection ColorScheme + { + get => colorScheme; + private set => SetProperty(ref colorScheme, value); + } - private AppLanguageModel selectedLanguageApp = LanguageApp.FirstOrDefault(x => x.AppLanguage == Settings.Default.AppLanguage); + /*private AppLanguageModel selectedLanguageApp; public AppLanguageModel SelectedLanguageApp { get => selectedLanguageApp; @@ -151,43 +151,27 @@ public AppLanguageModel SelectedLanguageApp return; } - selectedLanguageApp = value; - - SetProperty(ref selectedLanguageApp, value); + bool isNewValue = SetProperty(ref selectedLanguageApp, value); - Settings.Default.AppLanguage = selectedLanguageApp.AppLanguage; + if (isNewValue) + Settings.Default.AppLanguage = SelectedLanguageApp.AppLanguage; } - } + }*/ - public static ObservableCollection BlocklyLanguageCollection { get; private set; } = LanguagesCollection.BlocklyLanguageCollection; - - private BlocklyLanguageModel selectedBlocklyWorkspaceLanguage = BlocklyLanguageCollection.FirstOrDefault(x => x.BlocklyLanguage == Settings.Default.BlocklyWorkspaceLanguage); + /*private BlocklyLanguageModel selectedBlocklyWorkspaceLanguage; public BlocklyLanguageModel SelectedBlocklyWorkspaceLanguage { get => selectedBlocklyWorkspaceLanguage; set { - if (value == selectedBlocklyWorkspaceLanguage) - { - return; - } - - selectedBlocklyWorkspaceLanguage = value; - - SetProperty(ref selectedBlocklyWorkspaceLanguage, value); - - if (!Settings.Default.ChangeToolboxLanguageToggleSwitchState) - { - SetToolboxLanguage(selectedBlocklyWorkspaceLanguage); - } + bool isNewValue = SetProperty(ref selectedBlocklyWorkspaceLanguage, value); - Settings.Default.BlocklyWorkspaceLanguage = selectedBlocklyWorkspaceLanguage.BlocklyLanguage; + if (isNewValue) + Settings.Default.BlocklyWorkspaceLanguage = SelectedBlocklyWorkspaceLanguage.BlocklyLanguage; } - } - - public ReadOnlyObservableCollection ColorScheme { get; set; } = ThemeManager.Current.ColorSchemes; + }*/ - private string selectedColorScheme = ThemeManager.Current.DetectTheme(Application.Current).ColorScheme; + private string selectedColorScheme; public string SelectedColorScheme { get => selectedColorScheme; @@ -195,78 +179,48 @@ public string SelectedColorScheme { bool isNewValue = SetProperty(ref selectedColorScheme, value); - if(isNewValue) - ChangeThemeColorScheme(selectedColorScheme); + if (isNewValue) + ChangeThemeColorScheme(SelectedColorScheme); } } - //TODO unused this variable - private short blocklyGridLenth = Settings.Default.BlocklyGridLenth; - public short BlocklyGridLenth - { - get => blocklyGridLenth; - set - { - if (value == blocklyGridLenth) - { - return; - } - - blocklyGridLenth = value; - - SetProperty(ref blocklyGridLenth, value); - Settings.Default.BlocklyGridLenth = BlocklyGridLenth; - } - } - - private double notificationOpacity = Settings.Default.NotificationOpacity; + private double notificationOpacity; public double NotificationOpacity { get => notificationOpacity; - set - { - if (value == notificationOpacity) return; - - notificationOpacity = value; - - ChangeNotificationOpacity(notificationOpacity); - - SetProperty(ref notificationOpacity, value); - } + set => SetProperty(ref notificationOpacity, value); } + #endregion - - - //private DelegateCommand openAdvancedBlocklySettingsCommand; - //public DelegateCommand OpenAdvancedBlocklySettingsCommand => openAdvancedBlocklySettingsCommand ??= new DelegateCommand(() => - //{ - // FlyoutManager.OpenFlyout(FlyoutNames.FlyotAdvancedBlocklySettings); - //}); - - //private DelegateCommand changeBaseColorTheme; - - //public DelegateCommand ChangeBaseColorTheme => changeBaseColorTheme ??= new DelegateCommand(obj => - //{ - //string mainTheme = obj; + #region Private methods - //if (mainTheme == null) return; + private void ChangeTheme(string newTheme) + { + _ = ThemeManager.Current.ChangeThemeBaseColor(Application.Current, newTheme); - //ChangeBaseTheme(mainTheme); + if (!Settings.Default.ChangeBlocklyThemeToggleSwitchState) + { + if (newTheme == "Dark") + { + Settings.Default.BlocklyTheme = BlocklyTheme.Dark; + Settings.Default.BlocklyGridColour = Colors.White.ToString(); + } + + if (newTheme == "Light") + { + Settings.Default.BlocklyTheme = BlocklyTheme.Classic; + Settings.Default.BlocklyGridColour = Colors.Black.ToString(); + } + } + } - //if (!Settings.Default.ChangeBlocklyThemeToggleSwitchState) - //{ - // if (mainTheme == "Dark") - // { - // SetBlocklyThemeAndGridColor(BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == BlocklyTheme.Dark)); - // } - // else if (mainTheme == "Light") - // { - // SetBlocklyThemeAndGridColor(BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == BlocklyTheme.Classic)); - // } - //} - //}); + private void ChangeThemeColorScheme(string colorScheme) + { + ThemeManager.Current.ChangeThemeColorScheme(Application.Current, colorScheme); + } + #endregion } } diff --git a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml index 4448d33..1b1c951 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml @@ -113,6 +113,7 @@ IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding SelectedColorScheme}" ItemsSource="{Binding ColorScheme}"> + diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs index 48d7165..f8041da 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/AdvancedBlocklySettingsViewModel.cs @@ -60,10 +60,12 @@ protected override void OnChanging(bool isOpening) private void UpdatePublicFields() { SelectedBlocklyGridColour = MahApps.Metro.Controls.ColorHelper.ColorFromString(Settings.Default.BlocklyGridColour); - BlocklyLanguageCollection = new ObservableCollection(LanguagesCollection.BlocklyLanguageCollection); - SelectedBlocklyToolboxLanguage = BlocklyLanguageCollection.FirstOrDefault(x => x.BlocklyLanguage == Settings.Default.BlocklyToolboxLanguage); + //BlocklyLanguageCollection = new ObservableCollection(LanguagesCollection.BlocklyLanguageCollection); + //SelectedBlocklyToolboxLanguage = BlocklyLanguageCollection.FirstOrDefault(x => x.BlocklyLanguage == Settings.Default.BlocklyToolboxLanguage); BlocklyThemes = new ObservableCollection(ThemesCollection.BlocklyThemes); SelectedBlocklyTheme = BlocklyThemes.FirstOrDefault(x => x.BlocklyTheme == Settings.Default.BlocklyTheme); + + //BlocklyGridLenth = Settings.Default.BlocklyGridLenth; } private void ClearPublicFields() @@ -116,6 +118,19 @@ public BlocklyThemeModel SelectedBlocklyTheme set => SetProperty(ref selectedBlocklyTheme, value); } + /*private short blocklyGridLenth; + public short BlocklyGridLenth + { + get => blocklyGridLenth; + set + { + bool isNewValue = SetProperty(ref blocklyGridLenth, value); + + if (isNewValue) + Settings.Default.BlocklyGridLenth = BlocklyGridLenth; + } + }*/ + #endregion #region Private metods From 87f7673346ded4afd518a827bf0396399b0d8bbe Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 22 Apr 2024 13:52:51 +1000 Subject: [PATCH 118/181] Close issue #43 --- Legacy/AdamBlocklyLibrary/Toolbox/CategoryToolbox.cs | 4 ++-- .../Views/VisualSettingsControlView.xaml | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Legacy/AdamBlocklyLibrary/Toolbox/CategoryToolbox.cs b/Legacy/AdamBlocklyLibrary/Toolbox/CategoryToolbox.cs index ef3a72c..c88d163 100644 --- a/Legacy/AdamBlocklyLibrary/Toolbox/CategoryToolbox.cs +++ b/Legacy/AdamBlocklyLibrary/Toolbox/CategoryToolbox.cs @@ -61,7 +61,7 @@ public class CategoryToolbox /// For set ExpandedCategory use Expanded /// [JsonPropertyName("expanded")] - internal string ExpandedCategory => Expanded ? Expanded.ToString().ToLower() : null; + public string ExpandedCategory => Expanded ? Expanded.ToString().ToLower() : null; /// /// A category can be hidden when the toolbox is first injected, or it can be hidden later on through JavaScript. @@ -73,7 +73,7 @@ public class CategoryToolbox /// For set HiddenCategory use Hidden /// [JsonPropertyName("hidden")] - internal string HiddenCategory => Hidden.ToString().ToLower(); + public string HiddenCategory => Hidden.ToString().ToLower(); } } diff --git a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml index 1b1c951..510622a 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml @@ -194,7 +194,6 @@ - From ca557693f7dca1f6d40aca37d17f3cb5e546bc0b Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 22 Apr 2024 14:55:41 +1000 Subject: [PATCH 119/181] Prepare work #44 --- .../Interfaces/IThemeManagerService.cs | 8 ++++ .../ThemeManagerService.cs | 38 +++++++++++++++++++ AdamController/App.xaml.cs | 38 +++++++++++-------- 3 files changed, 69 insertions(+), 15 deletions(-) create mode 100644 AdamController.Services/Interfaces/IThemeManagerService.cs create mode 100644 AdamController.Services/ThemeManagerService.cs diff --git a/AdamController.Services/Interfaces/IThemeManagerService.cs b/AdamController.Services/Interfaces/IThemeManagerService.cs new file mode 100644 index 0000000..c36048a --- /dev/null +++ b/AdamController.Services/Interfaces/IThemeManagerService.cs @@ -0,0 +1,8 @@ +using System; + +namespace AdamController.Services.Interfaces +{ + public interface IThemeManagerService : IDisposable + { + } +} diff --git a/AdamController.Services/ThemeManagerService.cs b/AdamController.Services/ThemeManagerService.cs new file mode 100644 index 0000000..178f5e9 --- /dev/null +++ b/AdamController.Services/ThemeManagerService.cs @@ -0,0 +1,38 @@ +using AdamController.Services.Interfaces; +using ControlzEx.Theming; +using System.Collections.ObjectModel; + +namespace AdamController.Services +{ + public class ThemeManagerService : IThemeManagerService + { + //ThemeManager mCurrentThemeManager; + + #region ~ + + public ThemeManagerService(int a) + { + //mCurrentThemeManager = ThemeManager.Current; + + //ReadOnlyObservableCollection themesCollection = mCurrentThemeManager.Themes; + //ReadOnlyObservableCollection colorSchemes = mCurrentThemeManager.ColorSchemes; + //ReadOnlyObservableCollection baseColorsCollection = mCurrentThemeManager.BaseColors; + //ReadOnlyObservableCollection themeProviders = mCurrentThemeManager.LibraryThemeProviders; + + var s = a; + + } + + #endregion + + + #region Public methods + + public void Dispose() + { + + } + + #endregion + } +} diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 72c41f5..3fd9531 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -74,23 +74,24 @@ protected override Window CreateShell() return window; } - protected override void OnStartup(StartupEventArgs e) - { - base.OnStartup(e); + //protected override void OnStartup(StartupEventArgs e) + //{ + // base.OnStartup(e); //TODO check theme before ChangeTheme - _ = ThemeManager.Current.ChangeTheme(this, $"{Settings.Default.BaseTheme}.{Settings.Default.ThemeColorScheme}", false); + //_ = ThemeManager.Current.ChangeTheme(this, $"{Settings.Default.BaseTheme}.{Settings.Default.ThemeColorScheme}", false); - } + //} protected override void RegisterTypes(IContainerRegistry containerRegistry) { - containerRegistry.RegisterSingleton(containerRegistry => + + containerRegistry.RegisterSingleton(() => { return new FileManagmentService(); }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(() => { return new FolderManagmentService(); }); @@ -102,17 +103,17 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return avalonService; }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(() => { return new WebViewProvider(); }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(() => { return new SubRegionChangeAwareService(); }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(() => { return new StatusBarNotificationDeliveryService(); }); @@ -125,7 +126,7 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return new FlyoutManager(container, regionManager); }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(() => { TcpClientOption option = new() { @@ -140,7 +141,7 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return client; }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(() => { IPAddress ip = IPAddress.Any; int port = int.Parse(Settings.Default.MessageDataExchangePort); @@ -154,7 +155,7 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return client; }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(() => { IPAddress ip = IPAddress.Any; int port = Settings.Default.LogServerPort; @@ -168,7 +169,7 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return server; }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(() => { string ip = Settings.Default.ServerIP; int port = Settings.Default.SoketServerPort; @@ -183,7 +184,7 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return client; }); - containerRegistry.RegisterSingleton(containerRegistry => + containerRegistry.RegisterSingleton(() => { string ip = Settings.Default.ServerIP; int port = Settings.Default.ApiPort; @@ -215,6 +216,12 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return remoteRunnerService; }); + containerRegistry.RegisterSingleton(() => + { + ThemeManagerService manager = new(5); + return manager; + }); + RegisterDialogs(containerRegistry); } @@ -272,6 +279,7 @@ private void SaveSettiings() /// private void DisposeServices() { + Container.Resolve().Dispose(); Container.Resolve().Dispose(); Container.Resolve().Dispose(); Container.Resolve().Dispose(); From 143baf1539f6d3a356f2d28689d21617601749aa Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 22 Apr 2024 16:09:02 +1000 Subject: [PATCH 120/181] Prepare work #44 --- AdamController.Services/AppThemeManager.cs | 19 ++++++++++ .../FileManagmentService.cs | 5 ++- .../Interfaces/IAppThemeManager.cs | 9 +++++ .../Interfaces/IThemeManagerService.cs | 8 ---- .../ThemeManagerService.cs | 38 ------------------- AdamController/App.xaml.cs | 21 ++++------ .../VisualSettingsControlViewModel.cs | 5 ++- 7 files changed, 44 insertions(+), 61 deletions(-) create mode 100644 AdamController.Services/AppThemeManager.cs create mode 100644 AdamController.Services/Interfaces/IAppThemeManager.cs delete mode 100644 AdamController.Services/Interfaces/IThemeManagerService.cs delete mode 100644 AdamController.Services/ThemeManagerService.cs diff --git a/AdamController.Services/AppThemeManager.cs b/AdamController.Services/AppThemeManager.cs new file mode 100644 index 0000000..2d8ffb4 --- /dev/null +++ b/AdamController.Services/AppThemeManager.cs @@ -0,0 +1,19 @@ +using AdamController.Services.Interfaces; +using System; + +namespace AdamController.Services +{ + public class AppThemeManager : IAppThemeManager + { + public AppThemeManager() + { + Name = "app"; + } + + public string Name { get; private set; } + public void Dispose() + { + + } + } +} diff --git a/AdamController.Services/FileManagmentService.cs b/AdamController.Services/FileManagmentService.cs index fd83e42..7db607f 100644 --- a/AdamController.Services/FileManagmentService.cs +++ b/AdamController.Services/FileManagmentService.cs @@ -17,7 +17,10 @@ public class FileManagmentService : IFileManagmentService #region ~ - public FileManagmentService() { } + public FileManagmentService() + { + + } #endregion diff --git a/AdamController.Services/Interfaces/IAppThemeManager.cs b/AdamController.Services/Interfaces/IAppThemeManager.cs new file mode 100644 index 0000000..6e7ce43 --- /dev/null +++ b/AdamController.Services/Interfaces/IAppThemeManager.cs @@ -0,0 +1,9 @@ +using System; + +namespace AdamController.Services.Interfaces +{ + public interface IAppThemeManager : IDisposable + { + public string Name { get; } + } +} diff --git a/AdamController.Services/Interfaces/IThemeManagerService.cs b/AdamController.Services/Interfaces/IThemeManagerService.cs deleted file mode 100644 index c36048a..0000000 --- a/AdamController.Services/Interfaces/IThemeManagerService.cs +++ /dev/null @@ -1,8 +0,0 @@ -using System; - -namespace AdamController.Services.Interfaces -{ - public interface IThemeManagerService : IDisposable - { - } -} diff --git a/AdamController.Services/ThemeManagerService.cs b/AdamController.Services/ThemeManagerService.cs deleted file mode 100644 index 178f5e9..0000000 --- a/AdamController.Services/ThemeManagerService.cs +++ /dev/null @@ -1,38 +0,0 @@ -using AdamController.Services.Interfaces; -using ControlzEx.Theming; -using System.Collections.ObjectModel; - -namespace AdamController.Services -{ - public class ThemeManagerService : IThemeManagerService - { - //ThemeManager mCurrentThemeManager; - - #region ~ - - public ThemeManagerService(int a) - { - //mCurrentThemeManager = ThemeManager.Current; - - //ReadOnlyObservableCollection themesCollection = mCurrentThemeManager.Themes; - //ReadOnlyObservableCollection colorSchemes = mCurrentThemeManager.ColorSchemes; - //ReadOnlyObservableCollection baseColorsCollection = mCurrentThemeManager.BaseColors; - //ReadOnlyObservableCollection themeProviders = mCurrentThemeManager.LibraryThemeProviders; - - var s = a; - - } - - #endregion - - - #region Public methods - - public void Dispose() - { - - } - - #endregion - } -} diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 3fd9531..b39cf48 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -1,9 +1,7 @@ #region system using System; -using System.IO; using System.Windows; -using System.Xml; #endregion @@ -42,14 +40,11 @@ #region other using ControlzEx.Theming; -using ICSharpCode.AvalonEdit.Highlighting; using AdamController.Core.Properties; using System.Diagnostics; using System.Threading.Tasks; using System.Net; using AdamController.Services.TcpClientDependency; -using ICSharpCode.AvalonEdit.Highlighting.Xshd; -using AdamController.Core; #endregion @@ -85,7 +80,6 @@ protected override Window CreateShell() protected override void RegisterTypes(IContainerRegistry containerRegistry) { - containerRegistry.RegisterSingleton(() => { return new FileManagmentService(); @@ -102,7 +96,12 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) AvalonEditService avalonService = new(fileManagment); return avalonService; }); - + + containerRegistry.RegisterSingleton(() => + { + return new AppThemeManager(); + }); + containerRegistry.RegisterSingleton(() => { return new WebViewProvider(); @@ -216,11 +215,7 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return remoteRunnerService; }); - containerRegistry.RegisterSingleton(() => - { - ThemeManagerService manager = new(5); - return manager; - }); + RegisterDialogs(containerRegistry); } @@ -279,10 +274,10 @@ private void SaveSettiings() /// private void DisposeServices() { - Container.Resolve().Dispose(); Container.Resolve().Dispose(); Container.Resolve().Dispose(); Container.Resolve().Dispose(); + Container.Resolve().Dispose(); Container.Resolve().Dispose(); Container.Resolve().Dispose(); diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index 229c24a..945def3 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -30,17 +30,20 @@ public class VisualSettingsControlViewModel : RegionViewModelBase #region Services private readonly IFlyoutManager mFlyoutManager; + private readonly IAppThemeManager mAppThemeManager; #endregion #region ~ - public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager, IWebViewProvider webViewProvider) : base(regionManager, dialogService) + public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager, IAppThemeManager appThemeManager) : base(regionManager, dialogService) { mFlyoutManager = flyoutManager; + mAppThemeManager = appThemeManager; OpenAdvancedBlocklySettingsDelegateCommand = new DelegateCommand(OpenAdvancedBlocklySettings, OpenAdvancedBlocklySettingsCanExecute); ChangeBaseThemeDelegateCommand = new DelegateCommand(ChangeBaseTheme, ChangeBaseThemeCanExecute); + var s = mAppThemeManager.Name; } #endregion From d24667033699ff79aa92ab65d3eeae9902463126 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Wed, 24 Apr 2024 10:13:50 +1000 Subject: [PATCH 121/181] Close #44 --- AdamController.Core/App.config | 257 ++++++++++++++++++ .../Properties/Settings.Designer.cs | 14 +- .../Properties/Settings.settings | 5 +- .../Interfaces/IThemeManagerService.cs | 16 +- .../ThemeManagerService.cs | 47 +++- AdamController/App.xaml.cs | 49 +--- .../ViewModels/MainWindowViewModel.cs | 12 +- .../VisualSettingsControlViewModel.cs | 92 ++++--- .../Views/VisualSettingsControlView.xaml | 42 +-- 9 files changed, 394 insertions(+), 140 deletions(-) diff --git a/AdamController.Core/App.config b/AdamController.Core/App.config index 0d6b677..41885a3 100644 --- a/AdamController.Core/App.config +++ b/AdamController.Core/App.config @@ -2,6 +2,7 @@ +
@@ -9,6 +10,262 @@ + + + 18000 + + + 15005 + + + 192.168.50.10 + + + Light + + + Blue + + + 0 + + + False + + + 20 + + + 0 + + + + + + True + + + True + + + ru + + + True + + + True + + + True + + + True + + + True + + + True + + + False + + + True + + + + + + + + + + + + + + + + + + + + + + + + + + + False + + + False + + + False + + + False + + + 854 + + + 512 + + + True + + + + + + + + + + + + + + + + + + True + + + True + + + 15000 + + + 32 + + + 192.168.50.10 + + + 15000 + + + 1 + + + 1000 + + + 10 + + + 10 + + + 16001 + + + 16002 + + + 32 + + + 1000 + + + 1 + + + 16000 + + + False + + + + + + 3 + + + 0 + + + 5 + + + 0 + + + True + + + False + + + True + + + 1 + + + True + + + False + + + + + + + + + True + + + + + + False + + + + + + adam + + + adam1234 + + + 5147 + + + True + + + 7071 + + + False + + + True + + + 8000 + + + + + 18000 diff --git a/AdamController.Core/Properties/Settings.Designer.cs b/AdamController.Core/Properties/Settings.Designer.cs index d5eb7fc..ec9bb80 100644 --- a/AdamController.Core/Properties/Settings.Designer.cs +++ b/AdamController.Core/Properties/Settings.Designer.cs @@ -12,7 +12,7 @@ namespace AdamController.Core.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.9.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.7.0.0")] public sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); @@ -1054,5 +1054,17 @@ public int SoketServerPort { this["SoketServerPort"] = value; } } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string AppThemeName { + get { + return ((string)(this["AppThemeName"])); + } + set { + this["AppThemeName"] = value; + } + } } } diff --git a/AdamController.Core/Properties/Settings.settings b/AdamController.Core/Properties/Settings.settings index 6e6d614..3869574 100644 --- a/AdamController.Core/Properties/Settings.settings +++ b/AdamController.Core/Properties/Settings.settings @@ -1,5 +1,5 @@  - + @@ -260,5 +260,8 @@ 8000 + + + \ No newline at end of file diff --git a/AdamController.Services/Interfaces/IThemeManagerService.cs b/AdamController.Services/Interfaces/IThemeManagerService.cs index c36048a..3139da2 100644 --- a/AdamController.Services/Interfaces/IThemeManagerService.cs +++ b/AdamController.Services/Interfaces/IThemeManagerService.cs @@ -1,8 +1,22 @@ -using System; +using ControlzEx.Theming; +using System; +using System.Collections.ObjectModel; namespace AdamController.Services.Interfaces { public interface IThemeManagerService : IDisposable { + #region Public fields + public ReadOnlyObservableCollection AppThemesCollection { get; } + + #endregion + + #region Public methods + + public Theme GetCurrentAppTheme(); + public Theme ChangeAppTheme(string themeName); + public Theme ChangeAppTheme(Theme themeName); + + #endregion } } diff --git a/AdamController.Services/ThemeManagerService.cs b/AdamController.Services/ThemeManagerService.cs index 178f5e9..dd84154 100644 --- a/AdamController.Services/ThemeManagerService.cs +++ b/AdamController.Services/ThemeManagerService.cs @@ -1,33 +1,56 @@ using AdamController.Services.Interfaces; using ControlzEx.Theming; using System.Collections.ObjectModel; +using System.Windows; namespace AdamController.Services { public class ThemeManagerService : IThemeManagerService { - //ThemeManager mCurrentThemeManager; - + private readonly Application mCurrentApplication; + private readonly ThemeManager mCurrentThemeManager; + #region ~ - public ThemeManagerService(int a) + public ThemeManagerService() { - //mCurrentThemeManager = ThemeManager.Current; - - //ReadOnlyObservableCollection themesCollection = mCurrentThemeManager.Themes; - //ReadOnlyObservableCollection colorSchemes = mCurrentThemeManager.ColorSchemes; - //ReadOnlyObservableCollection baseColorsCollection = mCurrentThemeManager.BaseColors; - //ReadOnlyObservableCollection themeProviders = mCurrentThemeManager.LibraryThemeProviders; - - var s = a; - + mCurrentApplication = Application.Current; + mCurrentThemeManager = ThemeManager.Current; + AppThemesCollection = mCurrentThemeManager.Themes; } #endregion + #region Public filelds + + public ReadOnlyObservableCollection AppThemesCollection { get; private set; } + + #endregion #region Public methods + public Theme ChangeAppTheme(string themeName) + { + var isThemeExist = mCurrentThemeManager.GetTheme(themeName) != null; + + if (isThemeExist) + return mCurrentThemeManager.ChangeTheme(mCurrentApplication, themeName, false); + + return null; + } + + public Theme ChangeAppTheme(Theme themeName) + { + return mCurrentThemeManager.ChangeTheme(mCurrentApplication, themeName.Name, false); + } + + public Theme GetCurrentAppTheme() + { + return mCurrentThemeManager.DetectTheme(); + } + + + public void Dispose() { diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 3fd9531..c160f9f 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -62,8 +62,6 @@ public partial class App : PrismApplication public App() { SetupUnhandledExceptionHandling(); - //? - //this.Dispatcher.UnhandledException += this.OnDispatcherUnhandledException; } #endregion @@ -74,27 +72,10 @@ protected override Window CreateShell() return window; } - //protected override void OnStartup(StartupEventArgs e) - //{ - // base.OnStartup(e); - - //TODO check theme before ChangeTheme - //_ = ThemeManager.Current.ChangeTheme(this, $"{Settings.Default.BaseTheme}.{Settings.Default.ThemeColorScheme}", false); - - //} - protected override void RegisterTypes(IContainerRegistry containerRegistry) { - - containerRegistry.RegisterSingleton(() => - { - return new FileManagmentService(); - }); - - containerRegistry.RegisterSingleton(() => - { - return new FolderManagmentService(); - }); + containerRegistry.RegisterSingleton(); + containerRegistry.RegisterSingleton(); containerRegistry.RegisterSingleton(containerRegistry => { @@ -103,20 +84,9 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return avalonService; }); - containerRegistry.RegisterSingleton(() => - { - return new WebViewProvider(); - }); - - containerRegistry.RegisterSingleton(() => - { - return new SubRegionChangeAwareService(); - }); - - containerRegistry.RegisterSingleton(() => - { - return new StatusBarNotificationDeliveryService(); - }); + containerRegistry.RegisterSingleton(); + containerRegistry.RegisterSingleton(); + containerRegistry.RegisterSingleton(); containerRegistry.RegisterSingleton(containerRegistry => { @@ -216,11 +186,7 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) return remoteRunnerService; }); - containerRegistry.RegisterSingleton(() => - { - ThemeManagerService manager = new(5); - return manager; - }); + containerRegistry.RegisterSingleton(); RegisterDialogs(containerRegistry); } @@ -268,8 +234,6 @@ private void OnAppCrashOrExit() private void SaveSettiings() { - Settings.Default.BaseTheme = ThemeManager.Current.DetectTheme(Current).BaseColorScheme; - Settings.Default.ThemeColorScheme = ThemeManager.Current.DetectTheme(Current).ColorScheme; Settings.Default.Save(); } @@ -289,7 +253,6 @@ private void DisposeServices() Container.Resolve().Dispose(); Container.Resolve().Dispose(); - Container.Resolve().Dispose(); Container.Resolve().Dispose(); Container.Resolve().Dispose(); diff --git a/AdamController/ViewModels/MainWindowViewModel.cs b/AdamController/ViewModels/MainWindowViewModel.cs index d6cbcff..eda6135 100644 --- a/AdamController/ViewModels/MainWindowViewModel.cs +++ b/AdamController/ViewModels/MainWindowViewModel.cs @@ -28,13 +28,15 @@ public class MainWindowViewModel : ViewModelBase private readonly IFolderManagmentService mFolderManagment; private readonly IWebApiService mWebApiService; private readonly IAvalonEditService mAvalonEditService; + private readonly IThemeManagerService mThemeManager; #endregion #region ~ public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareService subRegionChangeAwareService, IStatusBarNotificationDeliveryService statusBarNotification, - ICommunicationProviderService communicationProviderService, IFolderManagmentService folderManagment, IWebApiService webApiService, IAvalonEditService avalonEditService) + ICommunicationProviderService communicationProviderService, IFolderManagmentService folderManagment, IWebApiService webApiService, + IAvalonEditService avalonEditService, IThemeManagerService themeManager) { RegionManager = regionManager; mWebApiService = webApiService; @@ -43,6 +45,7 @@ public MainWindowViewModel(IRegionManager regionManager, ISubRegionChangeAwareSe mCommunicationProviderService = communicationProviderService; mFolderManagment = folderManagment; mAvalonEditService = avalonEditService; + mThemeManager = themeManager; ShowRegionCommand = new DelegateCommand(ShowRegion); Subscribe(); @@ -176,6 +179,12 @@ private void LoadCustomAvalonEditHighlighting() mAvalonEditService.RegisterHighlighting(HighlightingName.AdamPython, Resource.AdamPython); } + private void LoadAppTheme() + { + var appThemeName = Settings.Default.AppThemeName; + mThemeManager.ChangeAppTheme(appThemeName); + } + #endregion #region Subscriptions @@ -213,6 +222,7 @@ private void MainWindowLoaded(object sender, RoutedEventArgs e) { SaveFolderPathToSettings(); LoadCustomAvalonEditHighlighting(); + LoadAppTheme(); ShowRegionCommand.Execute(SubRegionNames.SubRegionScratch); mStatusBarNotification.CompileLogMessage = "Загрузка приложения завершена"; diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs index 229c24a..22685e9 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/VisualSettingsControlViewModel.cs @@ -1,7 +1,6 @@ using AdamBlocklyLibrary.Enum; using AdamController.Controls.CustomControls.Services; using AdamController.Core; -using AdamController.Core.DataSource; using AdamController.Core.Model; using AdamController.Core.Mvvm; using AdamController.Core.Properties; @@ -12,8 +11,6 @@ using Prism.Services.Dialogs; using System; using System.Collections.ObjectModel; -using System.Linq; -using System.Windows; using System.Windows.Media; namespace AdamController.Modules.ContentRegion.ViewModels @@ -23,26 +20,27 @@ public class VisualSettingsControlViewModel : RegionViewModelBase #region DelegateCommands public DelegateCommand OpenAdvancedBlocklySettingsDelegateCommand { get; } - public DelegateCommand ChangeBaseThemeDelegateCommand { get; } #endregion #region Services - private readonly IFlyoutManager mFlyoutManager; + private readonly IFlyoutManager mFlyoutManager; + private readonly IThemeManagerService mThemeManager; #endregion #region ~ - public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager, IWebViewProvider webViewProvider) : base(regionManager, dialogService) + public VisualSettingsControlViewModel(IRegionManager regionManager, IDialogService dialogService, IFlyoutManager flyoutManager, IThemeManagerService themeManager) : base(regionManager, dialogService) { mFlyoutManager = flyoutManager; + mThemeManager = themeManager; OpenAdvancedBlocklySettingsDelegateCommand = new DelegateCommand(OpenAdvancedBlocklySettings, OpenAdvancedBlocklySettingsCanExecute); - ChangeBaseThemeDelegateCommand = new DelegateCommand(ChangeBaseTheme, ChangeBaseThemeCanExecute); } + #endregion #region DelegateCommand methods @@ -57,16 +55,6 @@ private bool OpenAdvancedBlocklySettingsCanExecute() return true; } - private void ChangeBaseTheme(string theme) - { - ChangeTheme(theme); - } - - private bool ChangeBaseThemeCanExecute(string theme) - { - return true; - } - #endregion #region Navigation @@ -80,6 +68,10 @@ public override void OnNavigatedTo(NavigationContext navigationContext) { base.OnNavigatedTo(navigationContext); + /*new*/ + ThemesCollection = mThemeManager.AppThemesCollection; + SelectedTheme = mThemeManager.GetCurrentAppTheme(); + LanguageApp = new ObservableCollection { new AppLanguageModel { AppLanguage = "ru", LanguageName = "Русский" } @@ -92,14 +84,13 @@ public override void OnNavigatedTo(NavigationContext navigationContext) new BlocklyLanguageModel { BlocklyLanguage = BlocklyLanguage.en, LanguageName = "Английский" } }; - BlocklyThemes = ThemesCollection.BlocklyThemes; - ColorScheme = ThemeManager.Current.ColorSchemes; - //SelectedLanguageApp = LanguageApp.FirstOrDefault(x => x.AppLanguage == Settings.Default.AppLanguage); //SelectedBlocklyWorkspaceLanguage = BlocklyLanguageCollection.FirstOrDefault(x => x.BlocklyLanguage == Settings.Default.BlocklyWorkspaceLanguage); - SelectedColorScheme = ThemeManager.Current.DetectTheme(Application.Current).ColorScheme; NotificationOpacity = Settings.Default.NotificationOpacity; + + + } public override void OnNavigatedFrom(NavigationContext navigationContext) @@ -126,19 +117,39 @@ public ObservableCollection BlocklyLanguageCollection private set => SetProperty(ref blocklyLanguageCollection, value); } - private ObservableCollection blocklyThemes; + public ReadOnlyObservableCollection themesCollection; + public ReadOnlyObservableCollection ThemesCollection + { + get => themesCollection; + set => SetProperty(ref themesCollection, value); + } + + public Theme selectedTheme; + public Theme SelectedTheme + { + get => selectedTheme; + set + { + bool isNewValue = SetProperty(ref selectedTheme, value); + + if (isNewValue) + ChangeTheme(SelectedTheme); + } + } + + /*private ObservableCollection blocklyThemes; public ObservableCollection BlocklyThemes { get => blocklyThemes; private set => SetProperty(ref blocklyThemes, value); - } + }*/ - private ReadOnlyObservableCollection colorScheme; + /*private ReadOnlyObservableCollection colorScheme; public ReadOnlyObservableCollection ColorScheme { get => colorScheme; private set => SetProperty(ref colorScheme, value); - } + }*/ /*private AppLanguageModel selectedLanguageApp; public AppLanguageModel SelectedLanguageApp @@ -171,19 +182,6 @@ public BlocklyLanguageModel SelectedBlocklyWorkspaceLanguage } }*/ - private string selectedColorScheme; - public string SelectedColorScheme - { - get => selectedColorScheme; - set - { - bool isNewValue = SetProperty(ref selectedColorScheme, value); - - if (isNewValue) - ChangeThemeColorScheme(SelectedColorScheme); - } - } - private double notificationOpacity; public double NotificationOpacity @@ -196,19 +194,17 @@ public double NotificationOpacity #region Private methods - private void ChangeTheme(string newTheme) + private void ChangeBlockllyTheme(string baseColorAppTheme) { - _ = ThemeManager.Current.ChangeThemeBaseColor(Application.Current, newTheme); - if (!Settings.Default.ChangeBlocklyThemeToggleSwitchState) { - if (newTheme == "Dark") + if (baseColorAppTheme == "Dark") { Settings.Default.BlocklyTheme = BlocklyTheme.Dark; Settings.Default.BlocklyGridColour = Colors.White.ToString(); } - if (newTheme == "Light") + if (baseColorAppTheme == "Light") { Settings.Default.BlocklyTheme = BlocklyTheme.Classic; Settings.Default.BlocklyGridColour = Colors.Black.ToString(); @@ -216,9 +212,15 @@ private void ChangeTheme(string newTheme) } } - private void ChangeThemeColorScheme(string colorScheme) + private void ChangeTheme(Theme theme) { - ThemeManager.Current.ChangeThemeColorScheme(Application.Current, colorScheme); + Theme chagedTheme = mThemeManager.ChangeAppTheme(theme); + ChangeBlockllyTheme(chagedTheme.BaseColorScheme); + + Settings.Default.AppThemeName = chagedTheme.Name; + + //Is it necessary to save here? + Settings.Default.Save(); } #endregion diff --git a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml index 510622a..d0b0e2d 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml @@ -68,51 +68,20 @@ - \ No newline at end of file diff --git a/AdamController/App.xaml.cs b/AdamController/App.xaml.cs index 5986315..76126cf 100644 --- a/AdamController/App.xaml.cs +++ b/AdamController/App.xaml.cs @@ -210,6 +210,7 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) }); containerRegistry.RegisterSingleton(); + containerRegistry.RegisterSingleton(); RegisterDialogs(containerRegistry); } @@ -276,6 +277,8 @@ private void DisposeServices() Container.Resolve().Dispose(); Container.Resolve().Dispose(); Container.Resolve().Dispose(); + + Container.Resolve().Dispose(); } #region Subscribes diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index ab8e86e..44f883f 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -3,6 +3,7 @@ using AdamBlocklyLibrary.Struct; using AdamBlocklyLibrary.Toolbox; using AdamBlocklyLibrary.ToolboxSets; +using AdamController.Controls.CustomControls.Services; using AdamController.Core; using AdamController.Core.Extensions; using AdamController.Core.Mvvm; @@ -11,10 +12,13 @@ using AdamController.Services.WebViewProviderDependency; using AdamController.WebApi.Client.v1.ResponseModel; using ICSharpCode.AvalonEdit.Highlighting; +using MahApps.Metro.Controls; using Prism.Commands; using Prism.Regions; using System; +using System.Runtime; using System.Threading.Tasks; +using System.Windows; using System.Windows.Threading; namespace AdamController.Modules.ContentRegion.ViewModels @@ -23,6 +27,7 @@ public class ScratchControlViewModel : RegionViewModelBase { #region DelegateCommands + public DelegateCommand MoveSplitterDelegateCommand { get; } public DelegateCommand ReloadWebViewDelegateCommand { get; } public DelegateCommand ShowSaveFileDialogDelegateCommand { get; } public DelegateCommand ShowOpenFileDialogDelegateCommand { get; } @@ -44,6 +49,7 @@ public class ScratchControlViewModel : RegionViewModelBase private readonly IDialogManagerService mDialogManager; private readonly IFileManagmentService mFileManagment; private readonly IWebApiService mWebApiService; + private readonly IControlHelper mControlHelper; #endregion @@ -67,7 +73,7 @@ public class ScratchControlViewModel : RegionViewModelBase public ScratchControlViewModel(IRegionManager regionManager, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IWebViewProvider webViewProvider, IDialogManagerService dialogManager, - IFileManagmentService fileManagment, IWebApiService webApiService, IAvalonEditService avalonEditService) : base(regionManager) + IFileManagmentService fileManagment, IWebApiService webApiService, IAvalonEditService avalonEditService, IControlHelper controlHelper) : base(regionManager) { mCommunicationProvider = communicationProvider; mPythonRemoteRunner = pythonRemoteRunner; @@ -76,7 +82,9 @@ public ScratchControlViewModel(IRegionManager regionManager, ICommunicationProvi mDialogManager = dialogManager; mFileManagment = fileManagment; mWebApiService = webApiService; + mControlHelper = controlHelper; + MoveSplitterDelegateCommand = new DelegateCommand(MoveSplitter, MoveSplitterCanExecute); ReloadWebViewDelegateCommand = new DelegateCommand(ReloadWebView, ReloadWebViewCanExecute); ShowSaveFileDialogDelegateCommand = new DelegateCommand(ShowSaveFileDialog, ShowSaveFileDialogCanExecute); ShowOpenFileDialogDelegateCommand = new DelegateCommand(ShowOpenFileDialog, ShowOpenFileDialogCanExecute); @@ -89,6 +97,14 @@ public ScratchControlViewModel(IRegionManager regionManager, ICommunicationProvi HighlightingDefinition = avalonEditService.GetDefinition(HighlightingName.AdamPython); } + + /*private double controlWidth; + public double ControlWidth + { + get { return controlWidth; } + set => SetProperty(ref controlWidth, value); + }*/ + #endregion #region Navigation @@ -266,6 +282,40 @@ private void Unsubscribe() #region DelegateCommands methods + private void MoveSplitter(string arg) + { + var dividedScreen = mControlHelper.ActualWidth / 2; + + if (arg == "Left") + { + if (Settings.Default.BlocklyEditorWidth >= mControlHelper.ActualWidth - 10) + { + Settings.Default.BlocklyEditorWidth = dividedScreen; + return; + } + + if (Settings.Default.BlocklyEditorWidth <= mControlHelper.ActualWidth - 500) + Settings.Default.BlocklyEditorWidth = 0; + } + + if(arg == "Right") + { + if (Settings.Default.BlocklyEditorWidth == 0) + { + Settings.Default.BlocklyEditorWidth = dividedScreen; + return; + } + + + if (Settings.Default.BlocklyEditorWidth >= 500) + Settings.Default.BlocklyEditorWidth = mControlHelper.ActualWidth; + } + } + + private bool MoveSplitterCanExecute(string arg) + { + return true; + } private void ReloadWebView() { mWebViewProvider.ReloadWebView(); diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml index 8b170da..d45604f 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml @@ -19,304 +19,264 @@ - - - - - - - - - - - - - + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - + + - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + - - + - + - - + - - + + + - + + + + + + + + + + + + + + - + - - - + - - - - - + - - - - + + + + + + + + + + + + + + + + + + + + + + + - - - --> - + diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs index 8c8b9f2..3ff33eb 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml.cs @@ -1,4 +1,5 @@  +using AdamController.Controls.CustomControls.Services; using AdamController.Core.Properties; using AdamController.Services.Interfaces; using AdamController.Services.WebViewProviderDependency; @@ -20,6 +21,7 @@ public partial class ScratchControlView : UserControl private readonly IWebViewProvider mWebViewProvider; private readonly IStatusBarNotificationDeliveryService mStatusBarNotification; + private readonly IControlHelper mControlHelper; #endregion @@ -30,13 +32,14 @@ public partial class ScratchControlView : UserControl #endregion - public ScratchControlView(IWebViewProvider webViewProvider, IStatusBarNotificationDeliveryService statusBarNotification, IFolderManagmentService folderManagment) + public ScratchControlView(IWebViewProvider webViewProvider, IStatusBarNotificationDeliveryService statusBarNotification, IFolderManagmentService folderManagment, IControlHelper controlHelper) { InitializeComponent(); InitializeWebViewCore(); mWebViewProvider = webViewProvider; mStatusBarNotification = statusBarNotification; + mControlHelper = controlHelper; mPathToSource = Path.Combine(folderManagment.CommonDirAppData, "BlocklySource"); mPath = Path.Combine(Path.GetTempPath(), "AdamBrowser"); @@ -49,6 +52,13 @@ public ScratchControlView(IWebViewProvider webViewProvider, IStatusBarNotificati mWebViewProvider.RaiseExecuteReloadWebViewEvent += RaiseExecuteReloadWebViewEvent; TextResulEditor.TextChanged += TextResulEditorTextChanged; + + MainGrid.SizeChanged += MainGrid_SizeChanged; ; + } + + private void MainGrid_SizeChanged(object sender, SizeChangedEventArgs e) + { + mControlHelper.ActualWidth = MainGrid.ActualWidth; } private void RaiseExecuteReloadWebViewEvent(object sender) From 9d9b6430e5a4580fcb586ae516358a132051a0cf Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Fri, 3 May 2024 14:36:36 +1000 Subject: [PATCH 151/181] Close #51 p 9 --- .../ViewModels/ScratchControlViewModel.cs | 31 +++++++++++++------ .../Views/ScratchControlView.xaml | 27 ++++++++++++++++ .../Views/ScriptEditorControlView.xaml | 15 ++------- 3 files changed, 51 insertions(+), 22 deletions(-) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index 44f883f..3c2ee88 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -27,6 +27,7 @@ public class ScratchControlViewModel : RegionViewModelBase { #region DelegateCommands + public DelegateCommand CopyToClipboardDelegateCommand { get; } public DelegateCommand MoveSplitterDelegateCommand { get; } public DelegateCommand ReloadWebViewDelegateCommand { get; } public DelegateCommand ShowSaveFileDialogDelegateCommand { get; } @@ -84,6 +85,7 @@ public ScratchControlViewModel(IRegionManager regionManager, ICommunicationProvi mWebApiService = webApiService; mControlHelper = controlHelper; + CopyToClipboardDelegateCommand = new DelegateCommand(CopyToClipboard, CopyToClipboardCanExecute); MoveSplitterDelegateCommand = new DelegateCommand(MoveSplitter, MoveSplitterCanExecute); ReloadWebViewDelegateCommand = new DelegateCommand(ReloadWebView, ReloadWebViewCanExecute); ShowSaveFileDialogDelegateCommand = new DelegateCommand(ShowSaveFileDialog, ShowSaveFileDialogCanExecute); @@ -98,13 +100,6 @@ public ScratchControlViewModel(IRegionManager regionManager, ICommunicationProvi HighlightingDefinition = avalonEditService.GetDefinition(HighlightingName.AdamPython); } - /*private double controlWidth; - public double ControlWidth - { - get { return controlWidth; } - set => SetProperty(ref controlWidth, value); - }*/ - #endregion #region Navigation @@ -282,6 +277,19 @@ private void Unsubscribe() #region DelegateCommands methods + private void CopyToClipboard() + { + Clipboard.SetText(SourceTextEditor); + } + + private bool CopyToClipboardCanExecute() + { + bool isPythonCodeNotExecute = !IsPythonCodeExecute; + bool isSourceNotEmpty = SourceTextEditor?.Length > 0; + + return isPythonCodeNotExecute && isSourceNotEmpty; + } + private void MoveSplitter(string arg) { var dividedScreen = mControlHelper.ActualWidth / 2; @@ -314,7 +322,8 @@ private void MoveSplitter(string arg) private bool MoveSplitterCanExecute(string arg) { - return true; + bool isPythonCodeNotExecute = !IsPythonCodeExecute; + return isPythonCodeNotExecute; } private void ReloadWebView() { @@ -586,7 +595,7 @@ private void OnPythonCodeExecuteStatusChange(bool isPythonCodeExecute) if (!isPythonCodeExecute) { - System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(async () => + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(async () => { await mWebViewProvider.ExecuteJavaScript(Scripts.ShadowDisable); })); @@ -612,7 +621,7 @@ private void OnPythonCodeExecuteStatusChange(bool isPythonCodeExecute) if (!Settings.Default.ShadowWorkspaceInDebug) return; - System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(async () => + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(async () => { await mWebViewProvider.ExecuteJavaScript(Scripts.ShadowEnable); })); @@ -635,6 +644,8 @@ private void UpdatePythonInfo(string pythonVersion = "", string pythonBinPath = private void RaiseDelegateCommandsCanExecuteChanged() { + MoveSplitterDelegateCommand.RaiseCanExecuteChanged(); + CopyToClipboardDelegateCommand.RaiseCanExecuteChanged(); ReloadWebViewDelegateCommand.RaiseCanExecuteChanged(); ShowSaveFileDialogDelegateCommand.RaiseCanExecuteChanged(); ShowOpenFileDialogDelegateCommand.RaiseCanExecuteChanged(); diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml index d45604f..b93dcfc 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml @@ -146,6 +146,32 @@ + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScriptEditorControlView.xaml.cs b/Modules/AdamController.Modules.ContentRegion/Views/ScriptEditorControlView.xaml.cs deleted file mode 100644 index 42027b0..0000000 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScriptEditorControlView.xaml.cs +++ /dev/null @@ -1,185 +0,0 @@ -using System; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Threading; - - -namespace AdamController.Modules.ContentRegion.Views -{ - public partial class ScriptEditorControlView : UserControl - { - public ScriptEditorControlView() - { - InitializeComponent(); - //LoadHighlighting(); - - TextResulEditor.TextChanged += TextResulEditorTextChanged; - } - - private void TextResulEditorTextChanged(object sender, EventArgs e) - { - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => - { - TextResulEditor.ScrollToEnd(); - })); - - } - - #region Example code - - /*public ScriptEditorControl() - { - //IHighlightingDefinition customHighlighting = HighlightingManager.Instance.HighlightingDefinitions[0]; - - InitializeComponent(); - - //textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#"); - //textEditor.SyntaxHighlighting = customHighlighting; - // initial highlighting now set by XAML - - //textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; - //textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; - - /*DispatcherTimer foldingUpdateTimer = new() - { - Interval = TimeSpan.FromSeconds(2) - }; - - foldingUpdateTimer.Tick += foldingUpdateTimer_Tick; - foldingUpdateTimer.Start(); - } - string currentFileName; - - void openFileClick(object sender, RoutedEventArgs e) - { - OpenFileDialog dlg = new() - { - CheckFileExists = true - }; - - if (dlg.ShowDialog() ?? false) - { - currentFileName = dlg.FileName; - textEditor.Load(currentFileName); - textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinitionByExtension(Path.GetExtension(currentFileName)); - } - } - - void saveFileClick(object sender, EventArgs e) - { - if (currentFileName == null) - { - SaveFileDialog dlg = new SaveFileDialog(); - dlg.DefaultExt = ".txt"; - if (dlg.ShowDialog() ?? false) - { - currentFileName = dlg.FileName; - } - else - { - return; - } - } - textEditor.Save(currentFileName); - } - - - - CompletionWindow completionWindow; - - void textEditor_TextArea_TextEntered(object sender, TextCompositionEventArgs e) - { - if (e.Text == ".") - { - // open code completion after the user has pressed dot: - completionWindow = new CompletionWindow(textEditor.TextArea); - - // provide AvalonEdit with the data: - IList data = completionWindow.CompletionList.CompletionData; - - data.Add(new EditorModel("Item1")); - data.Add(new EditorModel("Item2")); - data.Add(new EditorModel("Item3")); - data.Add(new EditorModel("Another item")); - completionWindow.Show(); - completionWindow.Closed += delegate { - completionWindow = null; - }; - } - } - - void textEditor_TextArea_TextEntering(object sender, TextCompositionEventArgs e) - { - if (e.Text.Length > 0 && completionWindow != null) - { - if (!char.IsLetterOrDigit(e.Text[0])) - { - // Whenever a non-letter is typed while the completion window is open, - // insert the currently selected element. - completionWindow.CompletionList.RequestInsertion(e); - } - } - // do not set e.Handled=true - we still want to insert the character that was typed - } - - #region Folding - private FoldingManager foldingManager; - private XmlFoldingStrategy foldingStrategy; - - void HighlightingComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) - { - if (textEditor.SyntaxHighlighting == null) - { - foldingStrategy = null; - } - else - { - switch (textEditor.SyntaxHighlighting.Name) - { - case "XML": - foldingStrategy = new XmlFoldingStrategy(); - textEditor.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.DefaultIndentationStrategy(); - break; - case "C#": - case "C++": - case "PHP": - case "Java": - textEditor.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.CSharp.CSharpIndentationStrategy(textEditor.Options); - foldingStrategy = new XmlFoldingStrategy(); - break; - default: - textEditor.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.DefaultIndentationStrategy(); - foldingStrategy = null; - break; - } - } - if (foldingStrategy != null) - { - if (foldingManager == null) - foldingManager = FoldingManager.Install(textEditor.TextArea); - - foldingStrategy.UpdateFoldings(foldingManager, textEditor.Document); - } - else - { - if (foldingManager != null) - { - FoldingManager.Uninstall(foldingManager); - foldingManager = null; - } - } - } - - void foldingUpdateTimer_Tick(object sender, EventArgs e) - { - if (foldingStrategy != null) - { - foldingStrategy.UpdateFoldings(foldingManager, textEditor.Document); - } - } - - }*/ - - #endregion - } -} diff --git a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs index 227002f..59f44ac 100644 --- a/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs +++ b/Modules/AdamController.Modules.MenuRegion/ViewModels/MenuRegionViewModel.cs @@ -64,13 +64,6 @@ public bool IsCheckedScratchMenuItem set => SetProperty(ref isCheckedScratchMenuItem, value); } - private bool isCheckedScriptEditorMenuItem; - public bool IsCheckedScriptEditorMenuItem - { - get => isCheckedScriptEditorMenuItem; - set => SetProperty(ref isCheckedScriptEditorMenuItem, value); - } - private bool isCheckedComputerVisionMenuItem; public bool IsCheckedComputerVisionMenuItem { @@ -98,9 +91,6 @@ private void ChangeCheckedMenuItem(string selectedSubRegionName) case SubRegionNames.SubRegionScratch: IsCheckedScratchMenuItem = true; break; - case SubRegionNames.SubRegionScriptEditor: - IsCheckedScriptEditorMenuItem = true; - break; case SubRegionNames.SubRegionComputerVisionControl: IsCheckedComputerVisionMenuItem = true; break; @@ -113,7 +103,6 @@ private void ChangeCheckedMenuItem(string selectedSubRegionName) private void ResetIsCheckedMenuItem() { IsCheckedScratchMenuItem = false; - IsCheckedScriptEditorMenuItem = false; IsCheckedComputerVisionMenuItem = false; IsCheckedVisualSettingsMenuItem = false; } @@ -152,9 +141,6 @@ private void ShowRegion(string subRegionName) case SubRegionNames.SubRegionScratch: RegionManager.RequestNavigate(RegionNames.ContentRegion, SubRegionNames.SubRegionScratch); break; - case SubRegionNames.SubRegionScriptEditor: - RegionManager.RequestNavigate(RegionNames.ContentRegion, SubRegionNames.SubRegionScriptEditor); - break; case SubRegionNames.SubRegionComputerVisionControl: RegionManager.RequestNavigate(RegionNames.ContentRegion, SubRegionNames.SubRegionComputerVisionControl); break; diff --git a/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml b/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml index 4a04fce..3c3071f 100644 --- a/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml +++ b/Modules/AdamController.Modules.MenuRegion/Views/MenuRegionView.xaml @@ -22,11 +22,6 @@ CommandParameter="{x:Static core:SubRegionNames.SubRegionScratch}" IsChecked="{Binding IsCheckedScratchMenuItem}" /> - - + + + + + - Date: Sun, 5 May 2024 13:27:32 +1000 Subject: [PATCH 153/181] Prepare works #51 p. 6 --- .../ViewModels/ScratchControlViewModel.cs | 21 ++++++- .../Views/ScratchControlView.xaml | 62 +++++++++++++------ 2 files changed, 63 insertions(+), 20 deletions(-) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index a6e75fe..bd15b5a 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -191,6 +191,20 @@ public string ResultText } } + private ExtendedCommandExecuteResult resultExecutionTime; + public ExtendedCommandExecuteResult ResultExecutionTime + { + get => resultExecutionTime; + set => SetProperty(ref resultExecutionTime, value); + } + + private ExtendedCommandExecuteResult resultInitilizationTime; + public ExtendedCommandExecuteResult ResultInitilizationTime + { + get => resultInitilizationTime; + set => SetProperty(ref resultInitilizationTime, value); + } + private string resultTextEditorError; public string ResultTextEditorError @@ -452,9 +466,11 @@ private async void RunPythonCode() } finally { + ResultInitilizationTime = executeResult; } + /* remove with settings */ if (Settings.Default.ChangeExtendedExecuteReportToggleSwitchState) { UpdateResultText("Отчет о инициализации процесса программы\n" + @@ -530,7 +546,7 @@ private bool ToZeroPositionCanExecute() private void UpdateResultText(string text, bool isFinishMessage = false) { - System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { if (isFinishMessage) { @@ -689,6 +705,9 @@ private void OnRaisePythonScriptExecuteFinish(object sender, ExtendedCommandExec if (remoteCommandExecuteResult == null) return; + ResultExecutionTime = remoteCommandExecuteResult; + + /* removed this */ string messageWithResult = $"{message}\n" + $"\n" + $"Отчет о выполнении\n" + diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml index 302c450..6c13387 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ScratchControlView.xaml @@ -10,6 +10,7 @@ xmlns:behaviors="clr-namespace:AdamController.Core.Behaviors;assembly=AdamController.Core" xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit" xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" + xmlns:system="clr-namespace:System;assembly=mscorlib" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True"> @@ -241,7 +242,6 @@ - + Grid.Row="3" + Grid.Column="0" + Grid.ColumnSpan="3" + IsExpanded="False" + Header="Результат" + BorderThickness="0" + ExpandDirection="Down" + BorderBrush="{DynamicResource MahApps.Brushes.Control.Border}" + mah:HeaderedControlHelper.HeaderBackground="{DynamicResource MahApps.Brushes.Control.Background}" + mah:ControlsHelper.ContentCharacterCasing="Normal"> @@ -272,34 +272,58 @@ - + - + + + + + + + + + + + + - + + + + + + + + + + + + From 74f6c035fdeb9b3a5b0802a113db40dbbf6604ee Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Sun, 5 May 2024 15:34:39 +1000 Subject: [PATCH 154/181] prepare works #51 p. 6-7 --- .../ViewModels/ScratchControlViewModel.cs | 131 ++++++++---------- .../Views/VisualSettingsControlView.xaml | 16 +-- 2 files changed, 58 insertions(+), 89 deletions(-) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index bd15b5a..b26093d 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -195,7 +195,18 @@ public string ResultText public ExtendedCommandExecuteResult ResultExecutionTime { get => resultExecutionTime; - set => SetProperty(ref resultExecutionTime, value); + set + { + bool isNewValue = SetProperty(ref resultExecutionTime, value); + + if (isNewValue) + { + /*fix*/ + ResultExecutionTime.Succeesed = ResultExecutionTime.ExitCode == 0; + } + } + + } private ExtendedCommandExecuteResult resultInitilizationTime; @@ -205,25 +216,6 @@ public ExtendedCommandExecuteResult ResultInitilizationTime set => SetProperty(ref resultInitilizationTime, value); } - - private string resultTextEditorError; - public string ResultTextEditorError - { - get => resultTextEditorError; - set - { - bool isNewValue = SetProperty(ref resultTextEditorError, value); - - if (isNewValue) - { - RaiseDelegateCommandsCanExecuteChanged(); - - if (ResultTextEditorError.Length > 0) - resultTextEditorError = $"Error: {ResultTextEditorError}"; - } - } - } - private string pythonVersion; public string PythonVersion { @@ -435,7 +427,6 @@ private bool ShowSaveFileSourceTextDialogCanExecute() private void CleanExecuteEditor() { - ResultTextEditorError = string.Empty; ClearResultText(); } @@ -448,44 +439,27 @@ private bool CleanExecuteEditorCanExecute() private async void RunPythonCode() { - ResultTextEditorError = string.Empty; ExtendedCommandExecuteResult executeResult = new(); + string source = SourceTextEditor; + bool isErrorHappened = false; try { var command = new WebApi.Client.v1.RequestModel.PythonCommandModel { - Command = SourceTextEditor + Command = source }; executeResult = await mWebApiService.PythonExecuteAsync(command); } catch (Exception ex) { - ResultTextEditorError = ex.Message.ToString(); + isErrorHappened = true; } finally { - ResultInitilizationTime = executeResult; - + UpdateResultInitilizationTimeText(executeResult); } - - /* remove with settings */ - if (Settings.Default.ChangeExtendedExecuteReportToggleSwitchState) - { - UpdateResultText("Отчет о инициализации процесса программы\n" + - "======================\n" + - $"Начало инициализации: {executeResult.StartTime}\n" + - $"Завершение инициализации: {executeResult.EndTime}\n" + - $"Общее время инициализации: {executeResult.RunTime}\n" + - $"Код выхода: {executeResult.ExitCode}\n" + - $"Статус успешности инициализации: {executeResult.Succeesed}" + - "\n======================\n"); - } - - if (!string.IsNullOrEmpty(executeResult?.StandardError)) - UpdateResultText($"Ошибка: {executeResult.StandardError}" + - "\n======================"); } private bool RunPythonCodeCanExecute() @@ -505,10 +479,15 @@ private async void StopPythonCodeExecute() { await mWebApiService.StopPythonExecute(); } - catch (Exception ex) + catch { - ResultTextEditorError = ex.Message.ToString(); + } + + /*catch (Exception ex) + { + //ResultTextEditorError = ex.Message.ToString(); + }*/ } private bool StopPythonCodeExecuteCanExecute() @@ -524,11 +503,17 @@ private async void ToZeroPosition() try { await mWebApiService.StopPythonExecute(); + await mWebApiService.MoveToZeroPosition(); } - catch (Exception ex) + catch { - ResultTextEditorError = ex.Message.ToString(); + } + + /*catch (Exception ex) + { + //ResultTextEditorError = ex.Message.ToString(); + }*/ } private bool ToZeroPositionCanExecute() @@ -550,8 +535,7 @@ private void UpdateResultText(string text, bool isFinishMessage = false) { if (isFinishMessage) { - ResultText += text; - IsPythonCodeExecute = false; + ResultText += "\n======================\n<<Выполнение программы завершено>>"; } if(!isFinishMessage) @@ -578,9 +562,29 @@ private void UpdateResultText(string text, bool isFinishMessage = false) })); } + private void UpdateResultExecutionTimeText(ExtendedCommandExecuteResult executeResult) + { + + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => + { + ResultExecutionTime = executeResult; + IsPythonCodeExecute = false; + })); + } + + private void UpdateResultInitilizationTimeText(ExtendedCommandExecuteResult executeResult) + { + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => + { + ResultInitilizationTime = executeResult; + })); + } + private void ClearResultText() { ResultText = string.Empty; + ResultExecutionTime = null; + ResultInitilizationTime = null; } private void OnPythonCodeExecuteStatusChange(bool isPythonCodeExecute) @@ -688,7 +692,7 @@ private void OnRaiseTcperviceClientDisconnect(object sender) UpdatePythonInfo(); } - private void OnRaisePythonScriptExecuteStart(object sender) + private void OnRaisePythonScriptExecuteStart(object sender) { IsPythonCodeExecute = true; } @@ -700,32 +704,11 @@ private void OnRaisePythonStandartOutput(object sender, string message) private void OnRaisePythonScriptExecuteFinish(object sender, ExtendedCommandExecuteResult remoteCommandExecuteResult) { - string message = "\n======================\n<<Выполнение программы завершено>>"; - if (remoteCommandExecuteResult == null) return; - - ResultExecutionTime = remoteCommandExecuteResult; - - /* removed this */ - string messageWithResult = $"{message}\n" + - $"\n" + - $"Отчет о выполнении\n" + - $"======================\n" + - $"Начало выполнения: {remoteCommandExecuteResult.StartTime}\n" + - $"Завершение выполнения: {remoteCommandExecuteResult.EndTime}\n" + - $"Общее время выполнения: {remoteCommandExecuteResult.RunTime}\n" + - $"Код выхода: {remoteCommandExecuteResult.ExitCode}\n" + - //The server returns an incorrect value, so the completion success status is determined by the exit code - //$"Статус успешности завершения: {remoteCommandExecuteResult.Succeesed}" + - $"Статус успешности завершения: {remoteCommandExecuteResult.ExitCode == 0}" + - $"\n======================\n"; - - if (!string.IsNullOrEmpty(remoteCommandExecuteResult.StandardError)) - messageWithResult += $"Ошибка: {remoteCommandExecuteResult.StandardError}" + - $"\n======================\n"; - - UpdateResultText(messageWithResult, true); + + UpdateResultText("", true); + UpdateResultExecutionTimeText(remoteCommandExecuteResult); } #endregion diff --git a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml index 4aae05b..3ccd3ff 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml @@ -378,21 +378,7 @@ - - - - - - - - - + From 3c8f17af35c55463e90421cc6d867a07fd7924f4 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 6 May 2024 08:52:20 +1000 Subject: [PATCH 155/181] Close #51 p6/7 --- .../ViewModels/ScratchControlViewModel.cs | 81 ++++++------------- 1 file changed, 26 insertions(+), 55 deletions(-) diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index b26093d..a48faa9 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -54,7 +54,6 @@ public class ScratchControlViewModel : RegionViewModelBase #region Const private const string cFilter = "XML documents (.xml) | *.xml"; - private const string cDebugColorScheme = "Red"; #endregion @@ -62,9 +61,6 @@ public class ScratchControlViewModel : RegionViewModelBase private bool mIsWarningStackOwerflowAlreadyShow; - //#8 p 6 - //private string mCurrentColorScheme; - #endregion #region ~ @@ -109,9 +105,6 @@ public override void OnNavigatedTo(NavigationContext navigationContext) { Subscribe(); - //#8 p 6 - //mCurrentColorScheme = ThemeManager.Current.DetectTheme(Application.Current).ColorScheme; - //#29 mWebViewProvider.ReloadWebView(); @@ -122,9 +115,6 @@ public override void OnNavigatedFrom(NavigationContext navigationContext) { Unsubscribe(); - //#8 p 6 - //ThemeManager.Current.ChangeThemeColorScheme(Application.Current, mCurrentColorScheme); - base.OnNavigatedFrom(navigationContext); } @@ -195,18 +185,7 @@ public string ResultText public ExtendedCommandExecuteResult ResultExecutionTime { get => resultExecutionTime; - set - { - bool isNewValue = SetProperty(ref resultExecutionTime, value); - - if (isNewValue) - { - /*fix*/ - ResultExecutionTime.Succeesed = ResultExecutionTime.ExitCode == 0; - } - } - - + set => SetProperty(ref resultExecutionTime, value); } private ExtendedCommandExecuteResult resultInitilizationTime; @@ -345,8 +324,7 @@ private async void ShowSaveFileDialog() string initialPath = Settings.Default.SavedUserWorkspaceFolderPath; string fileName = "workspace"; string defaultExt = ".xml"; - //string filter = "XML documents (.xml)|*.xml"; - + if (mDialogManager.ShowSaveFileDialog(dialogTitle, initialPath, fileName, defaultExt, cFilter)) { string path = mDialogManager.FilePathToSave; @@ -439,10 +417,8 @@ private bool CleanExecuteEditorCanExecute() private async void RunPythonCode() { - ExtendedCommandExecuteResult executeResult = new(); string source = SourceTextEditor; - bool isErrorHappened = false; - + try { var command = new WebApi.Client.v1.RequestModel.PythonCommandModel @@ -450,15 +426,16 @@ private async void RunPythonCode() Command = source }; - executeResult = await mWebApiService.PythonExecuteAsync(command); + ExtendedCommandExecuteResult executeResult = await mWebApiService.PythonExecuteAsync(command); + UpdateResultInitilizationTimeText(executeResult); } - catch (Exception ex) + catch { - isErrorHappened = true; + } finally { - UpdateResultInitilizationTimeText(executeResult); + } } @@ -483,11 +460,6 @@ private async void StopPythonCodeExecute() { } - - /*catch (Exception ex) - { - //ResultTextEditorError = ex.Message.ToString(); - }*/ } private bool StopPythonCodeExecuteCanExecute() @@ -509,11 +481,6 @@ private async void ToZeroPosition() { } - - /*catch (Exception ex) - { - //ResultTextEditorError = ex.Message.ToString(); - }*/ } private bool ToZeroPositionCanExecute() @@ -567,17 +534,30 @@ private void UpdateResultExecutionTimeText(ExtendedCommandExecuteResult executeR Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { - ResultExecutionTime = executeResult; + ExtendedCommandExecuteResult fixResult = new() + { + StandardOutput = executeResult.StandardOutput, + StandardError = executeResult.StandardError, + + StartTime = executeResult.StartTime, + EndTime = executeResult.EndTime, + RunTime = executeResult.RunTime, + + ExitCode = executeResult.ExitCode, + + // The server always returns False + // Therefore, the success of completion is determined by the exit code + Succeesed = executeResult.ExitCode == 0 + }; + + ResultExecutionTime = fixResult; IsPythonCodeExecute = false; })); } private void UpdateResultInitilizationTimeText(ExtendedCommandExecuteResult executeResult) { - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => - { - ResultInitilizationTime = executeResult; - })); + ResultInitilizationTime = executeResult; } private void ClearResultText() @@ -599,10 +579,6 @@ private void OnPythonCodeExecuteStatusChange(bool isPythonCodeExecute) mStatusBarNotificationDelivery.CompileLogMessage = "Сеанс отладки закончен"; mStatusBarNotificationDelivery.ProgressRingStart = false; - - //#8 p 6 - //ThemeManager.Current.ChangeThemeColorScheme(Application.Current, mCurrentColorScheme); - return; } @@ -610,11 +586,6 @@ private void OnPythonCodeExecuteStatusChange(bool isPythonCodeExecute) mStatusBarNotificationDelivery.CompileLogMessage = "Сеанс отладки запущен"; mStatusBarNotificationDelivery.ProgressRingStart = true; - //#8 p 6 - //ThemeManager.Current.ChangeThemeColorScheme(Application.Current, cDebugColorScheme); - - ClearResultText(); - if (!Settings.Default.ShadowWorkspaceInDebug) return; From 73fd0d43f855de24a832bb563e4e6e71215e996f Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 6 May 2024 10:11:08 +1000 Subject: [PATCH 156/181] Close #28 --- .../CommunicationProviderService.cs | 23 +++++++++++- .../ICommunicationProviderService.cs | 3 +- .../ViewModels/ScratchControlViewModel.cs | 6 ++-- .../ViewModels/NotificationViewModel.cs | 36 +++++++++++++------ .../ViewModels/StatusBarViewModel.cs | 6 ++-- 5 files changed, 57 insertions(+), 17 deletions(-) diff --git a/AdamController.Services/CommunicationProviderService.cs b/AdamController.Services/CommunicationProviderService.cs index b41004f..468f266 100644 --- a/AdamController.Services/CommunicationProviderService.cs +++ b/AdamController.Services/CommunicationProviderService.cs @@ -27,6 +27,12 @@ public class CommunicationProviderService : ICommunicationProviderService #endregion + #region var + + private bool mIsDisconnectByUserRequest = false; + + #endregion + #region ~ public CommunicationProviderService(ITcpClientService adamTcpClientService, IUdpClientService adamUdpClientService, @@ -60,6 +66,18 @@ public void ConnectAllAsync() public void DisconnectAllAsync() { + mIsDisconnectByUserRequest = false; + + _ = Task.Run(mTcpClientService.DisconnectAndStop); + _ = Task.Run(mUdpClientService.Stop); + _ = Task.Run(mUdpServerService.Stop); + _ = Task.Run(mWebSocketClientService.DisconnectAsync); + } + + public void DisconnectAllAsync(bool isUserRequest) + { + mIsDisconnectByUserRequest = isUserRequest; + _ = Task.Run(mTcpClientService.DisconnectAndStop); _ = Task.Run(mUdpClientService.Stop); _ = Task.Run(mUdpServerService.Stop); @@ -84,6 +102,7 @@ public void Dispose() #endregion + #region Private methods #endregion @@ -168,7 +187,9 @@ protected virtual void OnRaiseTcpServiceCientConnectedEvent() protected virtual void OnRaiseTcpServiceClientDisconnectEvent() { TcpServiceClientDisconnectEventHandler raiseEvent = RaiseTcpServiceClientDisconnectEvent; - raiseEvent?.Invoke(this); + raiseEvent?.Invoke(this, mIsDisconnectByUserRequest); + + mIsDisconnectByUserRequest = false; } public virtual void OnRaiseTcpServiceClientReconnectedEvent(int reconnectCounter) diff --git a/AdamController.Services/Interfaces/ICommunicationProviderService.cs b/AdamController.Services/Interfaces/ICommunicationProviderService.cs index 993ac75..b891f2a 100644 --- a/AdamController.Services/Interfaces/ICommunicationProviderService.cs +++ b/AdamController.Services/Interfaces/ICommunicationProviderService.cs @@ -6,7 +6,7 @@ namespace AdamController.Services.Interfaces #region Delegate public delegate void TcpServiceCientConnectedEventHandler(object sender); - public delegate void TcpServiceClientDisconnectEventHandler(object sender); + public delegate void TcpServiceClientDisconnectEventHandler(object sender, bool isUserRequest); public delegate void TcpServiceClientReconnectedEventHandler(object sender, int reconnectCounter); public delegate void UdpServiceServerReceivedEventHandler(object sender, string message); public delegate void UdpServiceClientMessageEnqueueEvent(object sender, ReceivedData data); @@ -37,6 +37,7 @@ public interface ICommunicationProviderService : IDisposable public void ConnectAllAsync(); public void DisconnectAllAsync(); + public void DisconnectAllAsync(bool isUserRequest); public void WebSocketSendTextMessage(string message); #endregion diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index a48faa9..1f58db2 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -230,7 +230,7 @@ public IHighlightingDefinition HighlightingDefinition private void Subscribe() { mCommunicationProvider.RaiseTcpServiceCientConnectedEvent += OnRaiseTcpServiceCientConnected; - mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent += OnRaiseTcperviceClientDisconnect; + mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent += OnRaiseTcpServiceClientDisconnect; mPythonRemoteRunner.RaisePythonScriptExecuteStartEvent += OnRaisePythonScriptExecuteStart; mPythonRemoteRunner.RaisePythonStandartOutputEvent += OnRaisePythonStandartOutput; @@ -243,7 +243,7 @@ private void Subscribe() private void Unsubscribe() { mCommunicationProvider.RaiseTcpServiceCientConnectedEvent -= OnRaiseTcpServiceCientConnected; - mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent -= OnRaiseTcperviceClientDisconnect; + mCommunicationProvider.RaiseTcpServiceClientDisconnectEvent -= OnRaiseTcpServiceClientDisconnect; mPythonRemoteRunner.RaisePythonScriptExecuteStartEvent -= OnRaisePythonScriptExecuteStart; mPythonRemoteRunner.RaisePythonStandartOutputEvent -= OnRaisePythonStandartOutput; @@ -656,7 +656,7 @@ private async void OnRaiseTcpServiceCientConnected(object sender) UpdatePythonInfo(pythonVersion, pythonBinPath, pythonWorkDir); } - private void OnRaiseTcperviceClientDisconnect(object sender) + private void OnRaiseTcpServiceClientDisconnect(object sender, bool isUserRequest) { IsTcpClientConnected = mCommunicationProvider.IsTcpClientConnected; diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index ee68fe9..7f4e1f7 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -35,6 +35,12 @@ public class NotificationViewModel : FlyoutBase #endregion + #region Var + + private bool mIsDisconnectByUserRequest = false; + + #endregion + #region ~ public NotificationViewModel(ICommunicationProviderService communicationProvider, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IFlyoutStateChecker flyoutState) @@ -57,9 +63,10 @@ protected override void OnChanging(bool isOpening) if (isOpening) { mFlyoutState.IsNotificationFlyoutOpened = true; + + Subscribe(); SetFlyoutParametrs(); - Subscribe(); UpdateStatusConnection(mCommunicationProvider.IsTcpClientConnected); return; @@ -149,24 +156,32 @@ private void SetFlyoutParametrs() /// /// true is connected, false disconetcted, null reconected /// - private void UpdateStatusConnection(bool? connectionStatus, int reconnectCounter = 0) + private void UpdateStatusConnection(bool? connectionStatus, bool isDisconnectByUserRequest = false, int reconnectCounter = 0) { if (connectionStatus == true) { + mIsDisconnectByUserRequest = false; ContentConnectButton = cConnectButtonStatusConnected; IconConnectButton = PackIconMaterialKind.Robot; } - if(connectionStatus == false) + if(connectionStatus == false && mIsDisconnectByUserRequest == false) { + IconConnectButton = PackIconMaterialKind.RobotDead; + ContentConnectButton = cConnectButtonStatusDisconnected; + + if (isDisconnectByUserRequest) + { + mIsDisconnectByUserRequest = true; + return; + } + + if (Settings.Default.IsMessageShowOnAbortMainConnection) { if (!IsOpen) FailConnectNotificationVisibility = Visibility.Visible; } - - ContentConnectButton = cConnectButtonStatusDisconnected; - IconConnectButton = PackIconMaterialKind.RobotDead; } if(connectionStatus == null) @@ -205,12 +220,12 @@ private void OnRaiseTcpServiceCientConnected(object sender) private void OnRaiseTcpServiceClientReconnected(object sender, int reconnectCounter) { - UpdateStatusConnection(null, reconnectCounter); + UpdateStatusConnection(null, reconnectCounter: reconnectCounter); } - private void OnRaiseTcpServiceClientDisconnect(object sender) + private void OnRaiseTcpServiceClientDisconnect(object sender, bool isUserRequest) { - UpdateStatusConnection(false); + UpdateStatusConnection(false, isDisconnectByUserRequest:isUserRequest); } #endregion @@ -223,7 +238,8 @@ private void ConnectButton() if (isConnected) { - mCommunicationProvider.DisconnectAllAsync(); + bool isUserRequest = true; + mCommunicationProvider.DisconnectAllAsync(isUserRequest); return; } diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index ed086a4..8b19881 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -201,11 +201,13 @@ private void RaiseTcpServiceClientReconnectedEvent(object sender, int reconnectC TextOnStatusConnectToolbar = $"{cTextOnStatusConnectToolbarReconnected} {reconnectCounter}"; } - private void RaiseAdamTcpClientDisconnectEvent(object sender) + private void RaiseAdamTcpClientDisconnectEvent(object sender, bool isUserRequest) { ConnectIcon = PackIconModernKind.Connect; TextOnStatusConnectToolbar = cTextOnStatusConnectToolbarDisconnected; - mStatusBarNotificationDelivery.NotificationCounter++; + + if(!isUserRequest) + mStatusBarNotificationDelivery.NotificationCounter++; } private void RaiseChangeProgressRingStateEvent(object sender, bool newState) From 75c42505e4e277dfec9ed054e32a23671fb79af2 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 6 May 2024 13:25:15 +1000 Subject: [PATCH 157/181] Close #50 p 3.1 --- .../AdamController.Core.csproj | 6 +++ .../DebuggerMessages.en.xaml | 16 ++++++ .../DebuggerMessages.ru.xaml | 16 ++++++ .../DictonaryCollection/HamburgerMenu.en.xaml | 1 - .../DictonaryCollection/HamburgerMenu.ru.xaml | 1 - .../DictonaryCollection/MainMenu.en.xaml | 1 - .../DictonaryCollection/MainMenu.ru.xaml | 1 - .../LocalizationDictionary/en.xaml | 1 + .../LocalizationDictionary/ru.xaml | 1 + AdamController.Services/CultureProvider.cs | 53 ++++++++++++++++--- .../Interfaces/ICultureProvider.cs | 13 +++++ .../ViewModels/ScratchControlViewModel.cs | 47 ++++++++++++---- .../ViewModels/NotificationViewModel.cs | 2 - .../ViewModels/StatusBarViewModel.cs | 1 - 14 files changed, 137 insertions(+), 23 deletions(-) create mode 100644 AdamController.Core/LocalizationDictionary/DictonaryCollection/DebuggerMessages.en.xaml create mode 100644 AdamController.Core/LocalizationDictionary/DictonaryCollection/DebuggerMessages.ru.xaml diff --git a/AdamController.Core/AdamController.Core.csproj b/AdamController.Core/AdamController.Core.csproj index cf90d94..d98fc40 100644 --- a/AdamController.Core/AdamController.Core.csproj +++ b/AdamController.Core/AdamController.Core.csproj @@ -57,6 +57,12 @@ + + MSBuild:Compile + + + MSBuild:Compile + MSBuild:Compile diff --git a/AdamController.Core/LocalizationDictionary/DictonaryCollection/DebuggerMessages.en.xaml b/AdamController.Core/LocalizationDictionary/DictonaryCollection/DebuggerMessages.en.xaml new file mode 100644 index 0000000..9162619 --- /dev/null +++ b/AdamController.Core/LocalizationDictionary/DictonaryCollection/DebuggerMessages.en.xaml @@ -0,0 +1,16 @@ + + + + The debugging session has started + The debugging session is over + + + The program has been completed + Further output of the result will be hidden. + The program continues to run interactively. + To stop the program, press "Stop" or wait for the completion. + + + \ No newline at end of file diff --git a/AdamController.Core/LocalizationDictionary/DictonaryCollection/DebuggerMessages.ru.xaml b/AdamController.Core/LocalizationDictionary/DictonaryCollection/DebuggerMessages.ru.xaml new file mode 100644 index 0000000..44f588e --- /dev/null +++ b/AdamController.Core/LocalizationDictionary/DictonaryCollection/DebuggerMessages.ru.xaml @@ -0,0 +1,16 @@ + + + + Сеанс отладки начат + Сеанс отладки закончен + + + Выполнение программы завершено + Дальнейший вывод результата, будет скрыт. + Программа продолжает выполняться в неинтерактивном режиме. + Для остановки нажмите "Stop" или дождитесь завершения. + + + \ No newline at end of file diff --git a/AdamController.Core/LocalizationDictionary/DictonaryCollection/HamburgerMenu.en.xaml b/AdamController.Core/LocalizationDictionary/DictonaryCollection/HamburgerMenu.en.xaml index 37d7b8f..2bcab40 100644 --- a/AdamController.Core/LocalizationDictionary/DictonaryCollection/HamburgerMenu.en.xaml +++ b/AdamController.Core/LocalizationDictionary/DictonaryCollection/HamburgerMenu.en.xaml @@ -4,7 +4,6 @@ Scratch editor - Script editor Computer vision Settings diff --git a/AdamController.Core/LocalizationDictionary/DictonaryCollection/HamburgerMenu.ru.xaml b/AdamController.Core/LocalizationDictionary/DictonaryCollection/HamburgerMenu.ru.xaml index 1c7f615..f782687 100644 --- a/AdamController.Core/LocalizationDictionary/DictonaryCollection/HamburgerMenu.ru.xaml +++ b/AdamController.Core/LocalizationDictionary/DictonaryCollection/HamburgerMenu.ru.xaml @@ -4,7 +4,6 @@ Скретч редактор - Редактор скриптов Компьютерное зрение Настройки diff --git a/AdamController.Core/LocalizationDictionary/DictonaryCollection/MainMenu.en.xaml b/AdamController.Core/LocalizationDictionary/DictonaryCollection/MainMenu.en.xaml index da74d18..6ea5913 100644 --- a/AdamController.Core/LocalizationDictionary/DictonaryCollection/MainMenu.en.xaml +++ b/AdamController.Core/LocalizationDictionary/DictonaryCollection/MainMenu.en.xaml @@ -11,7 +11,6 @@ Scratch editor - Script editor Computer vision Settings diff --git a/AdamController.Core/LocalizationDictionary/DictonaryCollection/MainMenu.ru.xaml b/AdamController.Core/LocalizationDictionary/DictonaryCollection/MainMenu.ru.xaml index c785660..de8fbfd 100644 --- a/AdamController.Core/LocalizationDictionary/DictonaryCollection/MainMenu.ru.xaml +++ b/AdamController.Core/LocalizationDictionary/DictonaryCollection/MainMenu.ru.xaml @@ -12,7 +12,6 @@ Скретч редактор - Редактор скриптов Компьютерное зрение Настройки diff --git a/AdamController.Core/LocalizationDictionary/en.xaml b/AdamController.Core/LocalizationDictionary/en.xaml index db1c088..22f3821 100644 --- a/AdamController.Core/LocalizationDictionary/en.xaml +++ b/AdamController.Core/LocalizationDictionary/en.xaml @@ -3,6 +3,7 @@ + \ No newline at end of file diff --git a/AdamController.Core/LocalizationDictionary/ru.xaml b/AdamController.Core/LocalizationDictionary/ru.xaml index 7979f17..16593b7 100644 --- a/AdamController.Core/LocalizationDictionary/ru.xaml +++ b/AdamController.Core/LocalizationDictionary/ru.xaml @@ -3,6 +3,7 @@ + \ No newline at end of file diff --git a/AdamController.Services/CultureProvider.cs b/AdamController.Services/CultureProvider.cs index aa23c0b..97586db 100644 --- a/AdamController.Services/CultureProvider.cs +++ b/AdamController.Services/CultureProvider.cs @@ -1,4 +1,5 @@ using AdamController.Services.Interfaces; +using Prism.Mvvm; using System; using System.Collections.Generic; using System.Globalization; @@ -8,8 +9,14 @@ namespace AdamController.Services { - public class CultureProvider : ICultureProvider + public class CultureProvider : BindableBase, ICultureProvider { + #region Events + + public event CurrentAppCultureLoadOrChangeEventHandler RaiseCurrentAppCultureLoadOrChangeEvent; + + #endregion + #region Const private const string cEnString = "en-EN"; @@ -17,6 +24,12 @@ public class CultureProvider : ICultureProvider #endregion + #region Var + + private readonly Application mCurrentApp = Application.Current; + + #endregion + #region ~ public CultureProvider() {} @@ -27,7 +40,19 @@ public CultureProvider() {} public List SupportAppCultures { get { return GetSupportAppCultures(); } } - public CultureInfo CurrentAppCulture { get; private set; } + private CultureInfo currentAppCulture; + public CultureInfo CurrentAppCulture + { + get => currentAppCulture; + private set + { + bool isNewValue = SetProperty(ref currentAppCulture, value); + + if (isNewValue) + OnRaiseCurrentAppCultureLoadOrChangeEvent(); + } + + } #endregion @@ -43,8 +68,8 @@ public void ChangeAppCulture(CultureInfo culture) }; RemoveLoadedDictonary(); - - Application.Current.Resources.MergedDictionaries.Add(resources); + + mCurrentApp.Resources.MergedDictionaries.Add(resources); UpdateCurrentCulture(culture); } @@ -54,6 +79,12 @@ public void Dispose() } + public string FindResource(string resource) + { + var @string = mCurrentApp.TryFindResource(resource) as string; + return @string; + } + #endregion #region Private method @@ -73,14 +104,14 @@ private void RemoveLoadedDictonary() foreach (var culture in supportedCultures) { string resourceName = $"pack://application:,,,/AdamController.Core;component/LocalizationDictionary/{culture.TwoLetterISOLanguageName}.xaml"; - currentResourceDictionary = Application.Current.Resources.MergedDictionaries.FirstOrDefault(x => x?.Source?.OriginalString == resourceName); + currentResourceDictionary = mCurrentApp.Resources.MergedDictionaries.FirstOrDefault(x => x?.Source?.OriginalString == resourceName); } if (currentResourceDictionary == null || currentResourceDictionary?.MergedDictionaries.Count == 0) return; foreach (ResourceDictionary dictionary in currentResourceDictionary.MergedDictionaries) - Application.Current.Resources.MergedDictionaries.Remove(dictionary); + mCurrentApp.Resources.MergedDictionaries.Remove(dictionary); } private static List GetSupportAppCultures() @@ -97,5 +128,15 @@ private static List GetSupportAppCultures() } #endregion + + #region OnRaise events + + protected virtual void OnRaiseCurrentAppCultureLoadOrChangeEvent() + { + CurrentAppCultureLoadOrChangeEventHandler raiseEvent = RaiseCurrentAppCultureLoadOrChangeEvent; + raiseEvent?.Invoke(this); + } + + #endregion } } diff --git a/AdamController.Services/Interfaces/ICultureProvider.cs b/AdamController.Services/Interfaces/ICultureProvider.cs index 0505c05..ef28e4e 100644 --- a/AdamController.Services/Interfaces/ICultureProvider.cs +++ b/AdamController.Services/Interfaces/ICultureProvider.cs @@ -4,8 +4,20 @@ namespace AdamController.Services.Interfaces { + #region Delegates + + public delegate void CurrentAppCultureLoadOrChangeEventHandler(object sender); + + #endregion + public interface ICultureProvider : IDisposable { + #region Events + + public event CurrentAppCultureLoadOrChangeEventHandler RaiseCurrentAppCultureLoadOrChangeEvent; + + #endregion + #region Public fields public List SupportAppCultures { get; } @@ -15,6 +27,7 @@ public interface ICultureProvider : IDisposable #region Public methods + public string FindResource(string resourcePath); public void ChangeAppCulture(CultureInfo culture); #endregion diff --git a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs index 1f58db2..313a900 100644 --- a/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs +++ b/Modules/AdamController.Modules.ContentRegion/ViewModels/ScratchControlViewModel.cs @@ -48,6 +48,7 @@ public class ScratchControlViewModel : RegionViewModelBase private readonly IFileManagmentService mFileManagment; private readonly IWebApiService mWebApiService; private readonly IControlHelper mControlHelper; + private readonly ICultureProvider mCultureProvider; #endregion @@ -61,14 +62,22 @@ public class ScratchControlViewModel : RegionViewModelBase private bool mIsWarningStackOwerflowAlreadyShow; + private string mCompileLogMessageStartDebug; + private string mCompileLogMessageEndDebug; + private string mFinishAppExecute; + private string mWarningStackOwerflow1; + private string mWarningStackOwerflow2; + private string mWarningStackOwerflow3; + #endregion #region ~ public ScratchControlViewModel(IRegionManager regionManager, ICommunicationProviderService communicationProvider, IPythonRemoteRunnerService pythonRemoteRunner, IStatusBarNotificationDeliveryService statusBarNotificationDelivery, IWebViewProvider webViewProvider, IDialogManagerService dialogManager, - IFileManagmentService fileManagment, IWebApiService webApiService, IAvalonEditService avalonEditService, IControlHelper controlHelper) : base(regionManager) + IFileManagmentService fileManagment, IWebApiService webApiService, IAvalonEditService avalonEditService, IControlHelper controlHelper, ICultureProvider cultureProvider) : base(regionManager) { + mCommunicationProvider = communicationProvider; mPythonRemoteRunner = pythonRemoteRunner; mStatusBarNotificationDelivery = statusBarNotificationDelivery; @@ -77,6 +86,7 @@ public ScratchControlViewModel(IRegionManager regionManager, ICommunicationProvi mFileManagment = fileManagment; mWebApiService = webApiService; mControlHelper = controlHelper; + mCultureProvider = cultureProvider; CopyToClipboardDelegateCommand = new DelegateCommand(CopyToClipboard, CopyToClipboardCanExecute); MoveSplitterDelegateCommand = new DelegateCommand(MoveSplitter, MoveSplitterCanExecute); @@ -90,6 +100,8 @@ public ScratchControlViewModel(IRegionManager regionManager, ICommunicationProvi ToZeroPositionDelegateCommand = new DelegateCommand(ToZeroPosition, ToZeroPositionCanExecute); HighlightingDefinition = avalonEditService.GetDefinition(HighlightingName.AdamPython); + + LoadResources(); } #endregion @@ -238,6 +250,8 @@ private void Subscribe() mWebViewProvider.RaiseWebViewMessageReceivedEvent += RaiseWebViewbMessageReceivedEvent; mWebViewProvider.RaiseWebViewNavigationCompleteEvent += RaiseWebViewNavigationCompleteEvent; + + mCultureProvider.RaiseCurrentAppCultureLoadOrChangeEvent += RaiseCurrentAppCultureLoadOrChangeEvent; } private void Unsubscribe() @@ -252,6 +266,7 @@ private void Unsubscribe() mWebViewProvider.RaiseWebViewMessageReceivedEvent -= RaiseWebViewbMessageReceivedEvent; mWebViewProvider.RaiseWebViewNavigationCompleteEvent -= RaiseWebViewNavigationCompleteEvent; + mCultureProvider.RaiseCurrentAppCultureLoadOrChangeEvent += RaiseCurrentAppCultureLoadOrChangeEvent; } #endregion @@ -502,7 +517,8 @@ private void UpdateResultText(string text, bool isFinishMessage = false) { if (isFinishMessage) { - ResultText += "\n======================\n<<Выполнение программы завершено>>"; + ResultText += "\n======================\n"; + ResultText += $"<<{mFinishAppExecute}>>\n"; } if(!isFinishMessage) @@ -511,13 +527,8 @@ private void UpdateResultText(string text, bool isFinishMessage = false) { if (!mIsWarningStackOwerflowAlreadyShow) { - string warningMessage = "\nДальнейший вывод результата, будет скрыт."; - warningMessage += "\nПрограмма продолжает выполняться в неинтерактивном режиме."; - warningMessage += "\nДля остановки нажмите \"Stop\". Или дождитесь завершения."; - warningMessage += "\n"; - + string warningMessage = $"\n{mWarningStackOwerflow1}\n{mWarningStackOwerflow2}\n{mWarningStackOwerflow3}\n"; ResultText += warningMessage; - mIsWarningStackOwerflowAlreadyShow = true; } @@ -577,13 +588,13 @@ private void OnPythonCodeExecuteStatusChange(bool isPythonCodeExecute) await mWebViewProvider.ExecuteJavaScript(Scripts.ShadowDisable); })); - mStatusBarNotificationDelivery.CompileLogMessage = "Сеанс отладки закончен"; + mStatusBarNotificationDelivery.CompileLogMessage = mCompileLogMessageEndDebug; mStatusBarNotificationDelivery.ProgressRingStart = false; return; } mIsWarningStackOwerflowAlreadyShow = false; - mStatusBarNotificationDelivery.CompileLogMessage = "Сеанс отладки запущен"; + mStatusBarNotificationDelivery.CompileLogMessage = mCompileLogMessageStartDebug; mStatusBarNotificationDelivery.ProgressRingStart = true; @@ -624,6 +635,17 @@ private void RaiseDelegateCommandsCanExecuteChanged() ToZeroPositionDelegateCommand.RaiseCanExecuteChanged(); } + private void LoadResources() + { + mCompileLogMessageStartDebug = mCultureProvider.FindResource("DebuggerMessages.CompileLogMessageStartDebug"); + mCompileLogMessageEndDebug = mCultureProvider.FindResource("DebuggerMessages.CompileLogMessageEndDebug"); + mFinishAppExecute = mCultureProvider.FindResource("DebuggerMessages.ResultMessages.FinishAppExecute"); + + mWarningStackOwerflow1 = mCultureProvider.FindResource("DebuggerMessages.ResultMessages.WarningStackOwerflow1"); + mWarningStackOwerflow2 = mCultureProvider.FindResource("DebuggerMessages.ResultMessages.WarningStackOwerflow2"); + mWarningStackOwerflow3 = mCultureProvider.FindResource("DebuggerMessages.ResultMessages.WarningStackOwerflow3"); + } + #endregion #region Event methods @@ -682,6 +704,11 @@ private void OnRaisePythonScriptExecuteFinish(object sender, ExtendedCommandExec UpdateResultExecutionTimeText(remoteCommandExecuteResult); } + private void RaiseCurrentAppCultureLoadOrChangeEvent(object sender) + { + LoadResources(); + } + #endregion #region Initialize Blockly diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs index 7f4e1f7..7888573 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/NotificationViewModel.cs @@ -4,7 +4,6 @@ using AdamController.Services.Interfaces; using MahApps.Metro.IconPacks; using Prism.Commands; -using System.ComponentModel; using System.Windows; namespace AdamController.Modules.FlayoutsRegion.ViewModels @@ -176,7 +175,6 @@ private void UpdateStatusConnection(bool? connectionStatus, bool isDisconnectByU return; } - if (Settings.Default.IsMessageShowOnAbortMainConnection) { if (!IsOpen) diff --git a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs index 8b19881..f4eb311 100644 --- a/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs +++ b/Modules/AdamController.Modules.StatusBar/ViewModels/StatusBarViewModel.cs @@ -6,7 +6,6 @@ using MahApps.Metro.IconPacks; using Prism.Commands; using Prism.Regions; -using Prism.Services.Dialogs; using System; namespace AdamController.Modules.StatusBarRegion.ViewModels From 03953535b5407cb56194478f528185f6f11851ef Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Mon, 6 May 2024 16:16:18 +1000 Subject: [PATCH 158/181] Close #50 p.4 --- .../SettingsControlView.en.xaml | 58 +++++++++++++ .../SettingsControlView.ru.xaml | 58 +++++++++++++ .../LocalizationDictionary/en.xaml | 1 + .../LocalizationDictionary/ru.xaml | 1 + .../Views/VisualSettingsControlView.xaml | 82 +++++++++---------- 5 files changed, 159 insertions(+), 41 deletions(-) create mode 100644 AdamController.Core/LocalizationDictionary/DictonaryCollection/SettingsControlView.en.xaml create mode 100644 AdamController.Core/LocalizationDictionary/DictonaryCollection/SettingsControlView.ru.xaml diff --git a/AdamController.Core/LocalizationDictionary/DictonaryCollection/SettingsControlView.en.xaml b/AdamController.Core/LocalizationDictionary/DictonaryCollection/SettingsControlView.en.xaml new file mode 100644 index 0000000..4f05669 --- /dev/null +++ b/AdamController.Core/LocalizationDictionary/DictonaryCollection/SettingsControlView.en.xaml @@ -0,0 +1,58 @@ + + + + Language and theme + Scratch editor settings + Connection and notification settings + Environment settings + + + App theme + App language + Displayed sets of blocks + + + Logical + Colors + Lists + Loops + Mathematical + Procedures + Text + Variables + Blocks Adam v.2.6 + Blocks Adam v.2.7 + + + Connect at startup + Notify robot disconnection + Create user folders + + + The size of the grid cell + + + Custom + + + By default + + + Show grid + Show the trash can + Align blocks + Load latest + Do not show the browser menu + Shadow on debug + + + Robot IP + + + WebApi settings + Port settings + Configuring user folders + + \ No newline at end of file diff --git a/AdamController.Core/LocalizationDictionary/DictonaryCollection/SettingsControlView.ru.xaml b/AdamController.Core/LocalizationDictionary/DictonaryCollection/SettingsControlView.ru.xaml new file mode 100644 index 0000000..05e709d --- /dev/null +++ b/AdamController.Core/LocalizationDictionary/DictonaryCollection/SettingsControlView.ru.xaml @@ -0,0 +1,58 @@ + + + + Язык и тема + Настройки скретч редактора + Настройки подключений и уведомлений + Настройки окружения + + + Тема приложения + Язык приложения + Отображаемые наборы блоков + + + Логические + Цвета + Списки + Циклы + Математические + Процедуры + Текстовые + Переменные + Блоки Adam v.2.6 + Блоки Adam v.2.7 + + + Подключаться при запуске + Уведомлять об отключении от робота + Создавать папки пользователя + + + Размер ячейки сетки + + + Пользовательский + + + По умолчанию + + + Показывать сетку + Показывать корзину + Выравнивать блоки + Загружать последние + Не показывать меню браузера + Затемнять при отладке + + + Адрес робота + + + Настройки WebApi + Настройки портов + Настройка папок пользователя + + \ No newline at end of file diff --git a/AdamController.Core/LocalizationDictionary/en.xaml b/AdamController.Core/LocalizationDictionary/en.xaml index 22f3821..d44841a 100644 --- a/AdamController.Core/LocalizationDictionary/en.xaml +++ b/AdamController.Core/LocalizationDictionary/en.xaml @@ -4,6 +4,7 @@ + \ No newline at end of file diff --git a/AdamController.Core/LocalizationDictionary/ru.xaml b/AdamController.Core/LocalizationDictionary/ru.xaml index 16593b7..9a744d2 100644 --- a/AdamController.Core/LocalizationDictionary/ru.xaml +++ b/AdamController.Core/LocalizationDictionary/ru.xaml @@ -4,6 +4,7 @@ + \ No newline at end of file diff --git a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml index 3ccd3ff..d56a87e 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml @@ -3,6 +3,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks" + xmlns:core="clr-namespace:AdamController.Core;assembly=AdamController.Core" xmlns:properties="clr-namespace:AdamController.Core.Properties;assembly=AdamController.Core" xmlns:converters="clr-namespace:AdamController.Core.Converters;assembly=AdamController.Core" xmlns:prism="http://prismlibrary.com/" @@ -67,11 +68,11 @@ + Header="{ DynamicResource SettingsControlView.GroupBox.Header.LanguageAndTheme }"> - - @@ -187,7 +188,7 @@ - + @@ -199,7 +200,7 @@ - + @@ -210,10 +211,10 @@ IsChecked="{Binding BlocklySnapToGridNodes, Mode=TwoWay, Source={x:Static properties:Settings.Default}}"> - - - + + + @@ -223,10 +224,10 @@ IsChecked="{Binding BlocklyRestoreBlockOnLoad, Mode=TwoWay, Source={x:Static properties:Settings.Default}}"> - - - + + + @@ -237,8 +238,8 @@ - - + + @@ -250,8 +251,8 @@ - - + + @@ -267,9 +268,9 @@ @@ -305,7 +306,7 @@ + Header="{DynamicResource SettingsControlView.GroupBox.Header.ConnectionAndNotificationSettings}"> @@ -314,7 +315,7 @@ Orientation="Horizontal"> From bf454e44ba377c5b52bf6211cd6d41342bb4f985 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Tue, 7 May 2024 08:59:41 +1000 Subject: [PATCH 161/181] Close #54 p2 --- .../Views/ComputerVisionControlView.xaml | 18 +- .../Views/VisualSettingsControlView.xaml | 339 +++++++++--------- 2 files changed, 180 insertions(+), 177 deletions(-) diff --git a/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml index 101dec7..f2039b2 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/ComputerVisionControlView.xaml @@ -3,7 +3,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" - xmlns:intr="http://schemas.microsoft.com/xaml/behaviors" + xmlns:behaviors="http://schemas.microsoft.com/xaml/behaviors" xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks" xmlns:i="http://schemas.microsoft.com/xaml/behaviors" @@ -11,15 +11,15 @@ xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True"> - - - - + + + + - - - - + + + + diff --git a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml index d56a87e..f829b66 100644 --- a/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml +++ b/Modules/AdamController.Modules.ContentRegion/Views/VisualSettingsControlView.xaml @@ -55,218 +55,220 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + + - + - - - - - - - - - - - + + + + + + + + + + + + + + - - - - - + + + + + + + + + + - - - - + - - - - - - - + - - - + + + + - - + - - + + - - - - + + + - + - - + + - - - + - + + - + - - - - - - + + - + + + + - + - - - - - + + - + + + - + - - - - - + + + + - - + - - - - - - - - + + + + + + - + - + + - - - - - - - - - - - - - - - - - - + + + + + + + + + - + + + + + + + - + - + + - + - - - + - @@ -87,8 +87,9 @@ HorizontalAlignment="Right" FontWeight="Bold"> - - Очистить уведомления + + From cc38a14e27b9573286c46094332f9b36294d9f95 Mon Sep 17 00:00:00 2001 From: Alexey Nesterov Date: Tue, 7 May 2024 11:35:11 +1000 Subject: [PATCH 164/181] Close #50 p 1.3 --- .../Flyout/PortSettingsView.en.xaml | 13 +++++++++++ .../Flyout/PortSettingsView.ru.xaml | 13 +++++++++++ .../LocalizationDictionary/en.xaml | 1 + .../LocalizationDictionary/ru.xaml | 1 + .../ViewModels/PortSettingsViewModel.cs | 23 ++++++++++++++++--- .../Views/PortSettingsView.xaml | 10 ++++---- 6 files changed, 53 insertions(+), 8 deletions(-) create mode 100644 AdamController.Core/LocalizationDictionary/DictonaryCollection/Flyout/PortSettingsView.en.xaml create mode 100644 AdamController.Core/LocalizationDictionary/DictonaryCollection/Flyout/PortSettingsView.ru.xaml diff --git a/AdamController.Core/LocalizationDictionary/DictonaryCollection/Flyout/PortSettingsView.en.xaml b/AdamController.Core/LocalizationDictionary/DictonaryCollection/Flyout/PortSettingsView.en.xaml new file mode 100644 index 0000000..7adf1fb --- /dev/null +++ b/AdamController.Core/LocalizationDictionary/DictonaryCollection/Flyout/PortSettingsView.en.xaml @@ -0,0 +1,13 @@ + + + Video stream + Server socket port + Debugger port + Log server port + Connection control port + + Port settings + + \ No newline at end of file diff --git a/AdamController.Core/LocalizationDictionary/DictonaryCollection/Flyout/PortSettingsView.ru.xaml b/AdamController.Core/LocalizationDictionary/DictonaryCollection/Flyout/PortSettingsView.ru.xaml new file mode 100644 index 0000000..dca8e4e --- /dev/null +++ b/AdamController.Core/LocalizationDictionary/DictonaryCollection/Flyout/PortSettingsView.ru.xaml @@ -0,0 +1,13 @@ + + + Видео стрим + Порт сокет сервера + Порт отладчика + Порт сервера логов + Порт контроля подключения + + Настройки портов + + \ No newline at end of file diff --git a/AdamController.Core/LocalizationDictionary/en.xaml b/AdamController.Core/LocalizationDictionary/en.xaml index 2cf0310..0126995 100644 --- a/AdamController.Core/LocalizationDictionary/en.xaml +++ b/AdamController.Core/LocalizationDictionary/en.xaml @@ -9,6 +9,7 @@ + \ No newline at end of file diff --git a/AdamController.Core/LocalizationDictionary/ru.xaml b/AdamController.Core/LocalizationDictionary/ru.xaml index 503e1ad..9add0db 100644 --- a/AdamController.Core/LocalizationDictionary/ru.xaml +++ b/AdamController.Core/LocalizationDictionary/ru.xaml @@ -9,6 +9,7 @@ + \ No newline at end of file diff --git a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/PortSettingsViewModel.cs b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/PortSettingsViewModel.cs index 5128581..3827ff0 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/PortSettingsViewModel.cs +++ b/Modules/AdamController.Modules.FlayoutsRegion/ViewModels/PortSettingsViewModel.cs @@ -1,13 +1,30 @@ using AdamController.Controls.CustomControls.Mvvm.FlyoutContainer; +using AdamController.Services.Interfaces; namespace AdamController.Modules.FlayoutsRegion.ViewModels { public class PortSettingsViewModel : FlyoutBase { - public PortSettingsViewModel() + + #region Services + + private readonly ICultureProvider mCultureProvider; + + #endregion + + public PortSettingsViewModel(ICultureProvider cultureProvider) + { + BorderThickness = 1; + mCultureProvider = cultureProvider; + } + + protected override void OnChanging(bool isOpening) { - BorderThickness = 0; - Header = "Настройки портов"; + if (isOpening) + { + Header = mCultureProvider.FindResource("PortSettingsView.ViewModel.Flyout.Header"); + return; + } } } } diff --git a/Modules/AdamController.Modules.FlayoutsRegion/Views/PortSettingsView.xaml b/Modules/AdamController.Modules.FlayoutsRegion/Views/PortSettingsView.xaml index 28fe325..d364626 100644 --- a/Modules/AdamController.Modules.FlayoutsRegion/Views/PortSettingsView.xaml +++ b/Modules/AdamController.Modules.FlayoutsRegion/Views/PortSettingsView.xaml @@ -17,7 +17,7 @@