aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Console/ConsoleControlVM.cs
blob: 2f7b1f7309c05fe49048f4e692bd5bf0a0704eec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core.Commands;
using Tango.SharedUI;

namespace Tango.Console
{
    /// <summary>
    /// Represents a command prompt console control view model.
    /// </summary>
    /// <seealso cref="Tango.SharedUI.ViewModel" />
    public class ConsoleControlVM : ViewModel
    {
        private int _historyIndex;
        private List<ConsoleSuggestion> _knownSuggestions;

        /// <summary>
        /// Occurs when a command is executing.
        /// </summary>
        public event EventHandler<ConsoleCommandExecutingEventArgs> CommandExecuting;

        /// <summary>
        /// Gets the commands history.
        /// </summary>
        public ObservableCollection<ConsoleCommand> Commands { get; private set; }

        private ConsoleCommand _currentCommand;
        /// <summary>
        /// Gets or sets the current command.
        /// </summary>
        public ConsoleCommand CurrentCommand
        {
            get { return _currentCommand; }
            set { _currentCommand = value; RaisePropertyChangedAuto(); }
        }

        private List<ConsoleSuggestion> _suggestions;
        /// <summary>
        /// Gets or sets the available auto complete suggestions.
        /// </summary>
        public List<ConsoleSuggestion> Suggestions
        {
            get { return _suggestions; }
            set { _suggestions = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Executes the current command.
        /// </summary>
        public RelayCommand ExecuteCommand { get; set; }

        /// <summary>
        /// Navigates down through the commands history.
        /// </summary>
        public RelayCommand HistoryDownCommand { get; set; }

        /// <summary>
        /// Navigates up through the commands history.
        /// </summary>
        public RelayCommand HistoryUpCommand { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ConsoleControlVM"/> class.
        /// </summary>
        public ConsoleControlVM()
        {
            Commands = new ObservableCollection<ConsoleCommand>();
            CurrentCommand = new ConsoleCommand()
            {
                WorkingFolder = Environment.CurrentDirectory
            };

            ExecuteCommand = new RelayCommand(Execute);

            HistoryDownCommand = new RelayCommand(HistoryDown);
            HistoryUpCommand = new RelayCommand(HistoryUp);

            _knownSuggestions = new List<ConsoleSuggestion>(ConsoleDictionary.GetKnownCommands().Select(x => new ConsoleSuggestion()
            {
                Type = ConsoleSuggestionType.Command,
                Name = x.Name,
                Description = x.Description
            }));

            Suggestions = new List<ConsoleSuggestion>(_knownSuggestions);
        }

        private void HistoryUp()
        {
            if (_historyIndex > 0)
            {
                _historyIndex--;
                CreateNew(CurrentCommand.WorkingFolder, false, GetDistinctCommands()[_historyIndex].CommandText, true);
            }
        }

        private void HistoryDown()
        {
            if (_historyIndex < GetDistinctCommands().Count - 1)
            {
                _historyIndex++;
                CreateNew(CurrentCommand.WorkingFolder, false, GetDistinctCommands()[_historyIndex].CommandText, true);
            }
        }

        private void Execute()
        {
            if (CurrentCommand != null)
            {
                if (!CurrentCommand.CommandText.IsNotNullOrEmpty())
                {
                    CreateNew(CurrentCommand.WorkingFolder, true);
                    return;
                }

                if (CurrentCommand.CommandText.ToLower() == "clear")
                {
                    Clear();
                    return;
                }

                CurrentCommand.IsExecuting = true;

                ConsoleCommandExecutingEventArgs args = new ConsoleCommandExecutingEventArgs(CurrentCommand, (result) =>
                {
                    CurrentCommand.IsExecuting = false;
                    CurrentCommand.Output = result.Output;

                    CreateNew(result.WorkingFolder, true);

                    AppendSuggestions(result.Suggestions);
                });

                CommandExecuting?.Invoke(this, args);
            }
        }

        /// <summary>
        /// Concatenates the specified suggestions to the current suggestions.
        /// </summary>
        /// <param name="suggestions">The suggestions.</param>
        public void AppendSuggestions(List<ConsoleSuggestion> suggestions)
        {
            Suggestions = _knownSuggestions.Concat(suggestions).OrderBy(x => x.Name).ToList();
        }

        /// <summary>
        /// Clears the console.
        /// </summary>
        public void Clear()
        {
            Commands.Clear();
            CreateNew(CurrentCommand.WorkingFolder, false);
        }

        /// <summary>
        /// Clears and creates a new current command with the specified working folder.
        /// </summary>
        /// <param name="workingFolder">The working folder.</param>
        public void Clear(String workingFolder)
        {
            Commands.Clear();
            CreateNew(workingFolder, false);
        }

        private void CreateNew(String workingFolder, bool pushCurrent, String commandText = null, bool fromHistory = false)
        {
            if (pushCurrent)
            {
                Commands.Add(CurrentCommand);
                _historyIndex = GetDistinctCommands().Count;
            }

            CurrentCommand = new ConsoleCommand()
            {
                WorkingFolder = workingFolder != null ? workingFolder : CurrentCommand.WorkingFolder,
                CommandText = commandText,
                IsFromHistory = fromHistory
            };
        }

        private List<ConsoleCommand> GetDistinctCommands()
        {
            return Commands.Where(x => !x.IsFromHistory).ToList();
        }
    }
}
lass="n">dispatcherProvider, IEventLogger eventLogger, IPPCModuleLoader moduleLoader, INotificationProvider notificationProvider) { _notificationProvider = notificationProvider; _machineProvider = machineProvider; _dispatcher = dispatcherProvider; _eventLogger = eventLogger; _moduleLoader = moduleLoader; if (!DesignMode) { _notifiedViewModels = new List<PPCViewModel>(); MainWindow.Instance.ContentRendered += (_, __) => { OnMainWindowContentRendered(); }; } } /// <summary> /// Called when the main window content has been rendered /// </summary> private void OnMainWindowContentRendered() { LogManager.Log("Main window content rendered."); ContentRendered?.Invoke(this, new EventArgs()); StartApplication(); } private async void StartApplication() { PPCSettings settings = null; bool initialized = false; bool isAfterSetup = false; await Task.Factory.StartNew(() => { try { LogManager.Log("Reading PPC settings..."); settings = SettingsManager.Default.GetOrCreate<PPCSettings>(); LogManager.Log(settings.ToJsonString()); //Start watchdog _watchdogServer = new WatchDogServer(Application.Current.Dispatcher); #if !DEBUG if (settings.EnableWatchDog) { _watchdogServer.Start(); } #endif LogManager.Log("Reading Core settings..."); var coreSettings = SettingsManager.Default.GetOrCreate<CoreSettings>(); if (!SettingsManager.Default.IsFileExists()) { LogManager.Log("Settings file does not exists. creating..."); settings.Save(); } if (App.StartupArgs.Contains("-update_ok")) { LogManager.Log("Application started with '-update_ok' startup arguments. The application has been successfully updated."); if (settings.ApplicationState == ApplicationStates.PreSetup) { isAfterSetup = true; LogManager.Log("System restart is required."); } settings.ApplicationState = ApplicationStates.Ready; settings.Save(); if (isAfterSetup) { SystemRestartRequired?.Invoke(this, new EventArgs()); return; } } if (settings.ApplicationState == ApplicationStates.Ready) { LogManager.Log("Initializing ObservablesStaticCollections..."); ObservablesStaticCollections.Instance.Initialize(); LogManager.Log("Loading machine from database..."); _machineContext = ObservablesContext.CreateDefault(); _machine = new MachineBuilder(_machineContext).SetFirst().WithSettings().WithOrganization().WithConfiguration().WithSpools().WithCats().Build(); } initialized = true; } catch (Exception ex) { LogManager.Log(ex, "Application Initialization Error!"); ApplicationInitializationError?.Invoke(this, ex); return; } }); if (initialized) { try { if (settings.ApplicationState == ApplicationStates.PreSetup) { LogManager.Log($"The application is in {settings.ApplicationState} state. database initialization skipped. Invoking setup required event!"); SetupRequired?.Invoke(this, new EventArgs()); } else { PostDbInitialize(); } } catch (Exception ex) { LogManager.Log(ex, "Application Post Initialization Error!"); ApplicationInitializationError?.Invoke(this, ex); return; } } } /// <summary> /// Called when the database has been initialized /// </summary> private void PostDbInitialize() { LogManager.Log($"Raising {nameof(ApplicationStarted)} event..."); _eventLogger.Log(EventTypes.APPLICATION_STARTED, "Application Started!"); ApplicationStarted?.Invoke(this, new EventArgs()); LogManager.Log("Invoking PPC view models OnApplicationStarted methods..."); foreach (var vm in TangoIOC.Default.GetAllInstancesByBase<PPCViewModel>()) { if (!_notifiedViewModels.Contains(vm)) { LogManager.Log($"Invoking {vm.GetType().Name}.OnApplicationStarted..."); vm.OnApplicationStarted(); _notifiedViewModels.Add(vm); } } LogManager.Log("Waiting for IPPCModuleLoader instance injection..."); TangoIOC.Default.GetInstanceWhenAvailable<IPPCModuleLoader>((loader) => { LogManager.Log("Module loader instance has been registered. Registering for the ModulesLoaded event..."); loader.ModulesLoaded += (x, y) => { LogManager.Log("Loading modules views"); _dispatcher.InvokeBlock(() => { foreach (var module in TangoIOC.Default.GetInstance<IPPCModuleLoader>().UserModules) { if (!Views.LayoutView.Instance.NavigationControl.Elements.ToList().Exists(m => m.GetType() == module.MainViewType)) { LogManager.Log("Loading module view " + module.Name + "..."); FrameworkElement view = Activator.CreateInstance(module.MainViewType) as FrameworkElement; SharedUI.Controls.NavigationControl.SetNavigationName(view, module.Name); Views.LayoutView.Instance.NavigationControl.Elements.Add(view); } } }); LogManager.Log($"{loader.UserModules.Count} modules loaded."); LogManager.Log($"Invoking {nameof(ModulesInitialized)} event."); ModulesInitialized?.Invoke(this, new EventArgs()); FinalizeModuleInitialization(); }; }); } /// <summary> /// Finalizes the module initialization. /// </summary> private void FinalizeModuleInitialization() { var settings = SettingsManager.Default.GetOrCreate<PPCSettings>(); LogManager.Log("Finalizing application initialization..."); LogManager.Log("Initializing Machine Provider..."); _machineProvider.Init(_machine, _machineContext); LogManager.Log("Applications initialization completed!"); LogManager.Log("Checking for un-notified PPC view models..."); foreach (var vm in TangoIOC.Default.GetAllInstancesByBase<PPCViewModel>()) { if (!_notifiedViewModels.Contains(vm)) { LogManager.Log($"Invoking {vm.GetType().Name}.OnApplicationStarted..."); vm.OnApplicationStarted(); _notifiedViewModels.Add(vm); } } _dispatcher.Invoke(() => { LogManager.Log($"Invoking {nameof(ApplicationReady)} event."); ApplicationReady?.Invoke(this, new EventArgs()); LogManager.Log("Notifying view models about application ready..."); foreach (var vm in TangoIOC.Default.GetAllInstancesByBase<PPCViewModel>()) { LogManager.Log($"Invoking {vm.GetType().Name}.OnApplicationReady..."); vm.OnApplicationReady(); } if (settings.EnableTechnicianModeByDefault) { EnterTechnicianMode(false); } if (settings.EnableLockScreen) { _screenLockTimer = new ActionTimer(settings.LockScreenTimeout); _screenLockTimer.ResetReplace(ScreenLockTimerAction); } TangoMessenger.Default.Register<MachineSettingsSavedMessage>((msg) => { if (_screenLockTimer != null) { _screenLockTimer.Dispose(); _screenLockTimer = null; } if (settings.EnableLockScreen) { _screenLockTimer = new ActionTimer(settings.LockScreenTimeout); _screenLockTimer.ResetReplace(ScreenLockTimerAction); } }); }); } /// <summary> /// Shutdown the application. /// </summary> public void ShutDown() { if (IsShuttingDown) return; IsShuttingDown = true; try { LogManager.Log("Shutting down application..."); _watchdogServer.Dispose(); foreach (var vm in TangoIOC.Default.GetAllInstancesByBase<PPCViewModel>()) { vm.OnApplicationShuttingDown(); } } catch { } Environment.Exit(0); } /// <summary> /// Restarts the application. /// </summary> public void Restart() { if (IsShuttingDown) return; IsShuttingDown = true; try { LogManager.Log("Restarting the application..."); _watchdogServer.Dispose(); foreach (var vm in TangoIOC.Default.GetAllInstancesByBase<PPCViewModel>()) { vm.OnApplicationShuttingDown(); } } catch { } try { if (_machineProvider.MachineOperator.State == Transport.TransportComponentState.Connected) { _machineProvider.MachineOperator.Adapter.Disconnect().Wait(); } } catch { } Process.Start(Application.ResourceAssembly.Location); Environment.Exit(0); } /// <summary> /// Runs the updater utility and exits the application. /// </summary> public void UpdateApplication(String updaterPath, String arguments) { if (IsShuttingDown) return; IsShuttingDown = true; try { _watchdogServer.Dispose(); foreach (var vm in TangoIOC.Default.GetAllInstancesByBase<PPCViewModel>()) { vm.OnApplicationShuttingDown(); } } catch { } LogManager.Log($"Executing '{updaterPath}' with arguments '{arguments}'..."); Process.Start(updaterPath, arguments); LogManager.Log("Terminating application..."); Environment.Exit(0); } /// <summary> /// Enteres the application technician mode. /// </summary> public async void EnterTechnicianMode(bool displayNotification = true) { if (displayNotification) { var vm = await _notificationProvider.ShowDialog<TechnicianModeLoginViewVM>(); if (vm.DialogResult) { if (vm.Password == "Aa123456") { IsInTechnicianMode = true; _moduleLoader.AllModules.ToList().ForEach(x => x.OnTechnicianEntered()); await _notificationProvider.ShowInfo("Technician mode is now enabled."); } else { await _notificationProvider.ShowError("Invalid technician mode password."); EnterTechnicianMode(); } } } else { IsInTechnicianMode = true; _moduleLoader.AllModules.ToList().ForEach(x => x.OnTechnicianEntered()); } } /// <summary> /// Exits the application technician mode. /// </summary> public void ExitTechnicianMode() { IsInTechnicianMode = false; _moduleLoader.AllModules.ToList().ForEach(x => x.OnTechnicianExited()); _notificationProvider.ShowInfo("Technician mode is now disabled."); } /// <summary> /// Invokes a dialog for entering a password and releasing the screen lock. /// </summary> public async void ReleaseScreenLock() { if (IsScreenLocked) { var vm = await _notificationProvider.ShowDialog<ScreenLockViewVM>(); if (vm.DialogResult) { if (vm.Password == SettingsManager.Default.GetOrCreate<PPCSettings>().LockScreenPassword) { IsScreenLocked = false; ResetScreenLockTimer(); } } } } public void ResetScreenLockTimer() { if (_screenLockTimer != null) { _screenLockTimer.ResetReplace(ScreenLockTimerAction); } } private void ScreenLockTimerAction() { IsScreenLocked = true; } } }