aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Modules/Tango.PPC.MachineSettings/ViewModels/MainViewVM.cs
blob: 7896367ec25c52e42b3bdfea98c050be0ce694c3 (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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using Tango.BL;
using Tango.BL.Entities;
using Tango.BL.Enumerations;
using Tango.Core.Commands;
using Tango.Core.DI;
using Tango.PPC.Common;
using Tango.PPC.Common.Connection;
using Tango.PPC.Common.ExternalBridge;
using Tango.PPC.Common.Messages;
using Tango.SharedUI.Components;
using Tango.WiFi;

namespace Tango.PPC.MachineSettings.ViewModels
{
    /// <summary>
    /// Represents the main view VM and entry point for <see cref="Synchronization.MyModule"/>.
    /// </summary>
    /// <seealso cref="Tango.PPC.Common.PPCViewModel" />
    public class MainViewVM : PPCViewModel
    {
        #region Properties

        private Machine _machine;
        public Machine Machine
        {
            get { return _machine; }
            set { _machine = value; RaisePropertyChangedAuto(); }
        }

        private SelectedObjectCollection<JobTypes> _selectedJobTypes;
        public SelectedObjectCollection<JobTypes> SelectedJobTypes
        {
            get { return _selectedJobTypes; }
            set { _selectedJobTypes = value; RaisePropertyChangedAuto(); }
        }

        private SelectedObjectCollection<ColorSpaces> _selectedColorSpaces;
        public SelectedObjectCollection<ColorSpaces> SelectedColorSpaces
        {
            get { return _selectedColorSpaces; }
            set { _selectedColorSpaces = value; RaisePropertyChangedAuto(); }
        }

        private bool _enableHotSpot;
        public bool EnableHotSpot
        {
            get { return _enableHotSpot; }
            set { _enableHotSpot = value; RaisePropertyChangedAuto(); OnEnableHotSpotChanged(); }
        }

        private String _hotSpotPassword;
        public String HotSpotPassword
        {
            get { return _hotSpotPassword; }
            set { _hotSpotPassword = value; RaisePropertyChangedAuto(); }
        }

        private bool _enableExternalBridge;
        public bool EnableExternalBridge
        {
            get { return _enableExternalBridge; }
            set { _enableExternalBridge = value; RaisePropertyChangedAuto(); OnEnableExternalBridgeChanged(); }
        }

        private String _externalBridgePassword;
        public String ExternalBridgePassword
        {
            get { return _externalBridgePassword; }
            set { _externalBridgePassword = value; RaisePropertyChangedAuto(); }
        }

        private bool _enableRemoteAssistance;
        public bool EnableRemoteAssistance
        {
            get { return _enableRemoteAssistance; }
            set { _enableRemoteAssistance = value; RaisePropertyChangedAuto(); OnEnableRemoteAssistanceChanged(); }
        }

        #endregion

        #region Commands

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

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

        #endregion

        public MainViewVM()
        {
            SaveCommand = new RelayCommand(Save);
            DiscardCommand = new RelayCommand(Discard);
        }

        private void Discard()
        {
            NavigationManager.NavigateBack();
        }

        private async void Save()
        {
            if (Validate())
            {
                Machine.SupportedJobTypes = SelectedJobTypes.SynchedSource.ToList();
                Machine.SupportedColorSpaces = SelectedColorSpaces.SynchedSource.ToList();
                Machine.ShallowCopyTo(MachineProvider.Machine);

                Settings.EnableHotSpot = EnableHotSpot;
                Settings.HotSpotPassword = HotSpotPassword;
                Settings.EnableExternalBridge = EnableExternalBridge;
                Settings.ExternalBridgePassword = ExternalBridgePassword;
                Settings.Save();

                await MachineProvider.SaveMachine();
                await NavigationManager.NavigateBack();
            }
        }

        protected override void OnValidating()
        {
            base.OnValidating();
        }

        /// <summary>
        /// Called when the application has been started
        /// </summary>
        public override void OnApplicationStarted()
        {

        }

        public override void OnNavigatedTo()
        {
            base.OnNavigatedTo();

            Machine = new Machine();
            MachineProvider.Machine.ShallowCopyTo(Machine);
            RaisePropertyChanged(nameof(Machine));

            _enableHotSpot = HotSpotProvider.IsEnabled;
            RaisePropertyChanged(nameof(EnableHotSpot));

            HotSpotPassword = Settings.HotSpotPassword;

            _enableExternalBridge = ExternalBridgeService.Enabled;
            RaisePropertyChanged(nameof(EnableExternalBridge));

            ExternalBridgePassword = Settings.ExternalBridgePassword;

            _enableRemoteAssistance = RemoteAssistanceProvider.IsEnabled;
            RaisePropertyChanged(nameof(EnableRemoteAssistance));


            SelectedJobTypes = new SelectedObjectCollection<JobTypes>(Enum.GetValues(typeof(JobTypes)).Cast<JobTypes>().ToObservableCollection(), Machine.SupportedJobTypes.ToObservableCollection());
            SelectedColorSpaces = new SelectedObjectCollection<ColorSpaces>(Enum.GetValues(typeof(ColorSpaces)).Cast<ColorSpaces>().Where(x => x.IsUserSpace()).ToObservableCollection(), Machine.SupportedColorSpaces.ToObservableCollection());
        }

        private async void OnEnableRemoteAssistanceChanged()
        {
            if (EnableRemoteAssistance)
            {
                try
                {
                    await RemoteAssistanceProvider.EnableRemoteAssistance();
                }
                catch
                {
                    await NotificationProvider.ShowError("An error occurred while trying to activate the remote assistance service. Please check your device settings and try again.");
                    _enableRemoteAssistance = false;
                }
            }
            else
            {
                try
                {
                    await RemoteAssistanceProvider.DisableRemoteAssistance();
                }
                catch
                {
                    await NotificationProvider.ShowError("An error occurred while trying to deactivate the remote assistance service. Please check your device settings and try again.");
                    _enableRemoteAssistance = true;
                }
            }

            RaisePropertyChanged(nameof(EnableRemoteAssistance));
        }

        private async void OnEnableHotSpotChanged()
        {
            if (EnableHotSpot)
            {
                if (HotSpotPassword == null || HotSpotPassword.Length < 8 || HotSpotPassword.Length > 16)
                {
                    await NotificationProvider.ShowError("Hot spot requires a password of 8 to 16 characters.");
                    _enableHotSpot = false;
                    RaisePropertyChanged(nameof(EnableHotSpot));
                    return;
                }

                try
                {
                    await HotSpotProvider.EnableHotSpot(HotSpotPassword);
                }
                catch
                {
                    await NotificationProvider.ShowError("An error occurred while trying to activate the hot spot network. Please check your device settings and try again.");
                    _enableHotSpot = false;
                }
            }
            else
            {
                try
                {
                    await HotSpotProvider.DisableHotSpot();
                }
                catch
                {
                    await NotificationProvider.ShowError("An error occurred while trying to deactivate the hot spot network.");
                    _enableHotSpot = true;
                }
            }

            RaisePropertyChanged(nameof(EnableHotSpot));
        }

        private void OnEnableExternalBridgeChanged()
        {
            ExternalBridgeService.Enabled = EnableExternalBridge;
        }
    }
}
w"> = new SearchPanelAdorner(textArea, this); DataContext = this; renderer = new SearchResultBackgroundRenderer(); currentDocument = textArea.Document; if (currentDocument != null) currentDocument.TextChanged += textArea_Document_TextChanged; textArea.DocumentChanged += textArea_DocumentChanged; KeyDown += SearchLayerKeyDown; this.CommandBindings.Add(new CommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); this.CommandBindings.Add(new CommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); this.CommandBindings.Add(new CommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); IsClosed = true; } void textArea_DocumentChanged(object sender, EventArgs e) { if (currentDocument != null) currentDocument.TextChanged -= textArea_Document_TextChanged; currentDocument = textArea.Document; if (currentDocument != null) { currentDocument.TextChanged += textArea_Document_TextChanged; DoSearch(false); } } void textArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } /// <inheritdoc/> public override void OnApplyTemplate() { base.OnApplyTemplate(); searchTextBox = Template.FindName("PART_searchTextBox", this) as TextBox; } void ValidateSearchText() { if (searchTextBox == null) return; var be = searchTextBox.GetBindingExpression(TextBox.TextProperty); try { Validation.ClearInvalid(be); UpdateSearch(); } catch (SearchPatternException ex) { var ve = new ValidationError(be.ParentBinding.ValidationRules[0], be, ex.Message, ex); Validation.MarkInvalid(be, ve); } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (searchTextBox == null) return; searchTextBox.Focus(); searchTextBox.SelectAll(); } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { SearchResult result = renderer.CurrentResults.FindFirstSegmentWithStartAfter(textArea.Caret.Offset + 1); if (result == null) result = renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { SearchResult result = renderer.CurrentResults.FindFirstSegmentWithStartAfter(textArea.Caret.Offset); if (result != null) result = renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } ToolTip messageView = new ToolTip { Placement = PlacementMode.Bottom, StaysOpen = false }; void DoSearch(bool changeSelection) { if (IsClosed) return; renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { int offset = textArea.Caret.Offset; if (changeSelection) { textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (SearchResult result in strategy.FindAll(textArea.Document, 0, textArea.Document.TextLength)) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } renderer.CurrentResults.Add(result); } if (!renderer.CurrentResults.Any()) { messageView.IsOpen = true; messageView.Content = Localization.NoMatchesFoundText; messageView.PlacementTarget = searchTextBox; } else messageView.IsOpen = false; } textArea.TextView.InvalidateLayer(KnownLayer.Selection); } void SelectResult(SearchResult result) { textArea.Caret.Offset = result.StartOffset; textArea.Selection = Selection.Create(textArea, result.StartOffset, result.EndOffset); textArea.Caret.BringCaretToView(); // show caret even if the editor does not have the Keyboard Focus textArea.Caret.Show(); } void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: e.Handled = true; messageView.IsOpen = false; if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) FindPrevious(); else FindNext(); if (searchTextBox != null) { var error = Validation.GetErrors(searchTextBox).FirstOrDefault(); if (error != null) { messageView.Content = Localization.ErrorText + " " + error.ErrorContent; messageView.PlacementTarget = searchTextBox; messageView.IsOpen = true; } } break; case Key.Escape: e.Handled = true; Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { bool hasFocus = this.IsKeyboardFocusWithin; var layer = AdornerLayer.GetAdornerLayer(textArea); if (layer != null) layer.Remove(adorner); messageView.IsOpen = false; textArea.TextView.BackgroundRenderers.Remove(renderer); if (hasFocus) textArea.Focus(); IsClosed = true; // Clear existing search results so that the segments don't have to be maintained renderer.CurrentResults.Clear(); } /// <summary> /// Closes the SearchPanel and removes it. /// </summary> public void CloseAndRemove() { Close(); textArea.DocumentChanged -= textArea_DocumentChanged; if (currentDocument != null) currentDocument.TextChanged -= textArea_Document_TextChanged; } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; var layer = AdornerLayer.GetAdornerLayer(textArea); if (layer != null) layer.Add(adorner); textArea.TextView.BackgroundRenderers.Add(renderer); IsClosed = false; DoSearch(false); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchPanel.SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { if (SearchOptionsChanged != null) { SearchOptionsChanged(this, e); } } } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; private set; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; private set; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; private set; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; private set; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { this.SearchPattern = searchPattern; this.MatchCase = matchCase; this.UseRegex = useRegex; this.WholeWords = wholeWords; } } class SearchPanelAdorner : Adorner { SearchPanel panel; public SearchPanelAdorner(TextArea textArea, SearchPanel panel) : base(textArea) { this.panel = panel; AddVisualChild(panel); } protected override int VisualChildrenCount { get { return 1; } } protected override Visual GetVisualChild(int index) { if (index != 0) throw new ArgumentOutOfRangeException(); return panel; } protected override Size ArrangeOverride(Size finalSize) { panel.Arrange(new Rect(new Point(0, 0), finalSize)); return new Size(panel.ActualWidth, panel.ActualHeight); } } }