public void Parse(string path, TextChangedEvent e = null) { //if the server is restarted during Eclipse lifetime, then we need to init the parser //This is useful when debugging. Perhaps it'll be deleted at the end if (!Compilers.ContainsKey(path)) { Init(path, new TypeCobolOptions { ExecToStep = ExecutionStep.Generate }); } Compiler = Compilers[path]; Compiler.CompilationResultsForProgram.TextLinesChanged += OnTextLine; Compiler.CompilationResultsForProgram.CodeElementsLinesChanged += OnCodeElementLine; if (!Inits[path]) { Inits[path] = true; // no need to update with the same content as at compiler creation } else if (e != null) { Compiler.CompilationResultsForProgram.UpdateTextLines(e); } try { Compiler.CompileOnce(); } catch (Exception ex) { throw new ParsingException(MessageCode.SyntaxErrorInParser, ex.Message, path, ex, true, true); } MissingCopys = Compiler.CompilationResultsForProgram.MissingCopies.Select(c => c.TextName).Distinct().ToList(); Compiler.CompilationResultsForProgram.TextLinesChanged -= OnTextLine; Compiler.CompilationResultsForProgram.CodeElementsLinesChanged -= OnCodeElementLine; }
protected void OnTouchButtonRelease(object o, ButtonReleaseEventArgs args) { if (enableTouch) { var parent = Toplevel as Window; var t = new TouchNumberInput(includeTimeFunctions, parent); if (!string.IsNullOrWhiteSpace(name)) { t.Title = name; } t.TextSetEvent += (sender, a) => { TextChangedEvent?.Invoke(this, a); if (a.keepText) { text = a.text; } }; t.Run(); t.Destroy(); QueueDraw(); } }
public void Parse(string path, TextChangedEvent e = null) { //if the server is restarted during Eclipse lifetime, then we need to init the parser //This is useful when debugging. Perhaps it'll be deleted at the end if (!Compilers.ContainsKey(path)) { Init(path, new TypeCobolOptions { ExecToStep = ExecutionStep.Generate }); } Compiler = Compilers[path]; Compiler.CompilationResultsForProgram.TextLinesChanged += OnTextLine; Compiler.CompilationResultsForProgram.CodeElementsLinesChanged += OnCodeElementLine; if (!Inits[path]) { Inits[path] = true; // no need to update with the same content as at compiler creation } else { Compiler.CompilationResultsForProgram.UpdateTextLines(e); } try { Compiler.CompileOnce(); } catch (Exception ex) { Observer.OnError(ex); System.Console.WriteLine(ex.ToString()); } MissingCopys = Compiler.CompilationProject.MissingCopys; Compiler.CompilationResultsForProgram.TextLinesChanged -= OnTextLine; Compiler.CompilationResultsForProgram.CodeElementsLinesChanged -= OnCodeElementLine; }
/// <summary> /// Update the message displaying how long since the results were updated /// </summary> private void UpdateMessage() { string newText = textMessage; // If there has been an update then display how old it is if (lastUpdate != DateTime.MinValue) { TimeSpan updateSpan = DateTime.Now - lastUpdate; if (updateSpan.TotalMinutes < 1) { newText = "Updated a moment ago"; } else if (updateSpan.TotalMinutes < 60) { if (updateSpan.TotalMinutes < 2) { newText = "Updated a minute ago"; } else { newText = string.Format("Updated {0} minutes ago", ( int )updateSpan.TotalMinutes); } } else if (updateSpan.TotalHours < 24) { if (updateSpan.TotalHours < 2) { newText = "Updated an hour ago"; } else { newText = string.Format("Updated {0} hours ago", ( int )updateSpan.TotalHours); } } else { newText = "Updated more than a day ago"; } } // If there is a trip selected then prompts for an update else if (TrainTrips.Selected != -1) { newText = "Click to update"; } else { // Prevent an update if nothing is selected newText = ""; } // If there has been a change then report it if (newText != textMessage) { textMessage = newText; TextChangedEvent?.Invoke(this, new TextChangedEventArgs { Text = textMessage }); } }
/// <summary> /// Update the text contents of the file /// </summary> public void UpdateSourceFile(Uri fileUri, TextChangedEvent textChangedEvent, bool bAsync) { FileCompiler fileCompilerToUpdate = null; if (OpenedFileCompiler.TryGetValue(fileUri, out fileCompilerToUpdate)) { fileCompilerToUpdate.CompilationResultsForProgram.UpdateTextLines(textChangedEvent); if (!bAsync) {//Don't wait asynchroneous snapshot refresh. fileCompilerToUpdate.CompilationResultsForProgram.UpdateTokensLines( () => { fileCompilerToUpdate.CompilationResultsForProgram.RefreshTokensDocumentSnapshot(); fileCompilerToUpdate.CompilationResultsForProgram.RefreshProcessedTokensDocumentSnapshot(); fileCompilerToUpdate.CompilationResultsForProgram.RefreshCodeElementsDocumentSnapshot(); fileCompilerToUpdate.CompilationResultsForProgram.RefreshProgramClassDocumentSnapshot(); } ); } else { fileCompilerToUpdate.CompilationResultsForProgram.UpdateTokensLines(); } } }
private void button1_Click(object sender, EventArgs e) { Id = (int)numericUpDown2.Value; Model = textBox2.Text; Price = numericUpDown1.Value; Sold = checkBox1.Checked; TextChangedEvent?.Invoke(this, EventArgs.Empty); }
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e) { if (sendNextChangeEvents) { RaiseTextChanged(textChangedEvent); textChangedEvent = new TextChangedEvent(); } }
private void SelectionChanged(int selection) { if (_hiddenTextBox.SelectionEnd < _hiddenTextBox.SelectionStart) { _hiddenTextBox.SelectionStart = _hiddenTextBox.SelectionEnd; } TextChangedEvent?.Invoke(_hiddenTextBox.Text ?? string.Empty, _hiddenTextBox.SelectionStart, _hiddenTextBox.SelectionEnd, true); }
private void RaiseTextChanged(TextChangedEvent textEvent) { EventHandler <TextChangedEvent> textChanged = TextChanged; if (textChanged != null) { textChanged(this, textEvent); } }
/// <summary> /// Update the text contents of the file /// </summary> public void UpdateSourceFile(string fileName, TextChangedEvent textChangedEvent) { FileCompiler fileCompilerToUpdate = null; if (OpenedFileCompilers.TryGetValue(fileName, out fileCompilerToUpdate)) { fileCompilerToUpdate.CompilationResultsForProgram.UpdateTextLines(textChangedEvent); fileCompilerToUpdate.CompilationResultsForProgram.UpdateTokensLines(); } }
public void CheckPerformance() { // Sample program properties string folder = "Parser" + Path.DirectorySeparatorChar + "Samples"; string textName = "BigBatch"; DocumentFormat documentFormat = DocumentFormat.RDZReferenceFormat; // Create a FileCompiler for this program DirectoryInfo localDirectory = new DirectoryInfo(PlatformUtils.GetPathForProjectFile(folder)); if (!localDirectory.Exists) { throw new Exception(String.Format("Directory : {0} does not exist", localDirectory.FullName)); } CompilationProject project = new CompilationProject("test", localDirectory.FullName, new string[] { ".cbl", ".cpy" }, documentFormat.Encoding, documentFormat.EndOfLineDelimiter, documentFormat.FixedLineLength, documentFormat.ColumnsLayout, new TypeCobolOptions()); FileCompiler compiler = new FileCompiler(null, textName, project.SourceFileProvider, project, documentFormat.ColumnsLayout, new TypeCobolOptions(), null, false, project); // Execute a first (complete) compilation compiler.CompileOnce(); // Append one line in the middle of the program ITextLine newLine = new TextLineSnapshot(9211, "094215D DISPLAY '-ICLAUA = ' ICLAUA. 0000000", null); TextChangedEvent textChangedEvent = new TextChangedEvent(); textChangedEvent.TextChanges.Add(new TextChange(TextChangeType.LineInserted, 9211, newLine)); compiler.CompilationResultsForProgram.UpdateTextLines(textChangedEvent); // Execute a second (incremental) compilation compiler.CompileOnce(); // Display a performance report StringBuilder report = new StringBuilder(); report.AppendLine("Program properties :"); report.AppendLine("- " + compiler.CompilationResultsForProgram.CobolTextLines.Count + " lines"); report.AppendLine("- " + compiler.CompilationResultsForProgram.CodeElementsDocumentSnapshot.CodeElements.Count() + " code elements"); report.AppendLine("First compilation performance"); report.AppendLine("- " + compiler.CompilationResultsForProgram.PerfStatsForText.FirstCompilationTime + " ms : text update"); report.AppendLine("- " + compiler.CompilationResultsForProgram.PerfStatsForScanner.FirstCompilationTime + " ms : scanner"); report.AppendLine("- " + compiler.CompilationResultsForProgram.PerfStatsForPreprocessor.FirstCompilationTime + " ms : preprocessor"); report.AppendLine("- " + compiler.CompilationResultsForProgram.PerfStatsForCodeElementsParser.FirstCompilationTime + " ms : code elements parser"); report.AppendLine("- " + compiler.CompilationResultsForProgram.PerfStatsForTemporarySemantic.FirstCompilationTime + " ms : temporary semantic class parser"); report.AppendLine("- " + compiler.CompilationResultsForProgram.PerfStatsForProgramCrossCheck.FirstCompilationTime + " ms : cross check class parser"); report.AppendLine("Incremental compilation performance"); report.AppendLine("- " + compiler.CompilationResultsForProgram.PerfStatsForText.LastRefreshTime + " ms : text update"); report.AppendLine("- " + compiler.CompilationResultsForProgram.PerfStatsForScanner.LastRefreshTime + " ms : scanner"); report.AppendLine("- " + compiler.CompilationResultsForProgram.PerfStatsForPreprocessor.LastRefreshTime + " ms : preprocessor"); report.AppendLine("- " + compiler.CompilationResultsForProgram.PerfStatsForCodeElementsParser.LastRefreshTime + " ms : code elements parser"); report.AppendLine("- " + compiler.CompilationResultsForProgram.PerfStatsForTemporarySemantic.LastRefreshTime + " ms : temporary semantic class parser"); report.AppendLine("- " + compiler.CompilationResultsForProgram.PerfStatsForProgramCrossCheck.LastRefreshTime + " ms : cross check class parser"); Console.WriteLine(report.ToString()); }
/// <summary> /// Update the text contents of the file /// </summary> public void UpdateSourceFile(Uri fileUri, TextChangedEvent textChangedEvent) { FileCompiler fileCompilerToUpdate = null; if (OpenedFileCompiler.TryGetValue(fileUri, out fileCompilerToUpdate)) { _semanticUpdaterTimer?.Stop(); fileCompilerToUpdate.CompilationResultsForProgram.UpdateTextLines(textChangedEvent); if (IsLsrSourceTesting) { //Log text lines string var sb = new StringBuilder(); foreach (var cobolTextLine in fileCompilerToUpdate.CompilationResultsForProgram.CobolTextLines) { sb.AppendLine(cobolTextLine.SourceText); } _Logger(sb.ToString(), fileUri); } var handler = new Action <object, ExecutionStepEventArgs>((sender, args) => { ExecutionStepEventHandler(sender, args, fileUri); }); //Subscribe to FileCompilerEvent fileCompilerToUpdate.ExecutionStepEventHandler += handler.Invoke; var execStep = LsrTestOptions.ExecutionStep(fileCompilerToUpdate.CompilerOptions.ExecToStep); if (execStep > ExecutionStep.SyntaxCheck) { execStep = ExecutionStep.SyntaxCheck; //The maximum execstep authorize for incremental parsing is SyntaxCheck, } //further it's for semantic, which is handle by NodeRefresh method fileCompilerToUpdate.CompileOnce(execStep, fileCompilerToUpdate.CompilerOptions.HaltOnMissingCopy, fileCompilerToUpdate.CompilerOptions.UseAntlrProgramParsing); fileCompilerToUpdate.ExecutionStepEventHandler -= handler.Invoke; if (LsrTestOptions == LsrTestingOptions.NoLsrTesting || LsrTestOptions == LsrTestingOptions.LsrSemanticPhaseTesting) { if (!_timerDisabled) //If TimerDisabled is false, create a timer to automatically launch Node phase { lock (_fileCompilerWaittingForNodePhase) { if (!_fileCompilerWaittingForNodePhase.Contains(fileCompilerToUpdate)) { _fileCompilerWaittingForNodePhase.Add(fileCompilerToUpdate); //Store that this fileCompiler will soon need a Node Phase } } _semanticUpdaterTimer = new System.Timers.Timer(750); _semanticUpdaterTimer.Elapsed += (sender, e) => TimerEvent(sender, e, fileCompilerToUpdate); _semanticUpdaterTimer.Start(); } } } }
private void OnTextChange() { if (!string.IsNullOrEmpty(Text) && CurrentSelectedChar > Text.Length) { CurrentSelectedChar = Text.Length; } TextChangedEvent.Invoke(); ButtonTextBlock.Text = Text; }
private void HandleTextChangedEvent(TextChangedEvent evnt) { if (!string.IsNullOrEmpty(evnt.Title)) { this.Title = evnt.Title; } if (!string.IsNullOrEmpty(evnt.Content)) { this.Content = evnt.Content; } }
public static TextChangedEvent UpdateLine(TextChangeType type, int line, string text, TextChangedEvent e = null) { if (e == null) { e = new TextChangedEvent(); } ITextLine snapshot = new TextLineSnapshot(line, text, null); e.TextChanges.Add(new TextChange(type, line, snapshot)); return(e); }
/// <summary> /// Send a change notification including all the text lines /// </summary> private void SendSocumentChangeEvent() { TextChangedEvent initialEvent = new TextChangedEvent(); int lineIndex = 0; foreach (ITextLine textLine in Lines) { TextChange lineAdded = new TextChange(TextChangeType.LineInserted, lineIndex, textLine); initialEvent.TextChanges.Add(lineAdded); lineIndex++; } RaiseTextChanged(initialEvent); }
private void HandleKeyPressEvent(object o, KeyPressEventArgs args) { var key = (Common.Configuration.Hid.Key)GTK3MappingHelper.ToInputKey(args.Event.Key); if (!(KeyPressedEvent?.Invoke(key)).GetValueOrDefault(true)) { return; } if (_canProcessInput) { _inputToTextEntry.SendKeyPressEvent(o, args); _inputToTextEntry.GetSelectionBounds(out int selectionStart, out int selectionEnd); TextChangedEvent?.Invoke(_inputToTextEntry.Text, selectionStart, selectionEnd, _inputToTextEntry.OverwriteMode); } }
private void HandleKeyReleaseEvent(object o, KeyReleaseEventArgs args) { var key = (Common.Configuration.Hid.Key)GTK3MappingHelper.ToInputKey(args.Event.Key); if (!(KeyReleasedEvent?.Invoke(key)).GetValueOrDefault(true)) { return; } if (_canProcessInput) { // TODO (caian): This solution may have problems if the pause is sent after a key press // and before a key release. But for now GTK Entry does not seem to use release events. _inputToTextEntry.SendKeyReleaseEvent(o, args); _inputToTextEntry.GetSelectionBounds(out int selectionStart, out int selectionEnd); TextChangedEvent?.Invoke(_inputToTextEntry.Text, selectionStart, selectionEnd, _inputToTextEntry.OverwriteMode); } }
private void InitEvent() { if (_eventAggregator == null) { return; } _requestSettingEvent = _eventAggregator.GetEvent <RequestSettingEvent>(); _requestSettingEvent.Subscribe(OnRequestSetting); _textChangedEvent = _eventAggregator.GetEvent <TextChangedEvent>(); _textChangedEvent.Subscribe(OnTextChanged, ThreadOption.UIThread); _requestTextEvent = _eventAggregator.GetEvent <RequestTextEvent>(); _requestTextEvent.Subscribe(OnRequestText); _saveTextEvent = _eventAggregator.GetEvent <SaveTextEvent>(); _saveTextEvent.Subscribe(OnSaveText, ThreadOption.UIThread); }
private void InitEvent() { if (_eventAggregator == null) { return; } _textChangedEvent = _eventAggregator.GetEvent <TextChangedEvent>(); _textChangedEvent.Subscribe(OnTextChanged); _requestTextEvent = _eventAggregator.GetEvent <RequestTextEvent>(); _requestTextEvent.Subscribe(OnRequestText); _saveTextEvent = _eventAggregator.GetEvent <SaveTextEvent>(); _saveTextEvent.Subscribe(OnSaveText); _cacheTextEvent = _eventAggregator.GetEvent <CacheTextEvent>(); _cacheTextEvent.Subscribe(OnCacheText); }
public async Task HandleAsync(TextChangedEvent message) { var id = message.AggregateRootKey.ToString(); var updateCriteria = new UpdateCriteria <TextTableObject>(); if (!string.IsNullOrEmpty(message.Title)) { updateCriteria.Add(x => x.Title, message.Title); } if (!string.IsNullOrEmpty(message.Content)) { updateCriteria.Add(x => x.Content, message.Content); } if (updateCriteria.Count == 0) { return; } Expression <Func <TextTableObject, bool> > updateSpecification = x => x.Id == id; await gateway.UpdateAsync <TextTableObject>(updateCriteria, updateSpecification); }
public static void ExecuteInceremental(FileCompiler compiler, TestUtils.CompilationStats stats) { // Execute a first (complete) compilation compiler.CompileOnce(); //Iterate multiple times over an incremental change stats.IterationNumber = 20; for (int i = 0; i < stats.IterationNumber; i++) { // Append one line in the middle of the program ITextLine newLine = new TextLineSnapshot(9211, "094215D DISPLAY '-ICLAUA = ' ICLAUA. 0000000", null); TextChangedEvent textChangedEvent = new TextChangedEvent(); textChangedEvent.TextChanges.Add(new TextChange(TextChangeType.LineInserted, 9211, newLine)); compiler.CompilationResultsForProgram.UpdateTextLines(textChangedEvent); // Execute a second (incremental) compilation compiler.CompileOnce(); //Accumulate results stats.AverageTextUpdateTime += compiler.CompilationResultsForProgram.PerfStatsForText.LastRefreshTime; stats.AverageScannerTime += compiler.CompilationResultsForProgram.PerfStatsForScanner.LastRefreshTime; stats.AveragePreprocessorTime += compiler.CompilationResultsForProgram.PerfStatsForPreprocessor.LastRefreshTime; stats.AverageCodeElementParserTime += compiler.CompilationResultsForProgram.PerfStatsForCodeElementsParser.LastRefreshTime; stats.AverateTemporarySemanticsParserTime += compiler.CompilationResultsForProgram.PerfStatsForTemporarySemantic.LastRefreshTime; stats.AverageCrossCheckerParserTime += compiler.CompilationResultsForProgram.PerfStatsForProgramCrossCheck.LastRefreshTime; } //Compute average time needed for each phase stats.AverageTextUpdateTime = (int)stats.AverageTextUpdateTime / stats.IterationNumber; stats.AverageScannerTime = (int)stats.AverageScannerTime / stats.IterationNumber; stats.AveragePreprocessorTime = (int)stats.AveragePreprocessorTime / stats.IterationNumber; stats.AverageCodeElementParserTime = (int)stats.AverageCodeElementParserTime / stats.IterationNumber; stats.AverateTemporarySemanticsParserTime = (int)stats.AverateTemporarySemanticsParserTime / stats.IterationNumber; stats.AverageCrossCheckerParserTime = (int)stats.AverageCrossCheckerParserTime / stats.IterationNumber; stats.AverageTotalProcessingTime = stats.AverageCodeElementParserTime + stats.AverageCrossCheckerParserTime + stats.AveragePreprocessorTime + stats.AverageScannerTime + stats.AverageTextUpdateTime + stats.AverateTemporarySemanticsParserTime; }
public void AddTextChangedEvent(TextChangedEvent @event) { textChangedEvents.Add(@event); }
public override void OnDidChangeTextDocument(DidChangeTextDocumentParams parameters) { var fileCompiler = GetFileCompilerFromStringUri(parameters.uri, false); //Text Change do not have to trigger node phase, it's only a another event that will do it if (fileCompiler == null) { return; } Uri objUri = new Uri(parameters.uri); #region Convert text changes format from multiline range replacement to single line updates TextChangedEvent textChangedEvent = new TextChangedEvent(); foreach (var contentChange in parameters.contentChanges) { // Split the text updated into distinct lines List <string> lineUpdates = null; bool replacementTextStartsWithNewLine = false; if (!string.IsNullOrEmpty(contentChange.text)) { replacementTextStartsWithNewLine = contentChange.text[0] == '\r' || contentChange.text[0] == '\n'; //Allow to know if a new line was added //Split on \r \n to know the number of lines added lineUpdates = contentChange.text.Replace("\r", "").Split('\n').ToList(); if (string.IsNullOrEmpty(lineUpdates.FirstOrDefault()) && replacementTextStartsWithNewLine) { lineUpdates.RemoveAt(0); } } // Document cleared if (contentChange.range == null) { //JCM: I have noticed that if the entire text has changed, is better to reload the entire file //To avoid crashes. try { typeCobolWorkspace.OpenSourceFile(objUri, contentChange.text, this.Workspace.LsrTestOptions); return; } catch (Exception e) { //Don't rethow an exception on save. RemoteConsole.Error(string.Format("Error while handling notification {0} : {1}", "textDocument/didChange", e.Message)); return; } } // Document updated else { // Get original lines text before change string originalFirstLineText = fileCompiler.CompilationResultsForProgram.CobolTextLines[contentChange.range.start.line] .Text; string originalLastLineText = originalFirstLineText; // Check if the first line was inserted int firstLineIndex = contentChange.range.start.line; int firstLineChar = contentChange.range.start.character; if (replacementTextStartsWithNewLine && !(contentChange.range.start.character < originalLastLineText.Length)) { firstLineIndex++; firstLineChar = 0; } else if (replacementTextStartsWithNewLine) //Detected that the add line appeared inside an existing line { lineUpdates.Add(lineUpdates.First()); //Add the default 7 spaces + add lineUpdates in order to update the current line and add the new one. } // Check if the last line was deleted int lastLineIndex = contentChange.range.end.line; if (contentChange.range.end.line > contentChange.range.start.line && contentChange.range.end.character == 0) { //Allows to detect if the next line was suppressed } if (contentChange.text?.Length == 0) { lineUpdates = new List <string>(); } if (lastLineIndex > firstLineIndex) { originalLastLineText = fileCompiler.CompilationResultsForProgram.CobolTextLines[ Math.Min(lastLineIndex, fileCompiler.CompilationResultsForProgram.CobolTextLines.Count - 1)].Text; } // Text not modified at the beginning of the first replaced line string startOfFirstLine = null; if (firstLineChar > 0) { if (originalFirstLineText.Length >= contentChange.range.start.character) { startOfFirstLine = originalFirstLineText.Substring(0, contentChange.range.start.character); } else { startOfFirstLine = originalFirstLineText.Substring(0, originalFirstLineText.Length) + new string(' ', contentChange.range.start.character - originalFirstLineText.Length); } } // Text not modified at the end of the last replaced line string endOfLastLine = null; if (contentChange.range.end.character < originalLastLineText.Length) { endOfLastLine = originalLastLineText.Substring(contentChange.range.end.character); } // Remove all the old lines for (int i = firstLineIndex; i <= lastLineIndex; i++) { var textChange = new TextChange(TextChangeType.LineRemoved, firstLineIndex, null); textChangedEvent.TextChanges.Add(textChange); //Mark the index line to be removed. The index will remains the same for each line delete, because text change are apply one after another } // Insert the updated lines if (!(startOfFirstLine == null && lineUpdates == null && endOfLastLine == null)) { int lineUpdatesCount = (lineUpdates != null && lineUpdates.Count > 0) ? lineUpdates.Count : 1; for (int i = 0; i < lineUpdatesCount; i++) { string newLine = (lineUpdates != null && lineUpdates.Count > 0) ? lineUpdates[i] : string.Empty; if (i == 0) { newLine = startOfFirstLine + newLine; } if (i == lineUpdatesCount - 1) { newLine = newLine + endOfLastLine; } var textChange = new TextChange(TextChangeType.LineInserted, firstLineIndex + i, new TextLineSnapshot(firstLineIndex + i, newLine, null)); textChangedEvent.TextChanges.Add(textChange); } } } } #endregion // Update the source file with the computed text changes typeCobolWorkspace.UpdateSourceFile(objUri, textChangedEvent); // DEBUG information RemoteConsole.Log("Udpated source file : " + objUri.LocalPath); foreach (var textChange in textChangedEvent.TextChanges) { RemoteConsole.Log(" - " + textChange.ToString()); } }
public override void OnDidChangeTextDocument(DidChangeTextDocumentParams parameters) { Uri objUri = new Uri(parameters.uri); if (objUri.IsFile) { string fileName = Path.GetFileName(objUri.LocalPath); var fileCompiler = typeCobolWorkspace.OpenedFileCompilers[fileName]; #region Convert text changes format from multiline range replacement to single line updates // THIS CONVERSION STILL NEEDS MORE WORK : much more complicated than you would think TextChangedEvent textChangedEvent = new TextChangedEvent(); foreach (var contentChange in parameters.contentChanges) { // Split the text updated into distinct lines string[] lineUpdates = null; bool replacementTextStartsWithNewLine = false; if (contentChange.text != null && contentChange.text.Length > 0) { replacementTextStartsWithNewLine = contentChange.text[0] == '\r' || contentChange.text[0] == '\n'; lineUpdates = contentChange.text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); } // Document cleared if (contentChange.range == null) { var textChange = new TextChange(TextChangeType.DocumentCleared, 0, null); textChangedEvent.TextChanges.Add(textChange); if (lineUpdates != null) { for (int i = 0; i < lineUpdates.Length; i++) { textChange = new TextChange(TextChangeType.LineInserted, i, new TextLineSnapshot(i, lineUpdates[i], null)); textChangedEvent.TextChanges.Add(textChange); } } } // Document updated else { // Check if the first line was inserted int firstLineIndex = contentChange.range.start.line; int firstLineChar = contentChange.range.start.character; if (replacementTextStartsWithNewLine) { firstLineIndex++; firstLineChar = 0; } // Check if the last line was deleted int lastLineIndex = contentChange.range.end.line; bool lastLineDeleted = false; if (contentChange.range.end.line > contentChange.range.start.line && contentChange.range.end.character == 0) { lastLineIndex--; lastLineDeleted = true; } if (!lastLineDeleted && contentChange.text.Length == 0) { lineUpdates = new string[0]; } // Get original lines text before change string originalFirstLineText = fileCompiler.CompilationResultsForProgram.CobolTextLines[contentChange.range.start.line].Text; string originalLastLineText = originalFirstLineText; if (lastLineIndex > firstLineIndex) { originalLastLineText = fileCompiler.CompilationResultsForProgram.CobolTextLines[lastLineIndex].Text; } // Text not modified at the beginning of the first replaced line string startOfFirstLine = null; if (firstLineChar > 0) { startOfFirstLine = originalFirstLineText.Substring(0, contentChange.range.start.character); } // Text not modified at the end of the last replaced line string endOfLastLine = null; if (!lastLineDeleted && contentChange.range.end.character < originalLastLineText.Length) { endOfLastLine = originalLastLineText.Substring(contentChange.range.end.character); } // Remove all the old lines for (int i = firstLineIndex; i <= lastLineIndex; i++) { var textChange = new TextChange(TextChangeType.LineRemoved, firstLineIndex, null); textChangedEvent.TextChanges.Add(textChange); } // Insert the updated lines if (!(startOfFirstLine == null && lineUpdates == null && endOfLastLine == null)) { int lineUpdatesCount = (lineUpdates != null && lineUpdates.Length > 0) ? lineUpdates.Length : 1; for (int i = 0; i < lineUpdatesCount; i++) { string newLine = (lineUpdates != null && lineUpdates.Length > 0) ? lineUpdates[i] : String.Empty; if (i == 0) { newLine = startOfFirstLine + newLine; } if (i == lineUpdatesCount - 1) { newLine = newLine + endOfLastLine; if (lastLineDeleted) { break; } } var textChange = new TextChange(TextChangeType.LineInserted, firstLineIndex + i, new TextLineSnapshot(firstLineIndex + i, newLine, null)); textChangedEvent.TextChanges.Add(textChange); } } } } #endregion // Update the source file with the computed text changes typeCobolWorkspace.UpdateSourceFile(fileName, textChangedEvent); // DEBUG information RemoteConsole.Log("Udpated source file : " + fileName); foreach (var textChange in textChangedEvent.TextChanges) { RemoteConsole.Log(" - " + textChange.ToString()); } } }
add => AddHandler(TextChangedEvent, value);
private void TextChanged(string text) { TextChangedEvent?.Invoke(text ?? string.Empty, _hiddenTextBox.SelectionStart, _hiddenTextBox.SelectionEnd, true); }
/// <summary> /// Update the text lines of the document after a text change event. /// NOT thread-safe : this method can only be called from the owner thread. /// </summary> public void UpdateTextLines(TextChangedEvent textChangedEvent) { // This method can only be called by the document owner thread if (documentOwnerThread == null) { documentOwnerThread = Thread.CurrentThread; } else { VerifyAccess(); } // Make sure we don't update the document while taking a snapshot DocumentChangedEvent <ICobolTextLine> documentChangedEvent = null; lock (lockObjectForDocumentLines) { // Start perf measurement PerfStatsForText.OnStartRefresh(); // Apply text changes to the compilation document IList <DocumentChange <ICobolTextLine> > documentChanges = new List <DocumentChange <ICobolTextLine> >(textChangedEvent.TextChanges.Count); foreach (TextChange textChange in textChangedEvent.TextChanges) { DocumentChange <ICobolTextLine> appliedChange = null; CodeElementsLine newLine = null; bool encounteredCodeElement; switch (textChange.Type) { case TextChangeType.DocumentCleared: compilationDocumentLines.Clear(); appliedChange = new DocumentChange <ICobolTextLine>(DocumentChangeType.DocumentCleared, 0, null); // Ignore all previous document changes : they are meaningless now that the document was completely cleared documentChanges.Clear(); break; case TextChangeType.LineInserted: newLine = CreateNewDocumentLine(textChange.NewLine, TextSourceInfo.ColumnsLayout); compilationDocumentLines.Insert(textChange.LineIndex, newLine); encounteredCodeElement = false; //Will allow to update allow line index without erasing all diagnostics after the first encountered line with CodeElements foreach (var lineToUpdate in compilationDocumentLines.Skip(textChange.LineIndex + 1)) //Loop on every line that appears after added line { //Remove generated diagnostics for the line below the inserted line. if (!encounteredCodeElement) { lineToUpdate.ResetDiagnostics(); //Reset diag when on the same zone } lineToUpdate.LineIndex++; lineToUpdate.UpdateDiagnositcsLine(); if (lineToUpdate.CodeElements != null) { encounteredCodeElement = true; } } appliedChange = new DocumentChange <ICobolTextLine>(DocumentChangeType.LineInserted, textChange.LineIndex, newLine); break; case TextChangeType.LineUpdated: newLine = CreateNewDocumentLine(textChange.NewLine, TextSourceInfo.ColumnsLayout); compilationDocumentLines[textChange.LineIndex] = newLine; // Check to see if this change can be merged with a previous one bool changeAlreadyApplied = false; foreach (DocumentChange <ICobolTextLine> documentChangeToAdjust in documentChanges) { if (documentChangeToAdjust.LineIndex == textChange.LineIndex) { changeAlreadyApplied = true; break; } } if (!changeAlreadyApplied) { appliedChange = new DocumentChange <ICobolTextLine>(DocumentChangeType.LineUpdated, textChange.LineIndex, newLine); } // Line indexes are not impacted break; case TextChangeType.LineRemoved: compilationDocumentLines.RemoveAt(textChange.LineIndex); encounteredCodeElement = false; //Will allow to update allow line index without erasing all diagnostics after the first encountered line with CodeElements foreach (var lineToUpdate in compilationDocumentLines.Skip(textChange.LineIndex)) //Loop on every line that appears after deleted line { //Remove generated diagnostics for the line below the deleted line. if (!encounteredCodeElement) { lineToUpdate.ResetDiagnostics(); } lineToUpdate.LineIndex--; lineToUpdate.UpdateDiagnositcsLine(); if (lineToUpdate.CodeElements != null) { encounteredCodeElement = true; } } appliedChange = new DocumentChange <ICobolTextLine>(DocumentChangeType.LineRemoved, textChange.LineIndex, null); // Recompute the line indexes of all the changes prevously applied IList <DocumentChange <ICobolTextLine> > documentChangesToRemove = null; foreach (DocumentChange <ICobolTextLine> documentChangeToAdjust in documentChanges) { if (documentChangeToAdjust.LineIndex > textChange.LineIndex) { documentChangeToAdjust.LineIndex = documentChangeToAdjust.LineIndex - 1; } else if (documentChangeToAdjust.LineIndex == textChange.LineIndex) { if (documentChangesToRemove == null) { documentChangesToRemove = new List <DocumentChange <ICobolTextLine> >(1); } documentChangesToRemove.Add(documentChangeToAdjust); } } // Ignore all previous changes applied to a line now removed if (documentChangesToRemove != null) { foreach (DocumentChange <ICobolTextLine> documentChangeToRemove in documentChangesToRemove) { documentChanges.Remove(documentChangeToRemove); } } break; } if (appliedChange != null) { documentChanges.Add(appliedChange); } } // Create a new version of the document to track these changes currentTextLinesVersion.changes = documentChanges; currentTextLinesVersion.next = new DocumentVersion <ICobolTextLine>(currentTextLinesVersion); // Prepare an event to signal document change to all listeners documentChangedEvent = new DocumentChangedEvent <ICobolTextLine>(currentTextLinesVersion, currentTextLinesVersion.next); currentTextLinesVersion = currentTextLinesVersion.next; // Stop perf measurement PerfStatsForText.OnStopRefresh(); } // Send events to all listeners EventHandler <DocumentChangedEvent <ICobolTextLine> > textLinesChanged = TextLinesChanged; // avoid race condition if (textLinesChanged != null) { textLinesChanged(this, documentChangedEvent); } }
remove => RemoveHandler(TextChangedEvent, value);
public void OnTextChanged(object sender, TextChangedEvent textChangedEvent) { LastTextChangedEvent = textChangedEvent; }
/// <summary> /// Handles the text box body changing. /// </summary> private void OnTextBoxBodyChanged(object sender, TextChangedEvent evt) { double val; if (double.TryParse(_textBox.Body, out val)) { Value = val; _textBox.TextColor = _goodColor; } else { _textBox.TextColor = _badColor; } }