aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.Stubs/ViewModels/MainViewVM.cs
blob: d7e6417353851764afdf60af497e19dfed395886 (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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Tango.Core.Commands;
using Tango.MachineStudio.Common.Notifications;
using Tango.MachineStudio.Common.StudioApplication;
using Tango.Scripting;
using Tango.Settings;
using Tango.SharedUI;
using Tango.Stubs;
using Tango.Transport;
using Tango.Transport.Adapters;

namespace Tango.MachineStudio.Stubs.ViewModels
{
    /// <summary>
    /// Represents the script execution utility main view model.
    /// </summary>
    /// <seealso cref="Tango.SharedUI.ViewModel" />
    public class MainViewVM : ViewModel
    {
        private UsbTransportAdapter _adapter; //Holds the USB transport adapter.
        private StubManager _stubManager;
        private INotificationProvider _notification;

        #region Properties

        public IStudioApplicationManager ApplicationManager { get; set; }

        private bool _useConnectedMachine;
        /// <summary>
        /// Gets or sets a value indicating whether [use connected machine].
        /// </summary>
        public bool UseConnectedMachine
        {
            get { return _useConnectedMachine; }
            set { _useConnectedMachine = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); }
        }

        /// <summary>
        /// Gets or sets the code tabs.
        /// </summary>
        public ObservableCollection<CodeTabVM> CodeTabs { get; set; }

        /// <summary>
        /// Gets or sets the additional highlight C# types.
        /// </summary>
        public ObservableCollection<KeyValuePair<String, Type>> HighlightTypes { get; set; }

        /// <summary>
        /// Gets or sets the collection of stub snippets.
        /// </summary>
        public ObservableCollection<StubSnippetVM> StubSnippets { get; set; }

        private StubSnippetVM _selectedStubSnippet;
        /// <summary>
        /// Gets or sets the selected stub snippet.
        /// </summary>
        public StubSnippetVM SelectedStubSnippet
        {
            get { return _selectedStubSnippet; }
            set { _selectedStubSnippet = value; RaisePropertyChanged(nameof(SelectedStubSnippet)); }
        }

        private String _log;
        /// <summary>
        /// Gets or sets the current response log.
        /// </summary>
        public String Log
        {
            get { return _log; }
            set { _log = value; RaisePropertyChanged(nameof(Log)); }
        }

        private CodeTabVM _selectedCodeTab;
        /// <summary>
        /// Gets or sets the selected code tab.
        /// </summary>
        public CodeTabVM SelectedCodeTab
        {
            get { return _selectedCodeTab; }
            set { _selectedCodeTab = value; RaisePropertyChanged(nameof(SelectedCodeTab)); InvalidateRelayCommands(); }
        }

        private bool _isConnected;
        /// <summary>
        /// Gets or sets a value indicating whether the USB adapter is connected.
        /// </summary>
        public bool IsConnected
        {
            get { return _isConnected; }
            set { _isConnected = value; RaisePropertyChanged(nameof(IsConnected)); InvalidateRelayCommands(); }
        }

        private List<String> _ports;
        /// <summary>
        /// Gets or sets the available USB ports.
        /// </summary>
        public List<String> Ports
        {
            get { return _ports; }
            set { _ports = value; RaisePropertyChanged(nameof(Ports)); }
        }

        private String _selectedPort;
        /// <summary>
        /// Gets or sets the selected USB port.
        /// </summary>
        public String SelectedPort
        {
            get { return _selectedPort; }
            set { _selectedPort = value; RaisePropertyChanged(nameof(SelectedPort)); InvalidateRelayCommands(); }
        }

        private String _status;
        /// <summary>
        /// Gets or sets the current status bar text.
        /// </summary>
        public String Status
        {
            get { return _status; }
            set { _status = value; RaisePropertyChanged(nameof(Status)); }
        }

        private bool _isRunning;
        /// <summary>
        /// Gets or sets a value indicating whether a stub is currently running.
        /// </summary>
        public bool IsRunning
        {
            get { return _isRunning; }
            set { _isRunning = value; RaisePropertyChanged(nameof(IsRunning)); InvalidateRelayCommands(); }
        }

        #endregion

        #region Commands

        /// <summary>
        /// Gets or sets the new command.
        /// </summary>
        public RelayCommand NewCommand { get; set; }

        /// <summary>
        /// Gets or sets the close tab command.
        /// </summary>
        public RelayCommand<CodeTabVM> CloseTabCommand { get; set; }

        /// <summary>
        /// Gets or sets the run command.
        /// </summary>
        public RelayCommand RunCommand { get; set; }

        /// <summary>
        /// Gets or sets the stop command.
        /// </summary>
        public RelayCommand StopCommand { get; set; }

        /// <summary>
        /// Gets or sets the toggle connection command.
        /// </summary>
        public RelayCommand ToggleConnectionCommand { get; set; }

        /// <summary>
        /// Gets or sets the open command.
        /// </summary>
        public RelayCommand OpenCommand { get; set; }

        /// <summary>
        /// Gets or sets the save command.
        /// </summary>
        public RelayCommand SaveCommand { get; set; }

        /// <summary>
        /// Gets or sets the save as command.
        /// </summary>
        public RelayCommand SaveAsCommand { get; set; }

        /// <summary>
        /// Gets or sets the stub snippet selected command.
        /// </summary>
        public RelayCommand StubSnippetSelectedCommand { get; set; }

        /// <summary>
        /// Gets or sets the insert snippet command.
        /// </summary>
        public RelayCommand<String> InsertSnippetCommand { get; set; }

        /// <summary>
        /// Gets or sets the exit command.
        /// </summary>
        public RelayCommand ExitCommand { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="MainViewVM"/> class.
        /// </summary>
        public MainViewVM(IStudioApplicationManager applicationManager, INotificationProvider notification)
        {
            ApplicationManager = applicationManager;
            _notification = notification;

            CodeTabs = new ObservableCollection<CodeTabVM>();

            NewCommand = new RelayCommand(CreateNewTab);
            CloseTabCommand = new RelayCommand<CodeTabVM>(OnTabClosing);
            RunCommand = new RelayCommand(RunTab, (x) => (IsConnected || UseConnectedMachine) && !IsRunning && SelectedCodeTab != null);
            StopCommand = new RelayCommand(StopTab, (x) => (IsConnected || UseConnectedMachine) && IsRunning && SelectedCodeTab != null);
            InsertSnippetCommand = new RelayCommand<string>((x) => { });

            HighlightTypes = new ObservableCollection<KeyValuePair<string, Type>>();
            HighlightTypes.Add(new KeyValuePair<string, Type>("stubManager", typeof(StubManager)));

            StubSnippets = new ObservableCollection<StubSnippetVM>();

            foreach (var stubType in StubBase.GetAvailableRequestStubs())
            {
                StubSnippetVM snippet = new StubSnippetVM();
                snippet.Name = stubType.Name.Replace("Stub_", "");
                snippet.Code = String.Format("stubManager.Run(\"{0}\" ,{1});", stubType.Name, String.Join(", ", stubType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(x => x.PropertyType.Name == "string" ? "\"string\"" : x.PropertyType.Name)));
                StubSnippets.Add(snippet);
            }

            ToggleConnectionCommand = new RelayCommand(ToggleConnection, (x) => !IsRunning);
            OpenCommand = new RelayCommand(OpenFile);
            SaveCommand = new RelayCommand(SaveFile);
            SaveAsCommand = new RelayCommand(SaveAsFile);
            StubSnippetSelectedCommand = new RelayCommand(OnStubSnippetSelected);
            ExitCommand = new RelayCommand(() => Application.Current.Shutdown());

            Ports = new List<string>()
            {
                "COM1",
                "COM2",
                "COM3",
                "COM4",
                "COM5",
                "COM6",
                "COM7",
                "COM8",
                "COM9",
            };

            SelectedPort = SettingsManager.Default.StubsUI.SelectedPort != null ? SettingsManager.Default.StubsUI.SelectedPort : Ports.First();

            Status = "Ready";

            if (SettingsManager.Default.StubsUI.LastTabs.Count > 0)
            {
                foreach (var file in SettingsManager.Default.StubsUI.LastTabs)
                {
                    if (File.Exists(file))
                    {
                        OpenFile(file);
                    }
                }
            }
            else
            {
                CreateNewTab();
            }

            Application.Current.Exit += Current_Exit;
        }

        #endregion

        #region Virtual Methods

        /// <summary>
        /// Called when a stub snippet is double clicked.
        /// </summary>
        protected virtual void OnStubSnippetSelected()
        {
            if (SelectedStubSnippet != null)
            {
                if (InsertSnippetCommand != null)
                {
                    InsertSnippetCommand.Execute(SelectedStubSnippet.Code);
                }
            }
        }

        /// <summary>
        /// Called when user closes a script tab.
        /// </summary>
        /// <param name="codeTab">The code tab.</param>
        protected virtual void OnTabClosing(CodeTabVM codeTab)
        {
            CodeTabs.Remove(codeTab);
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Saves the selected script file.
        /// </summary>
        private void SaveFile()
        {
            if (SelectedCodeTab != null)
            {
                if (SelectedCodeTab.File == null)
                {
                    SaveAsFile();
                }
                else
                {
                    File.WriteAllText(SelectedCodeTab.File, SelectedCodeTab.Code);
                }
            }
        }

        /// <summary>
        /// Saves the selected script file.
        /// </summary>
        private void SaveAsFile()
        {
            if (SelectedCodeTab != null)
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "C# Script Files|*.cs";
                dlg.DefaultExt = ".cs";
                if (dlg.ShowDialog().Value)
                {
                    File.WriteAllText(dlg.FileName, SelectedCodeTab.Code);
                    SelectedCodeTab.File = dlg.FileName;
                }
            }
        }

        /// <summary>
        /// Opens a script from HD.
        /// </summary>
        private void OpenFile()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "C# Script Files|*.cs";
            dlg.Multiselect = true;
            if (dlg.ShowDialog().Value)
            {
                foreach (var file in dlg.FileNames)
                {
                    OpenFile(file);
                }
            }
        }

        /// <summary>
        /// Opens the file.
        /// </summary>
        /// <param name="file">The file.</param>
        private void OpenFile(String file)
        {
            var newTab = new CodeTabVM();
            newTab.File = file;
            newTab.Code = File.ReadAllText(file);
            CodeTabs.Add(newTab);
            SelectedCodeTab = newTab;
        }

        /// <summary>
        /// Toggles the USB adapter connection.
        /// </summary>
        private void ToggleConnection()
        {
            try
            {
                if (!IsConnected)
                {
                    _adapter = new UsbTransportAdapter(SelectedPort);
                    _adapter.Connect().Wait();
                    IsConnected = true;
                }
                else
                {
                    _adapter.Disconnect().Wait();
                    IsConnected = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Tango");
            }
        }

        /// <summary>
        /// Creates a new script tab.
        /// </summary>
        private void CreateNewTab()
        {
            var newTab = new CodeTabVM();
            CodeTabs.Add(newTab);
            SelectedCodeTab = newTab;
        }

        /// <summary>
        /// Runs the selected script tab.
        /// </summary>
        private async void RunTab()
        {
            if (UseConnectedMachine && !ApplicationManager.IsMachineConnected)
            {
                _notification.ShowError("Cannot execute stub while 'Connected Machine' is set but not machine connected.");
                return;
            }

            IsRunning = true;
            SelectedCodeTab.IsRunning = true;
            Log = (DateTime.Now.ToTimeString() + ": ") + "Executing script '" + SelectedCodeTab.Title + "'..." + Environment.NewLine;

            await Task.Factory.StartNew(async () =>
            {
                try
                {
                    ITransportAdapter adapter = _adapter;

                    if (ApplicationManager.IsMachineConnected && UseConnectedMachine)
                    {
                        adapter = ApplicationManager.ConnectedMachine.Adapters.First();
                    }

                    _stubManager = new StubManager(adapter);
                    var thisStubManager = _stubManager;
                    _stubManager.Completed += Manager_Completed;
                    _stubManager.Failed += Manager_Failed;
                    _stubManager.Executed += Manager_Executed;

                    ScriptEngine engine = new ScriptEngine(new StubOnExecuteParameters(_stubManager));

                    engine.ReferencedAssemblies.Add(this.GetType());
                    await engine.Run(SelectedCodeTab.Code);

                    if (!thisStubManager.Aborted)
                    {
                        IsRunning = false;
                        SelectedCodeTab.IsRunning = false;
                    }
                }
                catch (Exception ex)
                {
                    IsRunning = false;
                    SelectedCodeTab.IsRunning = false;
                    MessageBox.Show(ex.Message, "Tango");
                }
            });
        }

        /// <summary>
        /// Stops the currently current script.
        /// </summary>
        private void StopTab()
        {
            if (_stubManager != null)
            {
                _stubManager.Abort();
                IsRunning = false;
                SelectedCodeTab.IsRunning = false;
                Status = "Stopped!";
                Log += (DateTime.Now.ToTimeString() + ": ") + "Stopped!" + Environment.NewLine;
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handled the <see cref="StubManager"/> Executed event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="stubName">Name of the stub.</param>
        private void Manager_Executed(object sender, string stubName)
        {
            Log += (DateTime.Now.ToTimeString() + ": ") + "Executing '" + stubName + "'..." + Environment.NewLine;
            Status = "Executing " + stubName + "...";
        }

        /// <summary>
        /// Handled the <see cref="StubManager"/> Failed event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="ex">The exception.</param>
        private void Manager_Failed(object sender, Exception ex)
        {
            if (IsRunning)
            {
                Log += (DateTime.Now.ToTimeString() + ": ") + ex.Message + Environment.NewLine;
                Status = "Failed!";
            }
        }

        /// <summary>
        /// Handled the <see cref="StubManager"/> Completed event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="response">The response.</param>
        private void Manager_Completed(object sender, string response)
        {
            Log += (DateTime.Now.ToTimeString() + ": ") + "Response Received:" + Environment.NewLine;
            Log += (DateTime.Now.ToTimeString() + ": ") + response + Environment.NewLine;
            Status = "Completed";
        }

        private void Current_Exit(object sender, ExitEventArgs e)
        {
            SettingsManager.Default.MachineStudio.StubsModule.SelectedPort = SelectedPort;
            SettingsManager.Default.MachineStudio.StubsModule.LastTabs = CodeTabs.Select(x => x.File).ToList();
            SettingsManager.SaveDefaultSettings();
        }

        #endregion
    }
}