protected internal override void DrawBackground(Context cr, Xwt.Rectangle area, DocumentLine line, int lineNumber, double x, double y, double height) { cr.Save(); cr.SetColor(Colors.LightGray); cr.Rectangle(x, y, Width, height + 1); cr.Fill(); cr.Restore(); }
protected internal override void Draw(Context cr, Xwt.Rectangle area, DocumentLine line, int lineNumber, double x, double y, double height) { if (lineNumber <= editor.Document.LineCount) { TextLayout layout; if (!layoutDict.TryGetValue(lineNumber, out layout)) { layout = new TextLayout(); layout.Font = editor.Options.EditorFont; layout.Text = lineNumber.ToString(); layoutDict[lineNumber] = layout; } cr.SetColor(Colors.Black); cr.DrawTextLayout(layout, x + leftPadding, y); } }
public override void Analyze (TextDocument doc, DocumentLine line, Chunk startChunk, int startOffset, int endOffset) { if (endOffset <= startOffset || startOffset >= doc.TextLength || inUpdate) return; inUpdate = true; try { string text = doc.GetTextAt (startOffset, System.Math.Min (endOffset, doc.TextLength) - startOffset); int startColumn = startOffset - line.Offset; /*var markers = new List <UrlMarker> (line.Markers.Where (m => m is UrlMarker).Cast<UrlMarker> ()); markers.ForEach (m => doc.RemoveMarker (m, false)); foreach (System.Text.RegularExpressions.Match m in UrlRegex.Matches (text)) { doc.AddMarker (line, new UrlMarker (doc, line, m.Value, UrlType.Url, syntax, startColumn + m.Index, startColumn + m.Index + m.Length), false); } foreach (System.Text.RegularExpressions.Match m in MailRegex.Matches (text)) { doc.AddMarker (line, new UrlMarker (doc, line, m.Value, UrlType.Email, syntax, startColumn + m.Index, startColumn + m.Index + m.Length), false); }*/ } finally { inUpdate = false; } }
private void Button_Click(object sender, RoutedEventArgs e) { if (scProduct.Product == null) { Util.ShowError("Please select a Product."); return; } if (cboUnit.SelectedItem == null) { Util.ShowError("Please select a Unit."); return; } if (string.IsNullOrEmpty(txtPrecio.Text)) return; if (string.IsNullOrEmpty(txtQty.Text)) return; double price, qty, qtycancel, qtybo; if (!Double.TryParse(txtPrecio.Text, out price)) { Util.ShowError("Please enter a valid price"); return; } if (!Double.TryParse(txtQty.Text, out qty)) { Util.ShowError("Please enter a valid Quantity."); return; } /*if (!Double.TryParse(txtCancel.Text, out qtycancel)) { Util.ShowError("Please enter a valid Quantity to Cancel."); return; } if (!Double.TryParse(txtBO.Text, out qtybo)) { Util.ShowError("Please enter a valid Quantity to Backorder."); return; }*/ if (price < 0) { Util.ShowError("Please enter a valid price"); return; } if (qty <= 0/* || qtycancel < 0 || qtybo < 0 */) { Util.ShowError("Please enter a valid quantities."); return; } /*if (qty - qtycancel - qtybo < 0) { Util.ShowError("Wrong Quantity balance. Quantity - QtyCancel - QtyBackOrder must be greather than zero."); return; }*/ string resultMsg = ""; //Add Update the Document Line if (CurDocLine == null) CurDocLine = new DocumentLine { }; try { CurDocLine.Unit = cboUnit.SelectedItem as Unit; CurDocLine.Product = scProduct.Product; CurDocLine.Quantity = qty; CurDocLine.UnitPrice = price; CurDocLine.QtyCancel = double.Parse(txtCancel.Text); CurDocLine.QtyBackOrder = double.Parse(txtBO.Text); CurDocLine.LineDescription = txtLineDescription.Text; CurDocLine.Document = CurDocument; CurDocLine.ModifiedBy = App.curUser.UserName; CurDocLine.CreatedBy = App.curUser.UserName; CurDocLine.CreationDate = DateTime.Now; //Preguntar si estos valores estan correctos CurDocLine.LineNumber = 0; CurDocLine.LineStatus = CurDocLine.Document.DocStatus; CurDocLine.IsDebit = false; CurDocLine.QtyInvoiced = 0; CurDocLine.QtyAllocated = 0; CurDocLine.Location = new Location { LocationID = CurDocLine.Document.Location.LocationID }; CurDocLine.QtyPending = 0; CurDocLine.Sequence = 0; CurDocLine = service.SaveDocumentLine(CurDocLine); //Refrescar el Padre. ((DocumentManagerPresenter)PresenterParent).ReloadDocumentLines(); ResetPanel(); Util.ShowMessage("Process Completed." + resultMsg); } catch (Exception ex) { Util.ShowError("Error creating Line.\n" + ex.Message); } }
public virtual ChunkParser CreateChunkParser (SpanParser spanParser, ColorScheme style, DocumentLine line) { return new ChunkParser (this, spanParser, style, line); }
private void Button_Click(object sender, RoutedEventArgs e) { if (scProduct.Product == null) { Util.ShowError("Please select a Product."); return; } if (cboUnit.SelectedItem == null) { Util.ShowError("Please select a Unit."); return; } if (string.IsNullOrEmpty(txtQty.Text)) { return; } double qty, qtycancel, qtybo; if (!Double.TryParse(txtQty.Text, out qty)) { Util.ShowError("Please enter a valid Quantity."); return; } if (!Double.TryParse(txtCancel.Text, out qtycancel)) { Util.ShowError("Please enter a valid Quantity to Cancel."); return; } if (!Double.TryParse(txtBO.Text, out qtybo)) { Util.ShowError("Please enter a valid Quantity to Backorder."); return; } if (qty <= 0 || qtycancel < 0 || qtybo < 0 ) { Util.ShowError("Please enter a valid quantities."); return; } if (qty - qtycancel - qtybo < 0) { Util.ShowError("Wrong Quantity balance. Quantity - QtyCancel - QtyBackOrder must be greather than zero."); return; } string resultMsg = ""; //Add Update the Document Line if (CurDocLine == null) CurDocLine = new DocumentLine { }; try { CurDocLine.Unit = cboUnit.SelectedItem as Unit; CurDocLine.Product = scProduct.Product; CurDocLine.Quantity = qty; CurDocLine.QtyCancel = double.Parse(txtCancel.Text); CurDocLine.QtyBackOrder = double.Parse(txtBO.Text); CurDocLine.LineDescription = txtNotes.Text; CurDocLine.Location = App.curLocation; CurDocLine.Document = CurDocument; CurDocLine.ModifiedBy = App.curUser.UserName; //Si es un Merged Order y es una linea nueva debe adicionarle el link Document if (CurDocLine.Document.DocType.DocTypeID == SDocType.MergedSalesOrder && CurDocLine.LineID == 0) { string oriDoc = service.GetDocumentLine(new DocumentLine { Document = new Document { DocID = CurDocLine.Document.DocID }, LineStatus = new Status { StatusID = DocStatus.New } }).First().LinkDocNumber; CurDocLine.LinkDocNumber = oriDoc; resultMsg = "\nLine added also in document " + oriDoc; } CurDocLine = service.SaveUpdateDocumentLine(CurDocLine, false); //Refrescar el Padre. if (PresenterParent.GetType().Name.Contains("ShippingPresenter")) ((ShippingPresenter)PresenterParent).ReloadDocumentLines(); else if (PresenterParent.GetType().Name.Contains("ShipperMngrPresenter")) ((ShipperMngrPresenter)PresenterParent).UpdateLines(CurDocLine); ResetPanel(); ((Popup)this.Parent).IsOpen = false; Util.ShowMessage("Process Completed." + resultMsg); } catch (Exception ex) { Util.ShowError("Error creating Line.\n" + ex.Message); } }
/// <summary> /// Checks to see if a text location is a matching word. /// </summary> /// <param name="Txt">The text being searched for.</param> /// <param name="Result">Receives the result if the text location is a matching word.</param> /// <param name="bMatchWord">True if an entire word is to be matched.</param> /// <param name="bFound">Set to true if a matching word is found.</param> /// <param name="bIsWord">True if <paramref name="Txt"/> is a valid word.</param> /// <param name="CurLineIndex">The index of the current line.</param> /// <param name="CurLineBldr">The text of the current line.</param> /// <param name="ColumnIndex">The character index within the line of text where the matching will begin.</param> /// <param name="Index">The index of a match within the range of searchable characters for the current line. The true line index is <paramref name="ColumnIndex"/> + <paramref name="Index"/>.</param> private static void CheckForWholeWord(string Txt, ref FindResult Result, bool bMatchWord, ref bool bFound, bool bIsWord, int CurLineIndex, DocumentLine CurLine, int ColumnIndex, int Index) { int FinalCharIndex = ColumnIndex + Txt.Length; if(bMatchWord && bIsWord) { if((FinalCharIndex >= CurLine.Length || !IsWordCharacter(CurLine[FinalCharIndex])) && (ColumnIndex == 0 || !IsWordCharacter(CurLine[ColumnIndex - 1]))) { bFound = true; } } else { bFound = true; } if(bFound) { Result.Line = CurLineIndex; Result.Column = ColumnIndex; Result.Length = Txt.Length; } }
public Boolean PickProduct(DocumentLine line, Label sourceLocation, Node node, Label packageLabel) { try { SetService(); return SerClient.PickProduct(line, sourceLocation, node, packageLabel, App.curUser, null); } finally { SerClient.Close(); if (SerClient.State == CommunicationState.Faulted) SerClient.Abort(); } }
public DocumentLine SaveAdjustmentTransaction(DocumentLine data, Label label) { try { SetService(); return SerClient.SaveAdjustmentTransaction(data, label, true); } finally { SerClient.Close(); if (SerClient.State == CommunicationState.Faulted) SerClient.Abort(); } }
bool EndsWithContinuation(Span span, DocumentLine line) { return(!span.StopAtEol || span.StopAtEol && !string.IsNullOrEmpty(span.Continuation) && line != null && doc.GetTextAt(line).Trim().EndsWith(span.Continuation, StringComparison.Ordinal)); }
protected override bool OnIMProcessedKeyPressEvent(Gdk.Key key, uint ch, Gdk.ModifierType state) { bool result = true; if (key == Gdk.Key.Escape) { bool b = Extension != null?ExtensionKeyPress(key, ch, state) : base.OnIMProcessedKeyPressEvent(key, ch, state); if (b) { view.SourceEditorWidget.RemoveSearchWidget(); return(true); } return(false); } if (Document == null) { return(true); } bool inStringOrComment = false; DocumentLine line = Document.GetLine(Caret.Line); if (line == null) { return(true); } // string escape = "\""; var stack = line.StartSpan.Clone(); var sm = Document.SyntaxMode as SyntaxMode; if (sm != null) { Mono.TextEditor.Highlighting.SyntaxModeService.ScanSpans(Document, sm, sm, stack, line.Offset, Caret.Offset); } string spanColor = null; foreach (Span span in stack) { if (string.IsNullOrEmpty(span.Color)) { continue; } if (span.Color.StartsWith("String", StringComparison.Ordinal) || span.Color.StartsWith("Comment", StringComparison.Ordinal)) { spanColor = span.Color; inStringOrComment = true; break; } } // insert template when space is typed (currently disabled - it's annoying). bool templateInserted = false; //!inStringOrComment && (key == Gdk.Key.space) && DoInsertTemplate (); bool returnBetweenBraces = key == Gdk.Key.Return && (state & (Gdk.ModifierType.ControlMask | Gdk.ModifierType.ShiftMask)) == Gdk.ModifierType.None && Caret.Offset > 0 && Caret.Offset < Document.TextLength && Document.GetCharAt(Caret.Offset - 1) == '{' && Document.GetCharAt(Caret.Offset) == '}' && !inStringOrComment; // int initialOffset = Caret.Offset; const string openBrackets = "{[('\""; const string closingBrackets = "}])'\""; int braceIndex = openBrackets.IndexOf((char)ch); var skipChars = GetTextEditorData().SkipChars; var skipChar = skipChars.Find(sc => sc.Char == (char)ch && sc.Offset == Caret.Offset); // bool startedAtomicOperation = false; // special handling for escape chars inside ' and " if (Caret.Offset > 0) { char charBefore = Document.GetCharAt(Caret.Offset - 1); if (ch == '"') { if (!inStringOrComment && charBefore == '"' || inStringOrComment && spanColor == "String" && charBefore == '\\') { skipChar = null; braceIndex = -1; } } } char insertionChar = '\0'; bool insertMatchingBracket = false; IDisposable undoGroup = null; if (skipChar == null && Options.AutoInsertMatchingBracket && braceIndex >= 0 && !IsSomethingSelected) { if (!inStringOrComment) { char closingBrace = closingBrackets [braceIndex]; char openingBrace = openBrackets [braceIndex]; int count = 0; foreach (char curCh in TextWithoutCommentsAndStrings) { if (curCh == openingBrace) { count++; } else if (curCh == closingBrace) { count--; } } if (count >= 0) { insertMatchingBracket = true; insertionChar = closingBrace; } } else { char charBefore = Document.GetCharAt(Caret.Offset - 1); if (!inStringOrComment && ch == '"' && charBefore != '\\') { insertMatchingBracket = true; insertionChar = '"'; } } } //Console.WriteLine (Caret.Offset + "/" + insOff); if (insertMatchingBracket) { undoGroup = Document.OpenUndoGroup(); } var oldMode = Caret.IsInInsertMode; if (skipChar != null) { Caret.IsInInsertMode = false; skipChars.Remove(skipChar); } if (Extension != null) { if (ExtensionKeyPress(key, ch, state)) { result = base.OnIMProcessedKeyPressEvent(key, ch, state); } if (returnBetweenBraces) { HitReturn(); } } else { result = base.OnIMProcessedKeyPressEvent(key, ch, state); if (returnBetweenBraces) { HitReturn(); } } if (skipChar != null) { Caret.IsInInsertMode = oldMode; } if (insertMatchingBracket) { GetTextEditorData().EnsureCaretIsNotVirtual(); int offset = Caret.Offset; Caret.AutoUpdatePosition = false; Insert(offset, insertionChar.ToString()); Caret.AutoUpdatePosition = true; GetTextEditorData().SetSkipChar(offset, insertionChar); undoGroup.Dispose(); } return(templateInserted || result); }
void ResultTextDataFunc(TreeViewColumn column, CellRenderer cell, TreeModel model, TreeIter iter) { if (TreeIter.Zero.Equals(iter)) { return; } var textRenderer = (CellRendererText)cell; var searchResult = (SearchResult)store.GetValue(iter, SearchResultColumn); if (searchResult == null || searchResult.Offset < 0) { textRenderer.Markup = "Invalid search result"; return; } string textMarkup = searchResult.TextMarkup; if (textMarkup == null) { var doc = GetDocument(searchResult); if (doc == null) { textMarkup = "Can't create document for:" + searchResult.FileName; goto end; } bool isSelected = treeviewSearchResults.Selection.IterIsSelected(iter); if (searchResult.Markup == null) { if (searchResult.LineNumber <= 0) { searchResult.LineNumber = doc.OffsetToLineNumber(searchResult.Offset); } DocumentLine line = doc.GetLine(searchResult.LineNumber); if (line == null) { textMarkup = "Invalid line number " + searchResult.LineNumber + " from offset: " + searchResult.Offset; goto end; } int indent = line.GetIndentation(doc).Length; var data = new Mono.TextEditor.TextEditorData(doc); data.ColorStyle = highlightStyle; var lineText = doc.GetTextAt(line.Offset + indent, line.Length - indent); int col = searchResult.Offset - line.Offset - indent; // search result contained part of the indent. if (col + searchResult.Length < lineText.Length) { lineText = doc.GetTextAt(line.Offset, line.Length); } var markup = doc.SyntaxMode != null? data.GetMarkup(line.Offset + indent, line.Length - indent, true, !isSelected, false) : GLib.Markup.EscapeText(lineText); searchResult.Markup = AdjustColors(markup.Replace("\t", new string (' ', TextEditorOptions.DefaultOptions.TabSize))); if (col >= 0) { uint start; uint end; try { start = (uint)TextViewMargin.TranslateIndexToUTF8(lineText, col); end = (uint)TextViewMargin.TranslateIndexToUTF8(lineText, Math.Min(lineText.Length, col + searchResult.Length)); } catch (Exception e) { LoggingService.LogError("Exception while translating index to utf8 (column was:" + col + " search result length:" + searchResult.Length + " line text:" + lineText + ")", e); return; } searchResult.StartIndex = start; searchResult.EndIndex = end; } } try { textMarkup = searchResult.Markup; if (!isSelected) { var searchColor = searchResult.GetBackgroundMarkerColor(highlightStyle).Color; double b1 = Mono.TextEditor.HslColor.Brightness(searchColor); double b2 = Mono.TextEditor.HslColor.Brightness(AdjustColor(Style.Base(StateType.Normal), (Mono.TextEditor.HslColor)highlightStyle.PlainText.Foreground)); double delta = Math.Abs(b1 - b2); if (delta < 0.1) { Mono.TextEditor.HslColor color1 = highlightStyle.SearchResult.Color; if (color1.L + 0.5 > 1.0) { color1.L -= 0.5; } else { color1.L += 0.5; } searchColor = color1; } if (searchResult.StartIndex != searchResult.EndIndex) { textMarkup = PangoHelper.ColorMarkupBackground(textMarkup, (int)searchResult.StartIndex, (int)searchResult.EndIndex, searchColor); } } } catch (Exception e) { LoggingService.LogError("Error whil setting the text renderer markup to: " + searchResult.Markup, e); } end: searchResult.TextMarkup = textMarkup; } textRenderer.Markup = textMarkup; }
string GetTooltipTextForCollapsedSection(ToolTipRequestEventArgs args, FoldingSection foldingSection) { // This fixes SD-1394: // Each line is checked for leading indentation whitespaces. If // a line has the same or more indentation than the first line, // it is reduced. If a line is less indented than the first line // the indentation is removed completely. // // See the following example: // line 1 // line 2 // line 3 // line 4 // // is reduced to: // line 1 // line 2 // line 3 // line 4 const int maxLineCount = 15; TextDocument document = (TextDocument)args.Editor.Document; int startOffset = foldingSection.StartOffset; int endOffset = foldingSection.EndOffset; DocumentLine startLine = document.GetLineByOffset(startOffset); DocumentLine endLine = document.GetLineByOffset(endOffset); StringBuilder builder = new StringBuilder(); DocumentLine current = startLine; ISegment startIndent = TextUtilities.GetLeadingWhitespace(document, startLine); int lineCount = 0; while (current != endLine.NextLine && lineCount < maxLineCount) { ISegment currentIndent = TextUtilities.GetLeadingWhitespace(document, current); if (current == startLine && current == endLine) { builder.Append(document.GetText(startOffset, endOffset - startOffset)); } else if (current == startLine) { if (current.EndOffset - startOffset > 0) { builder.AppendLine(document.GetText(startOffset, current.EndOffset - startOffset).TrimStart()); } } else if (current == endLine) { if (startIndent.Length <= currentIndent.Length) { builder.Append(document.GetText(current.Offset + startIndent.Length, endOffset - current.Offset - startIndent.Length)); } else { builder.Append(document.GetText(current.Offset + currentIndent.Length, endOffset - current.Offset - currentIndent.Length)); } } else { if (startIndent.Length <= currentIndent.Length) { builder.AppendLine(document.GetText(current.Offset + startIndent.Length, current.Length - startIndent.Length)); } else { builder.AppendLine(document.GetText(current.Offset + currentIndent.Length, current.Length - currentIndent.Length)); } } current = current.NextLine; lineCount++; } if (current != endLine.NextLine) { builder.Append("..."); } return(builder.ToString()); }
private void _textArea_TextEntering(object sender, TextCompositionEventArgs e) { try { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0]) && e.Text[0] != '_' && e.Text[0] != ' ') { string word = AvalonLoader.GetWholeWordAdv(_textEditor.TextArea.Document, _textEditor); var strategy = new RegexSearchStrategy(new Regex(word), true); if ((e.Text[0] != '\t' || e.Text[0] != '\n') && strategy.FindAll(_textEditor.Document, 0, _textEditor.Document.TextLength).Count() > 1) { _completionWindow.Close(); return; } string line = _getText(_textEditor.TextArea.Caret.Line); if (line.IndexOf('#') > -1) { _completionWindow.Close(); return; } _completionWindow.CompletionList.RequestInsertion(e); } else if (e.Text[0] == ' ') { _completionWindow.Close(); } } if (e.Text.Length > 0 && _completionWindow == null) { if (e.Text[0] == '\n') { int currentLine = _textEditor.TextArea.Caret.Line; DocumentLine docLine = _getLine(currentLine); string line = _getText(currentLine); int currentIndent = LineHelper.GetIndent(line); if (line.EndsWith(":") && _textEditor.CaretOffset >= docLine.EndOffset) { currentIndent++; } if (_textEditor.LineCount == currentLine) { _textEditor.Document.Insert(_textEditor.Document.TextLength, "\n" + LineHelper.GenerateIndent(currentIndent)); _textEditor.CaretOffset = _textEditor.Text.Length; } else { var position = _textEditor.CaretOffset; _textEditor.Document.Insert(_textEditor.CaretOffset, "\n" + LineHelper.GenerateIndent(currentIndent)); _textEditor.CaretOffset = position + ("\n" + LineHelper.GenerateIndent(currentIndent)).Length; } _textEditor.TextArea.Caret.BringCaretToView(); e.Handled = true; } } } catch { } }
/// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line);
protected void OnPaste(object target, ExecutedRoutedEventArgs args) { if (target != textEditor.textArea) { return; } TextArea textArea = textEditor.textArea; if (textArea != null && textArea.Document != null) { Debug.WriteLine(Clipboard.GetText(TextDataFormat.Html)); // convert text back to correct newlines for this document string newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); string text = TextUtilities.NormalizeNewLines(Clipboard.GetText(), newLine); string[] commands = text.Split(new String[] { newLine }, StringSplitOptions.None); string scriptText = ""; if (commands.Length > 1) { text = newLine; foreach (string command in commands) { text += "... " + command + newLine; scriptText += command.Replace("\t", " ") + newLine; } } if (!string.IsNullOrEmpty(text)) { bool fullLine = textArea.Options.CutCopyWholeLine && Clipboard.ContainsData(LineSelectedType); bool rectangular = Clipboard.ContainsData(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) { if (!RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, false)) { textEditor.Write(text, false); } } else { textEditor.Write(text, false); } } textArea.Caret.BringCaretToView(); args.Handled = true; if (commands.Length > 1) { lock (this.scriptText) { this.scriptText = scriptText; } dispatcher.BeginInvoke(new Action(delegate() { ExecuteStatements(); })); } } }
public void DeleteDocumentLine(DocumentLine data) { try { SetService(); SerClient.DeleteDocumentLine(data); } finally { SerClient.Close(); if (SerClient.State == CommunicationState.Faulted) SerClient.Abort(); } }
private void loliScriptEditor_KeyDown(object sender, KeyEventArgs e) { if (Keyboard.Modifiers == ModifierKeys.Control) { if (e.Key == System.Windows.Input.Key.S) { vm.LS.Script = loliScriptEditor.Text; OnSaveConfig(); } else if (e.Key == System.Windows.Input.Key.F) { Button_Click(null, null); } } if (SB.OBSettings.General.DisableSyntaxHelper) { return; } DocumentLine line = loliScriptEditor.Document.GetLineByOffset(loliScriptEditor.CaretOffset); var blockLine = loliScriptEditor.Document.GetText(line.Offset, line.Length); // Scan for the first non-indented line while (blockLine.StartsWith(" ") || blockLine.StartsWith("\t")) { try { line = line.PreviousLine; blockLine = loliScriptEditor.Document.GetText(line.Offset, line.Length); } catch { break; } } if (BlockParser.IsBlock(blockLine)) { var blockName = BlockParser.GetBlockType(blockLine); var caret = loliScriptEditor.TextArea.Caret.CalculateCaretRectangle(); toolTip.HorizontalOffset = caret.Right; toolTip.VerticalOffset = caret.Bottom; XmlNode node = null; for (int i = 0; i < syntaxHelperItems.Count; i++) { if (syntaxHelperItems[i].Attributes["name"].Value.ToUpper() == blockName.ToUpper()) { node = syntaxHelperItems[i]; break; } } if (node == null) { return; } toolTipEditor.Text = node.InnerText; toolTip.IsOpen = true; } else { toolTip.IsOpen = false; } }
public DocumentLine ChangeProductUbication(Label labelSource, DocumentLine changeLine, Label labelDest) { try { SetService(); return SerClient.ChangeProductUbication(labelSource, changeLine, labelDest,""); } finally { SerClient.Close(); if (SerClient.State == CommunicationState.Faulted) SerClient.Abort(); } }
public async Task ExtractLayoutFromFileAsync() { string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; DocumentAnalysisClient client = new DocumentAnalysisClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); #region Snippet:FormRecognizerExtractLayoutFromFileAsync #if SNIPPET string filePath = "<filePath>"; #else string filePath = DocumentAnalysisTestEnvironment.CreatePath("Form_1.jpg"); #endif using var stream = new FileStream(filePath, FileMode.Open); AnalyzeDocumentOperation operation = await client.StartAnalyzeDocumentAsync("prebuilt-layout", stream); await operation.WaitForCompletionAsync(); AnalyzeResult result = operation.Value; foreach (DocumentPage page in result.Pages) { Console.WriteLine($"Document Page {page.PageNumber} has {page.Lines.Count} line(s), {page.Words.Count} word(s),"); Console.WriteLine($"and {page.SelectionMarks.Count} selection mark(s)."); for (int i = 0; i < page.Lines.Count; i++) { DocumentLine line = page.Lines[i]; Console.WriteLine($" Line {i} has content: '{line.Content}'."); Console.WriteLine($" Its bounding box is:"); Console.WriteLine($" Upper left => X: {line.BoundingBox[0].X}, Y= {line.BoundingBox[0].Y}"); Console.WriteLine($" Upper right => X: {line.BoundingBox[1].X}, Y= {line.BoundingBox[1].Y}"); Console.WriteLine($" Lower right => X: {line.BoundingBox[2].X}, Y= {line.BoundingBox[2].Y}"); Console.WriteLine($" Lower left => X: {line.BoundingBox[3].X}, Y= {line.BoundingBox[3].Y}"); } for (int i = 0; i < page.SelectionMarks.Count; i++) { DocumentSelectionMark selectionMark = page.SelectionMarks[i]; Console.WriteLine($" Selection Mark {i} is {selectionMark.State}."); Console.WriteLine($" Its bounding box is:"); Console.WriteLine($" Upper left => X: {selectionMark.BoundingBox[0].X}, Y= {selectionMark.BoundingBox[0].Y}"); Console.WriteLine($" Upper right => X: {selectionMark.BoundingBox[1].X}, Y= {selectionMark.BoundingBox[1].Y}"); Console.WriteLine($" Lower right => X: {selectionMark.BoundingBox[2].X}, Y= {selectionMark.BoundingBox[2].Y}"); Console.WriteLine($" Lower left => X: {selectionMark.BoundingBox[3].X}, Y= {selectionMark.BoundingBox[3].Y}"); } } foreach (DocumentStyle style in result.Styles) { // Check the style and style confidence to see if text is handwritten. // Note that value '0.8' is used as an example. bool isHandwritten = style.IsHandwritten.HasValue && style.IsHandwritten == true; if (isHandwritten && style.Confidence > 0.8) { Console.WriteLine($"Handwritten content found:"); foreach (DocumentSpan span in style.Spans) { Console.WriteLine($" Content: {result.Content.Substring(span.Offset, span.Length)}"); } } } Console.WriteLine("The following tables were extracted:"); for (int i = 0; i < result.Tables.Count; i++) { DocumentTable table = result.Tables[i]; Console.WriteLine($" Table {i} has {table.RowCount} rows and {table.ColumnCount} columns."); foreach (DocumentTableCell cell in table.Cells) { Console.WriteLine($" Cell ({cell.RowIndex}, {cell.ColumnIndex}) has kind '{cell.Kind}' and content: '{cell.Content}'."); } } #endregion }
internal DocumentLine SaveUpdateDocumentLine(DocumentLine docLine, bool removeLine) { try { SetService(); return SerClient.SaveUpdateDocumentLine(docLine, removeLine); } finally { SerClient.Close(); if (SerClient.State == CommunicationState.Faulted) SerClient.Abort(); } }
//copied from EditMode.cs, with the undo stack handling code removed public void InsertChar(char ch) { var data = Editor.Data; var doc = Editor.Document; var caret = Editor.Data.Caret; if (!data.CanEdit(data.Caret.Line)) { return; } if (Editor.Editor != null) { Editor.Editor.HideMouseCursor(); } data.DeleteSelectedText(data.IsSomethingSelected ? data.MainSelection.SelectionMode != SelectionMode.Block : true); if (!char.IsControl(ch) && data.CanEdit(caret.Line)) { DocumentLine line = doc.GetLine(caret.Line); if (caret.IsInInsertMode || caret.Column >= line.Length + 1) { string text; if (data.HasIndentationTracker) { text = caret.Column > line.Length + 1 ? data.GetIndentationString(caret.Location) + ch.ToString() : ch.ToString(); } else { text = ch.ToString(); } if (data.IsSomethingSelected && data.MainSelection.SelectionMode == SelectionMode.Block) { int length = 0; for (int lineNumber = data.MainSelection.MinLine; lineNumber <= data.MainSelection.MaxLine; lineNumber++) { length = data.Insert(doc.GetLine(lineNumber).Offset + caret.Column, text); } caret.PreserveSelection = true; caret.Column += length - 1; data.MainSelection = data.MainSelection.WithRange( new DocumentLocation(data.MainSelection.Anchor.Line, caret.Column + 1), new DocumentLocation(data.MainSelection.Lead.Line, caret.Column + 1) ); doc.CommitMultipleLineUpdate(data.MainSelection.MinLine, data.MainSelection.MaxLine); } else { int length = data.Insert(caret.Offset, text); caret.Column += length - 1; } } else { data.Replace(caret.Offset, 1, ch.ToString()); } caret.Column++; if (caret.PreserveSelection) { caret.PreserveSelection = false; } } if (data.IsSomethingSelected && data.MainSelection.SelectionMode == SelectionMode.Block) { data.Caret.PreserveSelection = false; } }
internal ReadOnlyDocumentLine(DocumentLine DocLine) { mDocLine = DocLine; }
public BackgroundRenderer(DocumentLine line) { _line = line; }
public virtual IEnumerable<Chunk> GetChunks (ColorScheme style, DocumentLine line, int offset, int length) { SpanParser spanParser = CreateSpanParser (line, null); ChunkParser chunkParser = CreateChunkParser (spanParser, style, line); Chunk result = chunkParser.GetChunks (chunkParser.lineOffset, line.Length); if (SemanticRules != null) { foreach (SemanticRule sematicRule in SemanticRules) { sematicRule.Analyze (doc, line, result, offset, offset + length); } } if (result != null) { // crop to begin if (result.Offset < offset) { while (result != null && result.EndOffset < offset) { result = result.Next; } if (result != null) { int endOffset = result.EndOffset; result.Offset = offset; result.Length = endOffset - offset; } } } while (result != null) { // crop to end if (result.EndOffset >= offset + length) { result.Length = offset + length - result.Offset; result.Next = null; if (result.Length < 0) { result.Length = 0; yield break; } } yield return result; result = result.Next; } }
public async Task AnalyzePrebuiltDocumentFromUriAsync() { string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; DocumentAnalysisClient client = new DocumentAnalysisClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); #region Snippet:FormRecognizerAnalyzePrebuiltDocumentFromUriAsync #if SNIPPET string fileUri = "<fileUri>"; #else Uri fileUri = DocumentAnalysisTestEnvironment.CreateUri("Form_1.jpg"); #endif AnalyzeDocumentOperation operation = await client.StartAnalyzeDocumentFromUriAsync("prebuilt-document", fileUri); await operation.WaitForCompletionAsync(); AnalyzeResult result = operation.Value; Console.WriteLine("Detected key-value pairs:"); foreach (DocumentKeyValuePair kvp in result.KeyValuePairs) { if (kvp.Value == null) { Console.WriteLine($" Found key with no value: '{kvp.Key.Content}'"); } else { Console.WriteLine($" Found key-value pair: '{kvp.Key.Content}' and '{kvp.Value.Content}'"); } } Console.WriteLine("Detected entities:"); foreach (DocumentEntity entity in result.Entities) { if (entity.SubCategory == null) { Console.WriteLine($" Found entity '{entity.Content}' with category '{entity.Category}'."); } else { Console.WriteLine($" Found entity '{entity.Content}' with category '{entity.Category}' and sub-category '{entity.SubCategory}'."); } } foreach (DocumentPage page in result.Pages) { Console.WriteLine($"Document Page {page.PageNumber} has {page.Lines.Count} line(s), {page.Words.Count} word(s),"); Console.WriteLine($"and {page.SelectionMarks.Count} selection mark(s)."); for (int i = 0; i < page.Lines.Count; i++) { DocumentLine line = page.Lines[i]; Console.WriteLine($" Line {i} has content: '{line.Content}'."); Console.WriteLine($" Its bounding box is:"); Console.WriteLine($" Upper left => X: {line.BoundingBox[0].X}, Y= {line.BoundingBox[0].Y}"); Console.WriteLine($" Upper right => X: {line.BoundingBox[1].X}, Y= {line.BoundingBox[1].Y}"); Console.WriteLine($" Lower right => X: {line.BoundingBox[2].X}, Y= {line.BoundingBox[2].Y}"); Console.WriteLine($" Lower left => X: {line.BoundingBox[3].X}, Y= {line.BoundingBox[3].Y}"); } for (int i = 0; i < page.SelectionMarks.Count; i++) { DocumentSelectionMark selectionMark = page.SelectionMarks[i]; Console.WriteLine($" Selection Mark {i} is {selectionMark.State}."); Console.WriteLine($" Its bounding box is:"); Console.WriteLine($" Upper left => X: {selectionMark.BoundingBox[0].X}, Y= {selectionMark.BoundingBox[0].Y}"); Console.WriteLine($" Upper right => X: {selectionMark.BoundingBox[1].X}, Y= {selectionMark.BoundingBox[1].Y}"); Console.WriteLine($" Lower right => X: {selectionMark.BoundingBox[2].X}, Y= {selectionMark.BoundingBox[2].Y}"); Console.WriteLine($" Lower left => X: {selectionMark.BoundingBox[3].X}, Y= {selectionMark.BoundingBox[3].Y}"); } } foreach (DocumentStyle style in result.Styles) { // Check the style and style confidence to see if text is handwritten. // Note that value '0.8' is used as an example. bool isHandwritten = style.IsHandwritten.HasValue && style.IsHandwritten == true; if (isHandwritten && style.Confidence > 0.8) { Console.WriteLine($"Handwritten content found:"); foreach (DocumentSpan span in style.Spans) { Console.WriteLine($" Content: {result.Content.Substring(span.Offset, span.Length)}"); } } } Console.WriteLine("The following tables were extracted:"); for (int i = 0; i < result.Tables.Count; i++) { DocumentTable table = result.Tables[i]; Console.WriteLine($" Table {i} has {table.RowCount} rows and {table.ColumnCount} columns."); foreach (DocumentTableCell cell in table.Cells) { Console.WriteLine($" Cell ({cell.RowIndex}, {cell.ColumnIndex}) has kind '{cell.Kind}' and content: '{cell.Content}'."); } } #endregion }
private void ProcessBreakpointChange(DocumentLine line, BreakpointOperation ops) { // please notify ATF team before defining FullISyntaxEditorControl if (line == null || StringUtil.IsNullOrEmptyOrWhitespace(line.Text)) return; // get or create breakpoint layer. var layer = Document.SpanIndicatorLayers[SpanIndicatorLayer.BreakpointKey]; if (layer == null) { layer = new SpanIndicatorLayer(SpanIndicatorLayer.BreakpointKey, SpanIndicatorLayer.BreakpointDisplayPriority); Document.SpanIndicatorLayers.Add(layer); } // find breakpoint indicator for the current line. BreakpointIndicator breakpointIndicator = null; foreach (SpanIndicator si in line.SpanIndicators) { breakpointIndicator = si as BreakpointIndicator; if (breakpointIndicator != null) break; } var breakpointExist = breakpointIndicator != null; var addbreakpoint = ((ops == BreakpointOperation.Set || ops == BreakpointOperation.Toggle) && !breakpointExist); // do nothing if (addbreakpoint == breakpointExist) return; var e = new BreakpointEventArgs(addbreakpoint, line.Index + 1, line.Text); if (BreakpointChanging != null) BreakpointChanging(this, e); // cancel the operation if (e.Cancel) return; if (addbreakpoint) { breakpointIndicator = new BreakpointIndicator(); layer.Add(breakpointIndicator, line.TextRange); } else // remove breakpoint { layer.Remove(breakpointIndicator); } }
public string GenerateHtml(TextDocument document, IHighlighter highlighter) { string myMainStyle = MainStyle; string lineNumberStyle = "color: #606060;"; DocumentLine docline = null; string textLine = null; if (highlighter == null) { docline = document.GetLineByNumber(1); } StringWriter output = new StringWriter(); if (ShowLineNumbers || AlternateLineBackground) { output.Write("<div"); WriteStyle(output, myMainStyle); output.WriteLine(">"); int longestNumberLength = 1 + (int)Math.Log10(document.LineCount); for (int lineNumber = 1; lineNumber <= document.LineCount; lineNumber++) { HighlightedLine line = null; if (highlighter != null) { line = highlighter.HighlightLine(lineNumber); } else { textLine = document.GetText(docline); docline = docline.NextLine; } output.Write("<pre"); if (AlternateLineBackground && (lineNumber % 2) == 0) { WriteStyle(output, AlternateLineStyle); } else { WriteStyle(output, LineStyle); } output.Write(">"); if (ShowLineNumbers) { output.Write("<span"); WriteStyle(output, lineNumberStyle); output.Write('>'); output.Write(lineNumber.ToString().PadLeft(longestNumberLength)); output.Write(": "); output.Write("</span>"); } PrintWords(output, line, textLine); output.WriteLine("</pre>"); } output.WriteLine("</div>"); } else { output.Write("<pre"); WriteStyle(output, myMainStyle + LineStyle); output.WriteLine(">"); for (int lineNumber = 1; lineNumber <= document.LineCount; lineNumber++) { HighlightedLine line = highlighter.HighlightLine(lineNumber); PrintWords(output, line, textLine); output.WriteLine(); } output.WriteLine("</pre>"); } if (CreateStylesheet && _stylesheet.Length > 0) { string result = "<style type=\"text/css\">" + _stylesheet + "</style>" + output; _stylesheet = new StringBuilder(); return(result); } return(output.ToString()); }
bool EndsWithContinuation (Span span, DocumentLine line) { return !span.StopAtEol || span.StopAtEol && !string.IsNullOrEmpty (span.Continuation) && line != null && doc.GetTextAt (line).Trim ().EndsWith (span.Continuation, StringComparison.Ordinal); }
/// <summary> /// Retrieve completion suggestions /// </summary> /// <param name="completionWord">Word to complete</param> /// <param name="content">Script that we're working with</param> /// <param name="lineContent">Content of the current line</param> /// <param name="line">Line object from AvaloneEdit</param> /// <param name="runbookToken">Token containing the name of the runbook (if not runbook, null)</param> /// <param name="position">Caret offset</param> /// <param name="triggerChar">Not used</param> /// <param name="triggerTag">Counter</param> public void GetCompletionData(string completionWord, string content, string lineContent, DocumentLine line, Token runbookToken, int position, char?triggerChar, long triggerTag) { if (_requestTrigger != 0 && triggerTag <= _requestTrigger) { return; } DismissGetCompletionResults(); ProcessCompletion(content, triggerChar, completionWord, runbookToken, position, triggerTag); }
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength) { }
void ShowInconsistentWarning(bool preferUnixNewLines) { if (editor.Document == null) { return; // editor was disposed } groupBox = new GroupBox(); groupBox.Background = SystemColors.WindowBrush; groupBox.Foreground = SystemColors.WindowTextBrush; groupBox.Header = ResourceService.GetString("AddIns.AvalonEdit.InconsistentNewlines.Header"); groupBox.HorizontalAlignment = HorizontalAlignment.Right; groupBox.VerticalAlignment = VerticalAlignment.Bottom; groupBox.MaxWidth = 300; groupBox.Margin = new Thickness(0, 0, 20, 20); Grid.SetRow(groupBox, 1); windows = new RadioButton { IsChecked = !preferUnixNewLines, Content = ResourceService.GetString("Dialog.Options.IDEOptions.LoadSaveOptions.WindowsRadioButton"), Margin = new Thickness(0, 0, 8, 0) }; unix = new RadioButton { IsChecked = preferUnixNewLines, Content = ResourceService.GetString("Dialog.Options.IDEOptions.LoadSaveOptions.UnixRadioButton") }; normalizeButton = new Button { Content = ResourceService.GetString("AddIns.AvalonEdit.InconsistentNewlines.Normalize") }; cancelButton = new Button { Content = ResourceService.GetString("Global.CancelButtonText") }; groupBox.Content = new StackPanel { Children = { new TextBlock { Text = ResourceService.GetString("AddIns.AvalonEdit.InconsistentNewlines.Description"), TextWrapping = TextWrapping.WrapWithOverflow }, windows, unix, new StackPanel { Margin = new Thickness(0, 2, 0, 0), Orientation = Orientation.Horizontal, Children = { normalizeButton, cancelButton } } } }; editor.Children.Add(groupBox); var featureUse = AnalyticsMonitorService.TrackFeature(typeof(NewLineConsistencyCheck)); EventHandler removeWarning = null; removeWarning = delegate { editor.Children.Remove(groupBox); editor.PrimaryTextEditor.TextArea.Focus(); editor.LoadedFileContent -= removeWarning; featureUse.EndTracking(); }; editor.LoadedFileContent += removeWarning; cancelButton.Click += delegate { AnalyticsMonitorService.TrackFeature(typeof(NewLineConsistencyCheck), "cancelButton"); removeWarning(null, null); }; normalizeButton.Click += delegate { AnalyticsMonitorService.TrackFeature(typeof(NewLineConsistencyCheck), "normalizeButton"); removeWarning(null, null); TextDocument document = editor.Document; string newNewLine = (unix.IsChecked == true) ? "\n" : "\r\n"; using (document.RunUpdate()) { for (int i = 1; i <= document.LineCount; i++) { // re-fetch DocumentLine for every iteration because we're modifying the newlines so that DocumentLines might get re-created DocumentLine line = document.GetLineByNumber(i); if (line.DelimiterLength > 0) { int endOffset = line.EndOffset; if (document.GetText(endOffset, line.DelimiterLength) != newNewLine) { document.Replace(endOffset, line.DelimiterLength, newNewLine); } } } } }; }
//public IList<DocumentHistory> GetDocumentHistory(DocumentHistory data) //{ // try { // SetService(); return SerClient.GetDocumentHistory(data); } // finally // { // SerClient.Close(); // if (SerClient.State == CommunicationState.Faulted) // SerClient.Abort(); // } //} //public DocumentHistory SaveDocumentHistory(DocumentHistory data) //{ // try { // SetService(); return SerClient.SaveDocumentHistory(data); } // finally // { // SerClient.Close(); // if (SerClient.State == CommunicationState.Faulted) // SerClient.Abort(); // } //} //public void UpdateDocumentHistory(DocumentHistory data) //{ // try { // SetService(); SerClient.UpdateDocumentHistory(data); } // finally // { // SerClient.Close(); // if (SerClient.State == CommunicationState.Faulted) // SerClient.Abort(); // } //} //public void DeleteDocumentHistory(DocumentHistory data) //{ // try { // SetService(); SerClient.DeleteDocumentHistory(data); } // finally // { // SerClient.Close(); // if (SerClient.State == CommunicationState.Faulted) // SerClient.Abort(); // } //} public DocumentLine SaveDocumentLine(DocumentLine data) { try { SetService(); return SerClient.SaveDocumentLine(data); } finally { SerClient.Close(); if (SerClient.State == CommunicationState.Faulted) SerClient.Abort(); } }
public void IndentLine(TextDocument document, DocumentLine line) { if (document == null || line == null) { return; } DocumentLine previousLine = line.PreviousLine; if (previousLine != null) { ISegment indentationSegment = TextUtilities.GetWhitespaceAfter(document, previousLine.Offset); string indentation = document.GetText(indentationSegment); if (Program.OptionsObject.Editor_AgressiveIndentation) { string currentLineTextTrimmed = (document.GetText(line)).Trim(); string lastLineTextTrimmed = (document.GetText(previousLine)).Trim(); char currentLineFirstNonWhitespaceChar = ' '; if (currentLineTextTrimmed.Length > 0) { currentLineFirstNonWhitespaceChar = currentLineTextTrimmed[0]; } char lastLineLastNonWhitespaceChar = ' '; if (lastLineTextTrimmed.Length > 0) { lastLineLastNonWhitespaceChar = lastLineTextTrimmed[lastLineTextTrimmed.Length - 1]; } if (lastLineLastNonWhitespaceChar == '{' && currentLineFirstNonWhitespaceChar != '}') { if (Program.OptionsObject.Editor_ReplaceTabsToWhitespace) { indentation += new string(' ', Program.OptionsObject.Editor_IndentationSize); } else { indentation += "\t"; } } else if (currentLineFirstNonWhitespaceChar == '}') { if (indentation.Length > 0) { indentation = indentation.Substring(0, indentation.Length) + "\t\n" + indentation.Substring(0, indentation.Length); } else { indentation = "\t\n"; } } /*if (lastLineTextTrimmed == "{" && currentLineTextTrimmed != "}") * { * indentation += "\t"; * } * else if (currentLineTextTrimmed == "}") * { * if (indentation.Length > 0) * { * indentation = indentation.Substring(0, indentation.Length - 1); * } * else * { * indentation = string.Empty; * } * }*/ } indentationSegment = TextUtilities.GetWhitespaceAfter(document, line.Offset); document.Replace(indentationSegment, indentation); } }
public IList<Unit> GetDocumentUnit(DocumentLine data) { try { SetService(); return SerClient.GetDocumentUnit(data); } finally { SerClient.Close(); if (SerClient.State == CommunicationState.Faulted) SerClient.Abort(); } }
public override SpanParser CreateSpanParser(DocumentLine line, CloneableStack <Span> spanStack) { return(new ASPNetSpanParser(this, spanStack ?? line.StartSpan.Clone())); }
public Boolean CheckAdjustmentLine(DocumentLine data, Label label) { try { SetService(); return SerClient.CheckAdjustmentLine(data, label); } finally { SerClient.Close(); if (SerClient.State == CommunicationState.Faulted) SerClient.Abort(); } }
public virtual SpanParser CreateSpanParser(DocumentLine line, CloneableStack <Span> spanStack) { return(new SpanParser(this, spanStack ?? line.StartSpan.Clone())); }
public Boolean ReceiveProduct(DocumentLine receivingLine, Unit logisticUnit, Bin destLocation, Node recNode) { try { SetService(); return SerClient.ReceiveProduct(receivingLine, logisticUnit, destLocation, recNode); } finally { SerClient.Close(); if (SerClient.State == CommunicationState.Faulted) SerClient.Abort(); } }
public virtual ChunkParser CreateChunkParser(SpanParser spanParser, ColorScheme style, DocumentLine line) { return(new ChunkParser(this, spanParser, style, line)); }
internal void CancelMergerOrder(Document document, DocumentLine docLine) { try { SetService(); SerClient.CancelMergerOrder(document, docLine); } finally { SerClient.Close(); if (SerClient.State == CommunicationState.Faulted) SerClient.Abort(); } }
public ChunkParser(SyntaxMode mode, SpanParser spanParser, ColorScheme style, DocumentLine line) { this.mode = mode; this.doc = mode.Document; this.line = line; this.lineOffset = line.Offset; this.spanParser = spanParser; spanParser.FoundSpanBegin = FoundSpanBegin; spanParser.FoundSpanEnd = FoundSpanEnd; spanParser.FoundSpanExit = FoundSpanExit; spanParser.ParseChar += ParseChar; if (line == null) { throw new ArgumentNullException("line"); } }
/// <summary> /// Appends text of the specified color to the document. /// </summary> /// <param name="TxtColor">The color of the text to be appended</param> /// <param name="Txt">The text to be appended</param> public void AppendText(Color? TxtColor, string Txt) { if(Txt.Length == 0) { return; } DocumentLine CurLine; int CurLineLength = 0; if(mLines.Count == 0) { CurLine = new DocumentLine(); mLines.Add(CurLine); } else { CurLine = mLines[mLines.Count - 1]; } char LastChar = (char)0; // Break the Text in to multiple lines String[] Lines = System.Text.RegularExpressions.Regex.Split(Txt, "\r\n"); foreach (String Line in Lines) { // Skip empty lines if (Line.Length == 0) { continue; } // Put back the \r\n String ThisLine = Line + "\r\n"; Color? CurrColor = TxtColor; // Check for keywords if (ThisLine.Contains("Error")) { CurrColor = Color.Red; } else if (ThisLine.Contains("Warning")) { CurrColor = Color.Orange; } // Append the line foreach (char CurChar in ThisLine) { if (CurChar == '\n' && LastChar != '\r') { CurLine.Append(CurrColor, '\r'); } // replace tabs with 4 spaces if (CurChar == '\t') { CurLine.Append(CurrColor, " "); } else { CurLine.Append(CurrColor, CurChar); } if (CurChar == '\n') { // only count displayable characters (cut \r\n) CurLineLength = CurLine.Length - 2; if (CurLineLength > mLongestLineLength) { mLongestLineLength = CurLineLength; } // This isn't required but it enables readonly optimizations CurLine.FinishBuilding(); // A full line has been created so trigger the line added event OnLineAdded(new OutputWindowDocumentLineAddedEventArgs(mLines.Count - 1, new ReadOnlyDocumentLine(CurLine))); // Then begin our new line CurLine = new DocumentLine(); mLines.Add(CurLine); } LastChar = CurChar; } } // NOTE: This line hasn't been terminated yet so we don't have to account for \r\n at the end CurLineLength = CurLine.Length; if(CurLineLength > mLongestLineLength) { mLongestLineLength = CurLineLength; } OnModified(new EventArgs()); }
private bool IsLineCommented(DocumentLine line) { var trimmed = this.Document.GetText(line.Offset, line.Length).Trim(); return(trimmed.IndexOf(COMMENT_DELIM_DASH).Equals(0) || trimmed.IndexOf(COMMENT_DELIM_SLASH).Equals(0)); }
/// <summary> /// Gets the length of the line in characters. /// </summary> /// <param name="Line">The line whose length is to be retrieved.</param> /// <returns>The length of the line with the EOL characters removed (if they exist).</returns> private static int GetLineLength(DocumentLine Line) { if(Line.Length >= 2 && Line[Line.Length - 1] == '\n' && Line[Line.Length - 2] == '\r') { return Line.Length - 2; } else { return Line.Length; } }
protected override void ColorizeLine(DocumentLine line) { int lineOffset = line.Offset; string text = CurrentContext.Document.GetText(line); if (text.Length == 0) { return; } foreach (var token in Tokens .Where(x => x.Type != TokenType.Eof) .Where(x => x.Offset >= lineOffset && x.Offset <= lineOffset + text.Length || x.Offset + x.Length >= lineOffset).ToList()) { int endOffset = Math.Min(token.Offset + token.Length, lineOffset + text.Length); int startOffset = Math.Max(token.Offset, lineOffset); if (endOffset <= startOffset) { continue; } base.ChangeLinePart( startOffset, endOffset, element => { ColorizeElement(element, token, false); }); if (token is StringToken && Regex.IsMatch(((StringToken)token).Literal, @"^\s*\{.*\}\s*$")) { Regex r = new Regex(@"\b[\w\d]+\b"); int currentOffset = ((StringToken)token).Literal.IndexOf("{") + 1; foreach (Match match in r.Matches(((StringToken)token).Literal)) { ChangeLinePart( token.Offset + currentOffset + 1, token.Offset + currentOffset + match.Value.Length + 1, element => { element.TextRunProperties.SetForegroundBrush(Brushes.DarkSlateGray); } ); currentOffset += match.Value.Length + 1; } } } //foreach (var tokenError in Errors.Where(x => x.Offset >= lineOffset && x.Offset <= lineOffset + text.Length)) //{ // base.ChangeLinePart( // tokenError.Offset, // tokenError.Offset + 1 <= lineOffset + text.Length ? tokenError.Offset + 1 : tokenError.Offset, // element => { element.BackgroundBrush = Brushes.Red; }); //} try { _parser = new Parser(Tokens); try { _parser.Parse(); } catch (Exception) { } foreach (var token in _parser.AttributeNames.Where(x => x.Offset >= lineOffset && x.Offset <= lineOffset + text.Length)) { int endOffset = Math.Min(token.Offset + token.Length, lineOffset + text.Length); int startOffset = Math.Max(token.Offset, lineOffset); if (endOffset <= startOffset) { continue; } base.ChangeLinePart( startOffset, endOffset, element => { ColorizeElement(element, token, true); }); } } catch (Exception) { } }
public object Clone() { DocumentLine NewLine = new DocumentLine(); if(mBldrText != null) { NewLine.mBldrText.Append(mBldrText.ToString()); } else { NewLine.mBldrText = null; } NewLine.mFinalText = mFinalText; NewLine.mColorRanges = new List<ColoredTextRange>(mColorRanges); if(mUserData != null) { NewLine.mUserData = mUserData.Clone() as ICloneable; } return NewLine; }
void PerformVisualElementConstruction(VisualLineElementGenerator[] generators) { TextDocument document = this.Document; int offset = FirstDocumentLine.Offset; int currentLineEnd = offset + FirstDocumentLine.Length; LastDocumentLine = FirstDocumentLine; int askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { int textPieceEndOffset = currentLineEnd; foreach (VisualLineElementGenerator g in generators) { g.cachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.cachedInterest != -1) { if (g.cachedInterest < offset) { throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.cachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); } if (g.cachedInterest < textPieceEndOffset) { textPieceEndOffset = g.cachedInterest; } } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { int textPieceLength = textPieceEndOffset - offset; elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (VisualLineElementGenerator g in generators) { if (g.cachedInterest == offset) { VisualLineElement element = g.ConstructElement(offset); if (element != null) { elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { DocumentLine newEndLine = document.GetLineByOffset(offset); if (newEndLine == this.LastDocumentLine) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; } break; } } } } } }
internal void UpdateLines(DocumentLine docLine) { if (docLine.Note == "NEW") { //Pner en la linea la info del stock de producto. #region INVENTORY LINE BY LINE //1. Obtener el Stock de los productos de los documentos de se cliente. IList<ProductStock> curStock = service.GetDocumentProductStock(new Document { Customer = new Account { AccountID = View.Model.Customer.AccountID }, Location = App.curLocation, DocType = new DocumentType { DocTypeID = SDocType.SalesOrder }//, //DocStatus = new Status { StatusID = DocStatus.PENDING } }, docLine.Product); //Allocated, Available de los productos del documento. //Obtiene la lista de productos para obtener su stock en uso (Product Inventory). //Allocated in this moment List<int> productList = new List<int> { docLine.Product.ProductID }; //Inventario en Use de esos productos productInUseList = service.GetProductInUseForMerged(productList, App.curLocation); double qtyAvailable, qtyInUse; //ProductStock piInUse; if (docLine.IsDebit == null) docLine.IsDebit = false; docLine.Note = docLine.Document.DocNumber; //QTY AVAILABLE DE INVENTARIO - Debe Restarsele lo allocated y lo que este en uso //que sale de la clase product Inventory. try { qtyAvailable = curStock .Where(f => f.Product.ProductID == docLine.Product.ProductID) .First().FullStock; } catch { qtyAvailable = 0; } qtyAvailable = (double)((int)(qtyAvailable * availabilityMark)); docLine.QtyOnHand = qtyAvailable; //ON HAND //Cantidad en Uso - PROGRAMA. Allocated y Reservada try { //Otros documentos qtyInUse = productInUseList .Where(f => f.Product.ProductID == docLine.Product.ProductID) .Sum(f => f.Stock); //qtyInUse = piInUse.QtyAllocated + piInUse.QtyInUse; } catch { qtyInUse = 0; } qtyAvailable -= qtyInUse; //Finalmente la cantidad que se puede usar. //Cantidad final disponible docLine.QtyInvoiced = qtyInUse; //Allocated docLine.QtyAvailable = ((qtyAvailable > 0) ? qtyAvailable : 0) / docLine.Unit.BaseAmount; docLine.QtyAllocated = 0; //qtyToAllocated; docLine.Sequence = 0; //BALANCE #endregion //Adiciona las lineas View.Model.OrdersDetail.Add(docLine); if(View.ChkFilter.IsChecked == true) View.Model.CurrentDetails.Add(docLine); } else { try { View.Model.OrdersDetail.Where(f => f.LineID == docLine.LineID).First().Quantity = docLine.Quantity; View.Model.OrdersDetail.Where(f => f.LineID == docLine.LineID).First().QtyBackOrder = docLine.QtyBackOrder; View.Model.OrdersDetail.Where(f => f.LineID == docLine.LineID).First().QtyCancel = docLine.QtyCancel; View.Model.OrdersDetail.Where(f => f.LineID == docLine.LineID).First().LineDescription = docLine.LineDescription; } catch { } try { View.Model.CurrentDetails.Where(f => f.LineID == docLine.LineID).First().Quantity = docLine.Quantity; View.Model.CurrentDetails.Where(f => f.LineID == docLine.LineID).First().QtyBackOrder = docLine.QtyBackOrder; View.Model.CurrentDetails.Where(f => f.LineID == docLine.LineID).First().QtyCancel = docLine.QtyCancel; View.Model.CurrentDetails.Where(f => f.LineID == docLine.LineID).First().LineDescription = docLine.LineDescription; } catch { } /* try { DocumentLine oldLine = View.Model.OrdersDetail.Where(f => f.LineID == docLine.LineID).First(); View.Model.OrdersDetail.Remove(oldLine); View.Model.OrdersDetail.Add(docLine); if (View.ChkFilter.IsChecked == true) { DocumentLine oldCurLine = View.Model.CurrentDetails.Where(f => f.LineID == docLine.LineID).First(); View.Model.CurrentDetails.Remove(oldCurLine); View.Model.CurrentDetails.Add(docLine); } } catch { } */ } View.DgDetails.Items.Refresh(); }
static void MoveCaretUpDown(TextArea textArea, CaretMovementType direction, VisualLine visualLine, TextLine textLine, int caretVisualColumn) { // moving up/down happens using the desired visual X position double xPos = textArea.Caret.DesiredXPos; if (double.IsNaN(xPos)) { xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(caretVisualColumn, 0)); } // now find the TextLine+VisualLine where the caret will end up in VisualLine targetVisualLine = visualLine; TextLine targetLine; int textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line int prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { DocumentLine prevLine = textArea.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textArea.TextView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line int nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textArea.Document.LineCount) { DocumentLine nextLine = textArea.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textArea.TextView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position double yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) { yPos -= textArea.TextView.RenderSize.Height; } else { yPos += textArea.TextView.RenderSize.Height; } DocumentLine newLine = textArea.TextView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textArea.TextView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { CharacterHit ch = targetLine.GetCharacterHitFromDistance(xPos); SetCaretPosition(textArea, targetVisualLine, targetLine, ch, false); textArea.Caret.DesiredXPos = xPos; } }
public virtual SpanParser CreateSpanParser (DocumentLine line, CloneableStack<Span> spanStack) { return new SpanParser (this, spanStack ?? line.StartSpan.Clone ()); }
public async Task AnalyzePrebuiltReadFromFileAsync() { string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; DocumentAnalysisClient client = new DocumentAnalysisClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); #region Snippet:FormRecognizerAnalyzePrebuiltReadFromFileAsync #if SNIPPET string filePath = "<filePath>"; #else string filePath = DocumentAnalysisTestEnvironment.CreatePath("Form_1.jpg"); #endif using var stream = new FileStream(filePath, FileMode.Open); AnalyzeDocumentOperation operation = await client.StartAnalyzeDocumentAsync("prebuilt-read", stream); await operation.WaitForCompletionAsync(); AnalyzeResult result = operation.Value; Console.WriteLine("Detected languages:"); foreach (DocumentLanguage language in result.Languages) { Console.WriteLine($" Found language with locale '{language.Locale}' and confidence {language.Confidence}."); } foreach (DocumentPage page in result.Pages) { Console.WriteLine($"Document Page {page.PageNumber} has {page.Lines.Count} line(s), {page.Words.Count} word(s),"); Console.WriteLine($"and {page.SelectionMarks.Count} selection mark(s)."); for (int i = 0; i < page.Lines.Count; i++) { DocumentLine line = page.Lines[i]; Console.WriteLine($" Line {i} has content: '{line.Content}'."); Console.WriteLine($" Its bounding polygon (points ordered clockwise):"); for (int j = 0; j < line.BoundingPolygon.Points.Length; j++) { Console.WriteLine($" Point {j} => X: {line.BoundingPolygon[j].X}, Y: {line.BoundingPolygon[j].Y}"); } } } foreach (DocumentStyle style in result.Styles) { // Check the style and style confidence to see if text is handwritten. // Note that value '0.8' is used as an example. bool isHandwritten = style.IsHandwritten.HasValue && style.IsHandwritten == true; if (isHandwritten && style.Confidence > 0.8) { Console.WriteLine($"Handwritten content found:"); foreach (DocumentSpan span in style.Spans) { Console.WriteLine($" Content: {result.Content.Substring(span.Offset, span.Length)}"); } } } #endregion }
public ChunkParser (SyntaxMode mode, SpanParser spanParser, ColorScheme style, DocumentLine line) { this.mode = mode; this.doc = mode.Document; this.line = line; this.lineOffset = line.Offset; this.spanParser = spanParser; spanParser.FoundSpanBegin = FoundSpanBegin; spanParser.FoundSpanEnd = FoundSpanEnd; spanParser.FoundSpanExit = FoundSpanExit; spanParser.ParseChar += ParseChar; spanParser.IsAtWordStart = () => wordbuilder.Length == 0; if (line == null) throw new ArgumentNullException ("line"); }
internal void AddTo(TextDocument document, DocumentLine line) { this.document = document; document.AddMarker(line, IconMarker); document.AddMarker(TextMarker); }
private void ResetPanel() { CurDocLine = null; ProductUnits = null; scProduct.Product = null; scProduct.txtProductDesc.Text = ""; scProduct.txtData.Text = ""; cboUnit.SelectedItem = null; txtPrecio.Text = txtBO.Text = txtCancel.Text = txtQty.Text = "0"; txtLineDescription.Text = txtNote.Text = ""; }
public double GetVisualPosition(DocumentLine line) { return(GetVisualPositionFromNode(GetNode(line))); }
private void ProcessReceivingProduct(Bin destLocation, int numberOfPackages) { //Lote de Session Actual - Manejado para imprimir los ultimos labels if (string.IsNullOrEmpty(PrintSessionLot)) PrintSessionLot = "PR" + DateTime.Now.ToString("yyMMddHHmmss"); //Define Document, Product, Unit and Qty to send to receiving transaction DocumentLine receivingLine = new DocumentLine { Document = View.Model.Document, Product = (Product)View.TxtProduct.Product, //View.ComboProduct.SelectedItem, Unit = (Unit)View.ComboUnit.SelectedItem, Quantity = numberOfPackages * double.Parse(View.TxtQtyPerPack.Text), QtyPending = (double.Parse(View.TxtQtyPerPack.Text) > 0) ? double.Parse(View.TxtQtyPerPack.Text) : 1, QtyAllocated = numberOfPackages, CreatedBy = App.curUser.UserName, Note = PrintSessionLot }; Unit logisticUnit = View.Model.PackUnit; if (logisticUnit == null && int.Parse(View.TxtQtyPerPack.Text) > 1) { try { logisticUnit = service.GetUnit(new Unit { Company = App.curCompany, Name = WmsSetupValues.CustomUnit }).First(); } catch { Util.ShowError(Util.GetResourceLanguage("UNIT_CUSTOM_NOT_DEFINED")); return; } logisticUnit.BaseAmount = double.Parse(View.TxtQtyPerPack.Text); } service.ReceiveProduct(receivingLine, logisticUnit, destLocation, View.Model.Node); //If Update product info at receiving is enabled - Update Product if (Util.GetConfigOption("ALLUPPRO").Equals("T")) { View.Model.Product.ModifiedBy = App.curUser.UserName; View.Model.Product.ModDate = DateTime.Now; service.UpdateProduct(View.Model.Product); } //Refresh el Balance RefreshBalance(receivingLine.Document); //After Process AfterReceiving(); View.ProcessResult.Text = Util.GetResourceLanguage("PRODUCT_RECEIVED"); //Util.ShowMessage(View.ProcessResult.Text); if (showNextTime) { pw.Close(); showNextTime = UtilWindow.ConfirmResult(View.ProcessResult.Text); } }
public double GetHeight(DocumentLine line) { return(GetNode(line).lineNode.height); }
internal protected abstract void Draw(Context cr, Rectangle area, DocumentLine line, int lineNumber, double x, double y, double height);
HeightTreeNode GetNode(DocumentLine ls) { return(GetNodeByIndex(ls.LineNumber - 1)); }