aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MainViewVM.cs
blob: b53a54682c17403a2c9651d03cdf8c0fc7849a7c (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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
using Tango.BL;
using Tango.BL.Builders;
using Tango.BL.Entities;
using Tango.Core.DI;
using Tango.Integration.ExternalBridge;
using Tango.Integration.Operation;
using Tango.PPC.Common;
using Tango.PPC.Common.Application;
using Tango.PPC.Common.Authentication;
using Tango.PPC.Common.ExternalBridge;
using Tango.PPC.Common.Modules;
using Tango.PPC.Common.Navigation;
using Tango.PPC.Common.Notifications;
using Tango.PPC.Common.WatchDog;
using Tango.PPC.UI.Dialogs;
using Tango.SharedUI;
using System.Data.Entity;

namespace Tango.PPC.UI.ViewModels
{
    /// <summary>
    /// Represents the PPC main view model.
    /// </summary>
    /// <seealso cref="Tango.PPC.Common.PPCViewModel" />
    public class MainViewVM : PPCViewModel
    {
        private DispatcherTimer _date_timer;
        private bool _isPowerUpDialogShown;
        private bool _isThreadLoadingShown;

        private DateTime _currentDateTime;
        /// <summary>
        /// Gets or sets the current date time.
        /// </summary>
        public DateTime CurrentDateTime
        {
            get { return _currentDateTime; }
            set { _currentDateTime = value; RaisePropertyChangedAuto(); }
        }

        public MainViewVM()
        {
            _date_timer = new DispatcherTimer();
            _date_timer.Interval = TimeSpan.FromSeconds(1);
            _date_timer.Tick += _date_timer_Tick;
            _date_timer.Start();
        }

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

        }

        public override void OnApplicationReady()
        {
            base.OnApplicationReady();
            MachineProvider.MachineOperator.CartridgeValidationRequestReceived += MachineOperator_CartridgeValidationRequestReceived;
            MachineProvider.MachineOperator.PowerUpStarted += MachineOperator_PowerUpStarted;
            MachineProvider.MachineOperator.ThreadLoadingStatusChanged += MachineOperator_ThreadLoadingStatusChanged;
            MachineProvider.MachineOperator.ThreadLoadingConfirmationRequired += MachineOperator_ThreadLoadingConfirmationRequired;
        }

        #region Event Handlers

        /// <summary>
        /// Handles the Tick event of the _date_timer.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void _date_timer_Tick(object sender, EventArgs e)
        {
            CurrentDateTime = DateTime.Now;
        }

        private void MachineOperator_CartridgeValidationRequestReceived(object sender, CartridgeValidationEventArgs e)
        {
            InvokeUI(async () =>
            {
                var vm = await NotificationProvider.ShowDialog<CartridgeValidationViewVM>(new CartridgeValidationViewVM()
                {
                    IDSPacks = MachineProvider.Machine.Configuration.NoneEmptyIdsPacks.ToList(),
                });

                if (vm.DialogResult)
                {
                    e.Approve(vm.SelectedIDSPack.PackIndex);
                }
                else
                {
                    e.Decline();
                }
            });
        }

        private async void MachineOperator_PowerUpStarted(object sender, EventArgs e)
        {
            if (_isPowerUpDialogShown)
            {
                LogManager.Log("Power up detected but power up dialog is already shown. Skipping...");
                return;
            }

            LogManager.Log("Power up detected, showing power up screen...");

            if (!Settings.DisplayPowerUpScreen)
            {
                LogManager.Log("Power up screen disabled. skipping...");
                return;
            }

            PowerUpViewVM vm;

            try
            {
                LogManager.Log("Loading site rmls...");

                List<Rml> rmls = new List<Rml>();

                using (ObservablesContext db = ObservablesContext.CreateDefault())
                {
                    rmls = await new RmlsCollectionBuilder(db).SetAll().ForHeadType(MachineProvider.Machine.MachineHeadType).ForSite(MachineProvider.Machine.SiteGuid).BuildListAsync();
                }

                var selectedRml = rmls.SingleOrDefault(x => x.Guid == Settings.LoadedRmlGuid);

                vm = new PowerUpViewVM();
                vm.Rmls = rmls;
                vm.SelectedRml = selectedRml != null ? selectedRml : rmls.FirstOrDefault();
                vm.IsSelectedRml = selectedRml != null;
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error initializing power up screen.");
                return;
            }

            InvokeUI(async () =>
            {
                _isPowerUpDialogShown = true;
                await NotificationProvider.ShowDialog<PowerUpViewVM>(vm);
                _isPowerUpDialogShown = false;

                await Task.Factory.StartNew(() =>
                {
                    LogManager.Log("Power up screen closed.");

                    try
                    {
                        using (ObservablesContext db = ObservablesContext.CreateDefault())
                        {
                            List<ProcessParametersTable> processTables = new List<ProcessParametersTable>();

                            if (vm.IsSelectedRml)
                            {
                                LogManager.Log($"Selected rml '{vm.SelectedRml.Name}'...");
                                processTables = new RmlBuilder(db).Set(vm.SelectedRml.Guid).WithActiveParametersGroup().Build().GetActiveProcessGroup().ProcessParametersTables.ToList();
                            }
                            else
                            {
                                LogManager.Log("Selected minimal temperature...");
                                var rmlsToAvg = new RmlsCollectionBuilder(db).SetAll().ForHeadType(MachineProvider.Machine.MachineHeadType).ForSite(MachineProvider.Machine.SiteGuid).WithActiveParametersGroup().Build();
                                processTables = rmlsToAvg.Select(x => x.GetActiveProcessGroup()).SelectMany(x => x.ProcessParametersTables).ToList();
                            }

                            var processToLoad = processTables.OrderBy(x => x.GetAverageTemperature()).First();

                            LogManager.Log($"Selected process parameters:\nRML: {processToLoad.ProcessParametersTablesGroup.Rml.Name}\nGroup: {processToLoad.ProcessParametersTablesGroup.Name}\nProcess Table: {processToLoad.Name}");
                            LogManager.Log("Uploading process parameters...");
                            var r = MachineProvider.MachineOperator.UploadProcessParameters(processToLoad).Result;

                            Settings.LoadedRmlGuid = vm.IsSelectedRml ? vm.SelectedRml.Guid : null;
                            Settings.Save();
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error occurred while trying to get and upload the proper process parameters after power screen closed.");
                    }
                });
            });
        }

        private void MachineOperator_ThreadLoadingStatusChanged(object sender, PMR.ThreadLoading.StartThreadLoadingResponse e)
        {
            if (e.State == PMR.ThreadLoading.ThreadLoadingState.Preparing)
            {
                DisplayThreadLoading();
            }
        }

        private void MachineOperator_ThreadLoadingConfirmationRequired(object sender, ThreadLoadingConfirmationRequiredEventArgs e)
        {
            DisplayThreadLoading(e);
        }

        private async void DisplayThreadLoading(ThreadLoadingConfirmationRequiredEventArgs confirmationArgs = null)
        {
            if (_isThreadLoadingShown) return;

            _isThreadLoadingShown = true;

            LogManager.Log("Thread loading preparation/finalization detected, showing thread loading screen...");

            if (!Settings.DisplayAutomaticThreadLoadingScreen)
            {
                _isThreadLoadingShown = false;
                LogManager.Log("Thread loading screen disabled. skipping...");
                return;
            }

            ThreadLoadingViewVM vm;

            try
            {
                LogManager.Log("Loading site rmls...");

                List<Rml> rmls = new List<Rml>();

                using (ObservablesContext db = ObservablesContext.CreateDefault())
                {
                    rmls = await new RmlsCollectionBuilder(db).SetAll().ForHeadType(MachineProvider.Machine.MachineHeadType).ForSite(MachineProvider.Machine.SiteGuid).WithActiveParametersGroup().BuildListAsync();
                }

                var selectedRml = rmls.SingleOrDefault(x => x.Guid == Settings.LoadedRmlGuid);

                if (confirmationArgs == null)
                {
                    vm = new ThreadLoadingViewVM(MachineProvider);
                }
                else
                {
                    vm = new ThreadLoadingViewVM(MachineProvider, confirmationArgs);
                }

                vm.Rmls = rmls;
                vm.SelectedRml = selectedRml != null ? selectedRml : rmls.FirstOrDefault();
            }
            catch (Exception ex)
            {
                _isThreadLoadingShown = false;
                LogManager.Log(ex, "Error initializing thread loading screen.");
                return;
            }

            InvokeUI(async () =>
            {
                await NotificationProvider.ShowDialog<ThreadLoadingViewVM>(vm);

                _isThreadLoadingShown = false;

                LogManager.Log("Thread loading screen closed.");

                if (!vm.DialogResult)
                {
                    LogManager.Log("Thread loading screen aborted by user. No operation was performed.");
                    return;
                }

                try
                {
                    if (vm.Result.IsCompleted)
                    {
                        await NotificationProvider.ShowSuccess("Thread loading completed successfully.");
                    }
                    else
                    {
                        await NotificationProvider.ShowError($"Thread loading failed due to the following reason:\n{vm.Result.FailedException.FlattenException()}");
                    }

                    if (vm.SelectedRml != null)
                    {
                        Settings.LoadedRmlGuid = vm.SelectedRml.Guid;
                        Settings.Save();
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Error occurred after thread loading screen closed.");
                }
            });
        }
        #endregion
    }
}
nts = textArea.Selection.Segments.Cast<ISegment>(); } if (segments != null) { foreach (ISegment segment in segments.Reverse()) { foreach (ISegment writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak static void OnEnter(object target, ExecutedRoutedEventArgs args) { TextArea textArea = GetTextArea(target); if (textArea != null && textArea.IsKeyboardFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab static void OnTab(object target, ExecutedRoutedEventArgs args) { TextArea textArea = GetTextArea(target); if (textArea != null && textArea.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; DocumentLine start = textArea.Document.GetLineByOffset(segment.Offset); DocumentLine end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; DocumentLine current = start; while (true) { int offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { string indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { int offset = line.Offset; ISegment s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete static ExecutedRoutedEventHandler OnDelete(RoutedUICommand selectingCommand) { return (target, args) => { TextArea textArea = GetTextArea(target); if (textArea != null && textArea.Document != null) { // call BeginUpdate before running the 'selectingCommand' // so that undoing the delete does not select the deleted character using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsEmpty) { TextViewPosition oldCaretPosition = textArea.Caret.Position; if (textArea.Caret.IsInVirtualSpace && selectingCommand == EditingCommands.SelectRightByCharacter) EditingCommands.SelectRightByWord.Execute(args.Parameter, textArea); else selectingCommand.Execute(args.Parameter, textArea); bool hasSomethingDeletable = false; foreach (ISegment s in textArea.Selection.Segments) { if (textArea.GetDeletableSegments(s).Length > 0) { hasSomethingDeletable = true; break; } } if (!hasSomethingDeletable) { // If nothing in the selection is deletable; then reset caret+selection // to the previous value. This prevents the caret from moving through read-only sections. textArea.Caret.Position = oldCaretPosition; textArea.ClearSelection(); } } textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } static void CanDelete(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for delete command TextArea textArea = GetTextArea(target); if (textArea != null && textArea.Document != null) { args.CanExecute = !textArea.Selection.IsEmpty; args.Handled = true; } } #endregion #region Clipboard commands static void CanCutOrCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands TextArea textArea = GetTextArea(target); if (textArea != null && textArea.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } static void OnCopy(object target, ExecutedRoutedEventArgs args) { TextArea textArea = GetTextArea(target); if (textArea != null && textArea.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { DocumentLine currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } static void OnCut(object target, ExecutedRoutedEventArgs args) { TextArea textArea = GetTextArea(target); if (textArea != null && textArea.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { DocumentLine currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); ISegment[] segmentsToDelete = textArea.GetDeletableSegments(new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (int i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } else { CopySelectedText(textArea); textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } static void CopySelectedText(TextArea textArea) { var data = textArea.Selection.CreateDataObject(textArea); try { Clipboard.SetDataObject(data, true); } catch (ExternalException) { // Apparently this exception sometimes happens randomly. // The MS controls just ignore it, so we'll do the same. return; } string text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); textArea.OnTextCopied(new TextEventArgs(text)); } const string LineSelectedType = "MSDEVLineSelect"; // This is the type VS 2003 and 2005 use for flagging a whole line copy static void CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); string text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); DataObject data = new DataObject(text); // Also copy text in HTML format to clipboard - good for pasting text into Word // or to the SharpDevelop forums. IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; HtmlClipboard.SetHtml(data, HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, new HtmlOptions(textArea.Options))); MemoryStream lineSelected = new MemoryStream(1); lineSelected.WriteByte(1); data.SetData(LineSelectedType, lineSelected, false); try { Clipboard.SetDataObject(data, true); } catch (ExternalException) { // Apparently this exception sometimes happens randomly. // The MS controls just ignore it, so we'll do the same. return; } textArea.OnTextCopied(new TextEventArgs(text)); } static void CanPaste(object target, CanExecuteRoutedEventArgs args) { TextArea textArea = GetTextArea(target); if (textArea != null && textArea.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) && Clipboard.ContainsText(); // WPF Clipboard.ContainsText() is safe to call without catching ExternalExceptions // because it doesn't try to lock the clipboard - it just peeks inside with IsClipboardFormatAvailable(). args.Handled = true; } } static void OnPaste(object target, ExecutedRoutedEventArgs args) { TextArea textArea = GetTextArea(target); if (textArea != null && textArea.Document != null) { IDataObject dataObject; try { dataObject = Clipboard.GetDataObject(); } catch (ExternalException) { return; } if (dataObject == null) return; Debug.WriteLine( dataObject.GetData(DataFormats.Html) as string ); // convert text back to correct newlines for this document string newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); string text; try { text = (string)dataObject.GetData(DataFormats.UnicodeText); text = TextUtilities.NormalizeNewLines(text, newLine); } catch (OutOfMemoryException) { return; } if (!string.IsNullOrEmpty(text)) { bool fullLine = textArea.Options.CutCopyWholeLine && dataObject.GetDataPresent(LineSelectedType); bool rectangular = dataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); if (fullLine) { DocumentLine currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (textArea.ReadOnlySectionProvider.CanInsert(currentLine.Offset)) { textArea.Document.Insert(currentLine.Offset, text); } } else if (rectangular && textArea.Selection.IsEmpty && !(textArea.Selection is RectangleSelection)) { if (!RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, false)) textArea.ReplaceSelectionWithText(text); } else { textArea.ReplaceSelectionWithText(text); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region DeleteLine static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { TextArea textArea = GetTextArea(target); if (textArea != null && textArea.Document != null) { DocumentLine currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); textArea.Selection = Selection.Create(textArea, currentLine.Offset, currentLine.Offset + currentLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { TextDocument document = textArea.Document; int endOffset = segment.EndOffset; string indentationString = new string(' ', textArea.Options.IndentationSize); for (int offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { TextDocument document = textArea.Document; int endOffset = segment.EndOffset; int indentationSize = textArea.Options.IndentationSize; int spacesCount = 0; for (int offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { string oldText = textArea.Document.GetText(segment); string newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } static string InvertCase(string text) { CultureInfo culture = CultureInfo.CurrentCulture; char[] buffer = text.ToCharArray(); for (int i = 0; i < buffer.Length; ++i) { char c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c, culture) : char.ToUpper(c, culture); } return new string(buffer); } #endregion static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { TextArea textArea = GetTextArea(target); if (textArea != null && textArea.Document != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } else { start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset).LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset).LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } }