public IEnumerable<ISegment> GetDeletableSegments(ISegment segment)
		{
			if (segment == null)
				throw new ArgumentNullException("segment");
			// the segment is always deletable
			return ExtensionMethods.Sequence(segment);
		}
 public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
 {
     if (m_jsonEditorViewModel.IsBetweenQoats)
       {
     int offset = m_jsonEditorViewModel.Caret.Offset;
     List<char> startChars = new List<char> {m_autoCompleteValue.SchemaObject.AutoCompletePathSeperator, '"'};
     if (m_autoCompleteValue.SchemaObject.Prefix.Length > 0)
       startChars.Add(m_autoCompleteValue.SchemaObject.Prefix.Last());
     int indexQuotStart = m_jsonEditorViewModel.TextDocument.Text.LastIndexOfAny(startChars.ToArray(), offset - 1, offset - 1) + 1;
     int indexQuatEnd = m_jsonEditorViewModel.TextDocument.Text.IndexOf('"', offset);
     int indexLineBreak = m_jsonEditorViewModel.TextDocument.Text.IndexOf('\n', offset);
     if (indexQuatEnd >= indexQuotStart && indexQuatEnd < indexLineBreak)
       completionSegment = new SelectionSegment(indexQuotStart, indexQuatEnd);
       }
       int endOffset = completionSegment.Offset + Text.Length;
       textArea.Document.Replace(completionSegment, (Text + m_autoCompleteValue.SchemaObject.Suffix).Replace("\\", "\\\\"));
       m_jsonEditorViewModel.Caret.Offset = endOffset;
       string value = m_autoCompleteValue.SchemaObject.RemovePrefixAndSuffix(m_jsonEditorViewModel.GetCurrentValue());
       if (Text.StartsWith(".." + m_autoCompleteValue.SchemaObject.AutoCompletePathSeperator) && value.Any(char.IsLetterOrDigit))
       {
     value = value.Substring(0, value.Length - 4);
     int startIndex = value.LastIndexOf(m_autoCompleteValue.SchemaObject.AutoCompletePathSeperator);
     if (startIndex == -1)
       startIndex = m_autoCompleteValue.SchemaObject.Prefix.Length;
     else
     {
       startIndex++;
     }
     m_jsonEditorViewModel.TextDocument.Replace(
       m_jsonEditorViewModel.Caret.Offset - 4 - (value.Length - startIndex), (value.Length - startIndex) + 4, "");
       }
       m_jsonEditorViewModel.UpdateAutoCompletList = true;
 }
Exemple #3
0
        public SegmentReader(ISegment segment, IWebReader webReader, IWebMetadataFactory webMetadataFactory, IRetryManager retryManager, IPlatformServices platformServices)
        {
            if (null == segment)
                throw new ArgumentNullException(nameof(segment));
            if (null == webReader)
                throw new ArgumentNullException(nameof(webReader));
            if (null == webMetadataFactory)
                throw new ArgumentNullException(nameof(webMetadataFactory));
            if (null == retryManager)
                throw new ArgumentNullException(nameof(retryManager));
            if (null == platformServices)
                throw new ArgumentNullException(nameof(platformServices));

            _segment = segment;
            _webReader = webReader;
            _webMetadataFactory = webMetadataFactory;
            _retryManager = retryManager;
            _platformServices = platformServices;

            if ((segment.Offset >= 0) && (segment.Length > 0))
            {
                _startOffset = segment.Offset;
                _endOffset = segment.Offset + segment.Length - 1;
            }
        }
        public NumberVerifierMessageUI(MessageEventArgs messageEventArgs, IBilingualDocument bilingualDocument, ISegment sourceSegment, ISegment targetSegment)
        {
            MessageEventArgs = messageEventArgs;
            BilingualDocument = bilingualDocument;
            SourceSegment = sourceSegment;
            TargetSegment = targetSegment;
            InitializeComponent();
            
            _sourceSegmentControl.Dock = DockStyle.Fill;
            _sourceSegmentControl.IsReadOnly = false;
            _sourceSegmentControl.ReplaceDocumentSegment(sourceSegment.Clone() as ISegment);
            panel_Source.Controls.Add(_sourceSegmentControl);
            _sourceSegmentControl.ReplaceDocumentSegment(sourceSegment);

            _targetSegmentControl.Dock = DockStyle.Fill;
            _targetSegmentControl.IsReadOnly = false;
            _targetSegmentControl.ReplaceDocumentSegment(targetSegment.Clone() as ISegment);
            panel_Target.Controls.Add(_targetSegmentControl);
            _targetSegmentControl.ReplaceDocumentSegment((ISegment)targetSegment.Clone());

            _targetSegmentControl.SegmentContentChanged += OnSegmentContentChanged;

            _hasSegmentChanged = false;

            UpdateMessage(messageEventArgs);


        }
 /// <summary>
 /// Adds the specified segment to the geometry.
 /// </summary>
 public void AddSegment(TextView textView, ISegment segment)
 {
     if (textView == null)
         throw new ArgumentNullException(nameof(textView));
     Size pixelSize = PixelSnapHelpers.GetPixelSize(textView);
     foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd))
     {
         if (AlignToWholePixels)
         {
             AddRectangle(PixelSnapHelpers.Round(r.Left, pixelSize.Width),
                          PixelSnapHelpers.Round(r.Top + 1, pixelSize.Height),
                          PixelSnapHelpers.Round(r.Right, pixelSize.Width),
                          PixelSnapHelpers.Round(r.Bottom + 1, pixelSize.Height));
         }
         else if (AlignToMiddleOfPixels)
         {
             AddRectangle(PixelSnapHelpers.PixelAlign(r.Left, pixelSize.Width),
                          PixelSnapHelpers.PixelAlign(r.Top + 1, pixelSize.Height),
                          PixelSnapHelpers.PixelAlign(r.Right, pixelSize.Width),
                          PixelSnapHelpers.PixelAlign(r.Bottom + 1, pixelSize.Height));
         }
         else
         {
             AddRectangle(r.Left, r.Top + 1, r.Right, r.Bottom + 1);
         }
     }
 }
		public bool IsInOriginal (ISegment segment)
		{
			if (segment == null)
				throw new ArgumentNullException ("segment");

			return segment.Contains(Offset) && segment.Contains (Offset + Length); 
		}
        /// <summary>
        /// Constructor that takes the given message event args, bilingual document, source segment and target segment.
        /// </summary>
        /// <param name="messageEventArgs">message event arguments</param>
        /// <param name="bilingualDocument">bilingual document</param>
        /// <param name="sourceSegment">source segment</param>
        /// <param name="targetSegment">target segment</param>
        public CustomMessageControl(MessageEventArgs messageEventArgs, IBilingualDocument bilingualDocument, ISegment sourceSegment, ISegment targetSegment)
        {
            MessageEventArgs = messageEventArgs;
            BilingualDocument = bilingualDocument;
            SourceSegment = sourceSegment;
            TargetSegment = targetSegment;
            InitializeComponent();
            
            _sourceSegmentControl.Dock = DockStyle.Fill;
            _sourceSegmentPanel.Controls.Add(_sourceSegmentControl);

            _targetSegmentControl.Dock = DockStyle.Fill;
            _targetSegmentPanel.Controls.Add(_targetSegmentControl);

            UpdateMessage(messageEventArgs);
            UpdateSourceSegment(sourceSegment);
            UpdateTargetSegment((ISegment)targetSegment.Clone());
            UpdateProblemDescription(messageEventArgs);
            UpdateSuggestions(messageEventArgs);

            // make the target segment editable
            _targetSegmentControl.IsReadOnly = false;

            _suggestionsList.SelectedIndexChanged += _suggestionsList_SelectedIndexChanged;
        }
Exemple #8
0
 /// <summary>
 /// Shows completion window for passed functions.
 /// </summary>
 /// <param name="identifierSegment">optional segment that should be included in the progressive search: eg. part of an identifier that's already typed before code completion was started</param>
 /// <param name="functions"></param>
 public void ShowCompletionWindow(ISegment identifierSegment, IList<Function> functions)
 {
     FunctionCompletionData first = null;
     _completionWindow = new CompletionWindow(textEditor.TextArea);
     foreach (var function in functions)
     {
         var tooltip = string.IsNullOrWhiteSpace(function.Definition) ? function.Description : string.Format("{0}\n\n{1}", function.Definition.Replace("|", Environment.NewLine), function.Description);
         var item = new FunctionCompletionData(function.Name, tooltip);
         if (first == null) first = item;
         _completionWindow.CompletionList.CompletionData.Add(item);
     }
     _completionWindow.StartOffset = identifierSegment.Offset;
     _completionWindow.EndOffset = identifierSegment.EndOffset;
     if (first != null)
     {
         _completionWindow.CompletionList.SelectedItem = first;
     }
     _completionWindow.Show();
     _completionWindow.Closed += (sender, args) => _completionWindow = null;
     _completionWindow.PreviewTextInput += (sender, args) =>
     {
         if (args.Text == "(")
         {
             _completionWindow.CompletionList.RequestInsertion(EventArgs.Empty);
         }
         var c = args.Text[args.Text.Length - 1];
         args.Handled = !char.IsLetterOrDigit(c) && c != '_';
     };
 }
 public void Process(ISegment segment)
 {
     _plainText = new StringBuilder();
     _comments.Clear();
     _tokens.Clear();
     VisitChildren(segment);
 }
 internal static Sequence PackMessage(VersionCode version, ISegment header, SecurityParameters parameters, ISegment scope, IPrivacyProvider privacy)
 {
     if (scope == null)
     {
         throw new ArgumentNullException("scope");
     }
     
     if (parameters == null)
     {
         throw new ArgumentNullException("parameters");
     }
     
     if (header == null)
     {
         throw new ArgumentNullException("header");
     }
     
     if (privacy == null)
     {
         throw new ArgumentNullException("privacy");
     }
     
     ISnmpData[] collection = new ISnmpData[4]
                                      {
                                          new Integer32((int)version),
                                          header.GetData(version),
                                          parameters.GetData(version),
                                          privacy.Encrypt(scope.GetData(version), parameters)
                                      };
     return new Sequence(collection);
 }
 // Returns the plain text representation of a segment.
 // If the includeTagText parameter is true, the returned string will
 // also contain the tag content for each tag.
 public string GetPlainText(ISegment segment, bool includeTagText)
 {
     PlainText = new StringBuilder(string.Empty);
     IncludeTagText = includeTagText;
     VisitChildren(segment);
     return PlainText.ToString();
 }
Exemple #12
0
        /// <summary>
        /// Creates a HTML fragment from a part of a document.
        /// </summary>
        /// <param name="document">The document to create HTML from.</param>
        /// <param name="highlighter">The highlighter used to highlight the document. <c>null</c> is valid and will create HTML without any highlighting.</param>
        /// <param name="segment">The part of the document to create HTML for. You can pass <c>null</c> to create HTML for the whole document.</param>
        /// <param name="options">The options for the HTML creation.</param>
        /// <returns>HTML code for the document part.</returns>
        public static string CreateHtmlFragment(TextDocument document, IHighlighter highlighter, ISegment segment, HtmlOptions options)
        {
            if (document == null)
                throw new ArgumentNullException("document");
            if (options == null)
                throw new ArgumentNullException("options");
            if (highlighter != null && highlighter.Document != document)
                throw new ArgumentException("Highlighter does not belong to the specified document.");
            if (segment == null)
                segment = new SimpleSegment(0, document.TextLength);

            StringBuilder html = new StringBuilder();
            int segmentEndOffset = segment.EndOffset;
            DocumentLine line = document.GetLineByOffset(segment.Offset);
            while (line != null && line.Offset < segmentEndOffset) {
                HighlightedLine highlightedLine;
                if (highlighter != null)
                    highlightedLine = highlighter.HighlightLine(line.LineNumber);
                else
                    highlightedLine = new HighlightedLine(document, line);
                SimpleSegment s = segment.GetOverlap(line);
                if (html.Length > 0)
                    html.AppendLine("<br>");
                html.Append(highlightedLine.ToHtml(s.Offset, s.EndOffset, options));
                line = line.NextLine;
            }
            return html.ToString();
        }
 /// <summary>
 /// Creates a new SimpleSelection instance.
 /// </summary>
 public SimpleSelection(ISegment segment)
 {
     if (segment == null)
         throw new ArgumentNullException("segment");
     this.startOffset = segment.Offset;
     this.endOffset = startOffset + segment.Length;
 }
 public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
 {
     var instance = ServiceLocator.Current.GetInstance<MainViewModel>();
     var text = instance.ActiveEditor.TextBox.FindWord();
     var offset = completionSegment.Offset - text.Length;
     textArea.Document.Replace(offset, text.Length, Text);
 }
 public virtual void Complete(TextArea textArea, ISegment completionSegment,
     EventArgs insertionRequestEventArgs)
 {
   textArea.Document.Replace(completionSegment, Action == null ? this.Text : Action.Invoke());
   if (CaretOffset != 0)
     textArea.Caret.Offset += CaretOffset;
 }
		public CodeSegmentPreviewWindow (TextEditor editor, bool hideCodeSegmentPreviewInformString, ISegment segment, int width, int height) : base (Gtk.WindowType.Popup)
		{
			this.HideCodeSegmentPreviewInformString = hideCodeSegmentPreviewInformString;
			this.editor = editor;
			this.AppPaintable = true;
			layout = PangoUtil.CreateLayout (this);
			informLayout = PangoUtil.CreateLayout (this);
			informLayout.SetText (CodeSegmentPreviewInformString);
			
			fontDescription = Pango.FontDescription.FromString (editor.Options.FontName);
			fontDescription.Size = (int)(fontDescription.Size * 0.8f);
			layout.FontDescription = fontDescription;
			layout.Ellipsize = Pango.EllipsizeMode.End;
			// setting a max size for the segment (40 lines should be enough), 
			// no need to markup thousands of lines for a preview window
			int startLine = editor.Document.OffsetToLineNumber (segment.Offset);
			int endLine = editor.Document.OffsetToLineNumber (segment.EndOffset);
			const int maxLines = 40;
			bool pushedLineLimit = endLine - startLine > maxLines;
			if (pushedLineLimit)
				segment = new Segment (segment.Offset, editor.Document.GetLine (startLine + maxLines).Offset - segment.Offset);
			layout.Ellipsize = Pango.EllipsizeMode.End;
			layout.SetMarkup (editor.Document.SyntaxMode.GetMarkup (editor.Document,
			                                                        editor.Options,
			                                                        editor.ColorStyle,
			                                                        segment.Offset,
			                                                        segment.Length,
			                                                        true) + (pushedLineLimit ? Environment.NewLine + "..." : ""));
			CalculateSize ();
		}
 public List<string> GetSegmentComment(ISegment segment)
 {
     _Comments.Clear();
     VisitChildren(segment);
 
     return _Comments;
 }
Exemple #18
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Return a Reference (e.g., Scripture reference, or text abbreviation/para #/sentence#) for the specified character
		/// position (in the whole paragraph), which is assumed to belong to the specified segment.
		/// (For now, ich is not actually used, but it may become important if we decide not to split segements for
		/// verse numbers.)
		/// Overridden in ScrTxtPara to handle special cases for Scripture refs.
		/// </summary>
		/// <param name="seg">The segment.</param>
		/// <param name="ich">The character position.</param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		public virtual ITsString Reference(ISegment seg, int ich)
		{
			IStText stText = Owner as IStText;
			if (stText == null)
			{
				// Unusual case, possibly hvoPara is not actually a para at all, for example, it may
				// be a picture caption. For now we make an empty reference so at least it won't crash.
				ITsStrFactory tsf = TsStrFactoryClass.Create();
				return tsf.MakeString("", Cache.DefaultUserWs);
			}
			ITsString tssName = null;
			bool fUsingAbbreviation = false;
			if (stText.Owner is IText)
			{
				// see if we can find an abbreviation.
				IText text = (IText)stText.Owner;
				tssName = text.Abbreviation.BestVernacularAnalysisAlternative;
				if (tssName != null && tssName.Length > 0 && tssName.Text != text.Abbreviation.NotFoundTss.Text)
					fUsingAbbreviation = true;
			}

			if (!fUsingAbbreviation)
				tssName = stText.Title.BestVernacularAnalysisAlternative;

			ITsStrBldr bldr = tssName.GetBldr();
			// If we didn't find a "best", reset to an empty string.
			if (bldr.Length > 0 && bldr.Text == stText.Title.NotFoundTss.Text)
				bldr.ReplaceTsString(0, bldr.Length, null);
			// Truncate to 8 chars, if the user hasn't specified an abbreviation.
			if (!fUsingAbbreviation && bldr.Length > 8)
				bldr.ReplaceTsString(8, bldr.Length, null);

			// Make a TsTextProps specifying just the writing system.
			ITsPropsBldr propBldr = TsPropsBldrClass.Create();
			int dummy;
			int wsActual = bldr.get_Properties(0).GetIntPropValues((int)FwTextPropType.ktptWs, out dummy);
			propBldr.SetIntPropValues((int)FwTextPropType.ktptWs, (int)FwTextPropVar.ktpvDefault, wsActual);
			ITsTextProps props = propBldr.GetTextProps();

			// Insert a space (if there was any title)
			if (bldr.Length > 0)
				bldr.Replace(bldr.Length, bldr.Length, " ", props);

			// if Scripture.IsResponsibleFor(stText) we should try to get the verse number of the annotation.
			//if (stText.OwningFlid == (int)Text.TextTags.kflidContents)
			//{

			// Insert paragraph number.
			int ipara = stText.ParagraphsOS.IndexOf(this) + 1;
			bldr.Replace(bldr.Length, bldr.Length, ipara.ToString(), props);

			// And a period...
			bldr.Replace(bldr.Length, bldr.Length, ".", props);

			// And now the segment number
			int iseg = SegmentsOS.IndexOf(seg) + 1;
			bldr.Replace(bldr.Length, bldr.Length, iseg.ToString(), props);
			return bldr.GetString();
		}
		public static IFoldSegment CreateFoldSegment (TextEditor editor, ISegment segment, FoldingType foldingType = FoldingType.Unknown)
		{
			if (editor == null)
				throw new ArgumentNullException ("editor");
			if (segment == null)
				throw new ArgumentNullException ("segment");
			return CreateFoldSegment (editor, segment.Offset, segment.Length, false, "...", foldingType);
		}
		/// <summary>
		/// Calculates the list of rectangle where the segment in shown.
		/// This returns one rectangle for each line inside the segment.
		/// </summary>
		public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment)
		{
			if (textView == null)
				throw new ArgumentNullException("textView");
			if (segment == null)
				throw new ArgumentNullException("segment");
			return GetRectsForSegmentImpl(textView, segment);
		}
 public IdenticalVerifierMessageData(string errorDetails, ISegment replacementSuggestion)
 {
     this.ErrorDetails = errorDetails;
     this.ReplacementSuggestion = replacementSuggestion;
     
     //Identifier for this custom message type
     this.MessageType = "Sdl.Verification.Sdk.IdenticalCheck.MessageUI, Error_NotIdentical";
 }
 /// <summary>
 /// Calculates the list of rectangle where the segment in shown.
 /// This returns one rectangle for each line inside the segment.
 /// </summary>
 public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false)
 {
     if (textView == null)
         throw new ArgumentNullException("textView");
     if (segment == null)
         throw new ArgumentNullException("segment");
     return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd);
 }
Exemple #23
0
		public SearchLocation(SearchTarget target, string baseDirectory, string filter, bool searchSubdirs, ISegment selection)
		{
			this.Target = target;
			this.BaseDirectory = baseDirectory;
			this.Filter = filter ?? "*.*";
			this.SearchSubdirs = searchSubdirs;
			this.Selection = selection;
		}
		public TooltipItem (object item, ISegment itemSegment) 
		{
			if (itemSegment == null)
				throw new ArgumentNullException ("itemSegment");
			Item = item;
			this.offset = itemSegment.Offset;
			this.length = itemSegment.Length;
		}
		public static IFoldSegment CreateFoldSegment (TextEditor editor, ISegment segment, bool isCollapsed = false, string collapsedText = "...", FoldingType foldingType = FoldingType.Unknown)
		{
			if (editor == null)
				throw new ArgumentNullException ("editor");
			if (segment == null)
				throw new ArgumentNullException ("segment");
			return CreateFoldSegment (editor, segment.Offset, segment.Length, isCollapsed, collapsedText, foldingType);
		}
		/// <summary>
		/// Adds the specified segment to the geometry.
		/// </summary>
		public void AddSegment(TextView textView, ISegment segment)
		{
			if (textView == null)
				throw new ArgumentNullException("textView");
			Size pixelSize = PixelSnapHelpers.GetPixelSize(textView);
			foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) {
				AddRectangle(pixelSize, r);
			}
		}
 public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
 {
     StringBuilder stringBuilder = new StringBuilder();
       int stepB = m_schemaObject.GenerateMin(stringBuilder, m_jsonEditorViewModel.File.Path);
       textArea.Document.Replace(completionSegment, stringBuilder.ToString());
       m_jsonEditorViewModel.Caret.Offset -= stepB;
       m_jsonEditorViewModel.AutoCompleteSchemaObject = m_schemaObject;
       m_jsonEditorViewModel.UpdateAutoCompletList = true;
 }
		public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
		{
			textArea.Document.Replace(completionSegment, Text);

			// Get the current line and try to suggest attributes
			DocumentLine currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
			string lineText = textArea.Document.GetText(currentLine.Offset, currentLine.Length);
			_completer.CompleteAttributeName(lineText, textArea.Caret.Offset - currentLine.Offset);
		}
        /// <summary>
        /// Creates the message control for the given message.
        /// </summary>
        /// <param name="messageControlContainer">message control container</param>
        /// <param name="messageEventArgs">message</param>
        /// <param name="bilingualDocument">bilingual document</param>
        /// <param name="sourceSegment">source segment</param>
        /// <param name="targetSegment">target segment</param>
        /// <returns>message control</returns>
        public UserControl CreateMessageControl(IMessageControlContainer messageControlContainer, MessageEventArgs messageEventArgs, IBilingualDocument bilingualDocument, ISegment sourceSegment, ISegment targetSegment)
        {
            if (!SupportsMessage(messageEventArgs))
            {
                throw new ArgumentException("messageEventArgs is not supported by this message control plug-in", "messageEventArgs");
            }

            return new CustomMessageControl(messageEventArgs, bilingualDocument, sourceSegment, targetSegment);
        }
        public IndexSegment(int sourceFeatureID, ISegment location)
        {
            this.SourceFeatureID = sourceFeatureID;

            if (SpatialReferenceHelper.IsBCAlbers(location.SpatialReference) == false)
                location.Project(SpatialReferenceHelper.BCAlbersSpatialReference);

            this.Segment = location;
        }
Exemple #31
0
        private static IEnumerable <Tuple <int, int> > GetOffsetForLinesInSegmentOnScreen(TextView textView, ISegment segment,
                                                                                          bool extendToFullWidthAtLineEnd = false)
        {
            var segmentStart = segment.Offset;
            var segmentEnd   = segment.Offset + segment.Length;

            if (segmentStart > textView.TextDocument.TextLength)
            {
                segmentStart = textView.TextDocument.TextLength;
            }

            if (segmentEnd > textView.TextDocument.TextLength)
            {
                segmentEnd = textView.TextDocument.TextLength;
            }

            var start = new TextViewPosition(textView.TextDocument.GetLocation(segmentStart));
            var end   = new TextViewPosition(textView.TextDocument.GetLocation(segmentEnd));

            foreach (var line in textView.VisualLines)
            {
                if (!line.DocumentLine.IsDeleted)
                {
                    if (line.Offset > segmentEnd)
                    {
                        break;
                    }

                    if (line.EndOffset < segmentStart)
                    {
                        continue;
                    }

                    // find start and begining in current line.
                    var lineStartOffset = line.Offset;

                    if (segment.Offset > line.Offset)
                    {
                        lineStartOffset = line.Offset + (segment.Offset - line.Offset);
                    }

                    var lineEndOffset = line.EndOffset;

                    if (segment.EndOffset < line.EndOffset)
                    {
                        lineEndOffset = line.EndOffset - (line.EndOffset - segment.EndOffset);
                    }

                    // generate rect for section in this line.
                    yield return(new Tuple <int, int>(lineStartOffset, lineEndOffset));
                }
            }
        }
Exemple #32
0
 public SimpleSegment(ISegment segment)
 {
     Debug.Assert(segment != null);
     this.Offset = segment.Offset;
     this.Length = segment.Length;
 }
Exemple #33
0
 public Conflict(ISegment mySegment, ISegment theirSegment, ISegment startSegment, ISegment dividerSegment, ISegment endSegment)
 {
     this.MySegment      = mySegment;
     this.TheirSegment   = theirSegment;
     this.StartSegment   = startSegment;
     this.DividerSegment = dividerSegment;
     this.EndSegment     = endSegment;
 }
Exemple #34
0
 public static IMessage Message(ISegment Segment)
 {
     return(new Message(Segment));
 }
        /// <summary> Returns the expected XML element name for the given child of a message constituent
        /// of the given class (the class should be a Composite or Segment class).
        /// </summary>

        /*private String makeElementName(Class c, int child) {
         * String longClassName = c.getName();
         * String shortClassName = longClassName.substring(longClassName.lastIndexOf('.') + 1, longClassName.length());
         * if (shortClassName.startsWith("Valid")) {
         * shortClassName = shortClassName.substring(5, shortClassName.length());
         * }
         * return shortClassName + "." + child;
         * }*/

        /// <summary>Returns the expected XML element name for the given child of the given Segment </summary>
        private System.String MakeElementName(ISegment s, int child)
        {
            return(s.GetStructureName() + "." + child);
        }
Exemple #36
0
        public IPipelineBuilder Do(ISegment segment)
        {
            AddSegmentRunner(f => f.CreateSegmentRunner(segment));

            return(this);
        }
Exemple #37
0
        /// <summary>
        /// Packs parts into a single message body.
        /// </summary>
        /// <param name="length">Message length.</param>
        /// <param name="version">Message version.</param>
        /// <param name="header">Header.</param>
        /// <param name="parameters">Security parameters.</param>
        /// <param name="data">Scope data.</param>
        /// <returns>The <see cref="Sequence" /> object that represents the message body.</returns>
        public static Sequence PackMessage(byte[] length, VersionCode version, ISegment header, ISegment parameters, ISnmpData data)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            var items = new[]
            {
                new Integer32((int)version),
                header.GetData(version),
                parameters.GetData(version),
                data
            };

            return(new Sequence(length, items));
        }
Exemple #38
0
 public int IndexOf(ISegment item) => InternalList.IndexOf(item);
Exemple #39
0
 public void Insert(int index, ISegment item) => InternalList.Insert(index, item);
Exemple #40
0
 public void Add(ISegment item) => InternalList.Add(item);
Exemple #41
0
 public bool Contains(ISegment item) => InternalList.Contains(item);
Exemple #42
0
 public bool Remove(ISegment item) => InternalList.Remove(item);
Exemple #43
0
 /// <summary>
 /// Make one.
 /// Note: index is not the index of the segment in its owning paragraph.
 /// </summary>
 /// <param name="seg">A segment with at least index+1 analysis references.</param>
 /// <param name="index">The index of an analysis in the segment.</param>
 public AnalysisOccurrence(ISegment seg, int index)
 {
     Segment = seg;
     Index   = index;
 }
Exemple #44
0
 public void UpdateSegment(ISegment segment, Guid id)
 {
     _segmentData.Update(segment, id);
 }
Exemple #45
0
 public HighlightedLine(ISegment textSegment, IReadOnlyList <ColoredSegment> segments)
 {
     TextSegment = textSegment;
     Segments    = segments;
 }
Exemple #46
0
        /// <summary>
        /// Creates a HTML fragment from a part of a document.
        /// </summary>
        /// <param name="document">The document to create HTML from.</param>
        /// <param name="highlighter">The highlighter used to highlight the document. <c>null</c> is valid and will create HTML without any highlighting.</param>
        /// <param name="segment">The part of the document to create HTML for. You can pass <c>null</c> to create HTML for the whole document.</param>
        /// <param name="options">The options for the HTML creation.</param>
        /// <returns>HTML code for the document part.</returns>
        public static string CreateHtmlFragment(TextDocument document, IHighlighter highlighter, ISegment segment, HtmlOptions options)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (highlighter != null && highlighter.Document != document)
            {
                throw new ArgumentException("Highlighter does not belong to the specified document.");
            }
            if (segment == null)
            {
                segment = new SimpleSegment(0, document.TextLength);
            }

            StringBuilder html             = new StringBuilder();
            int           segmentEndOffset = segment.EndOffset;
            DocumentLine  line             = document.GetLineByOffset(segment.Offset);

            while (line != null && line.Offset < segmentEndOffset)
            {
                HighlightedLine highlightedLine;
                if (highlighter != null)
                {
                    highlightedLine = highlighter.HighlightLine(line.LineNumber);
                }
                else
                {
                    highlightedLine = new HighlightedLine(document, line);
                }
                SimpleSegment s = segment.GetOverlap(line);
                if (html.Length > 0)
                {
                    html.AppendLine("<br>");
                }
                html.Append(highlightedLine.ToHtml(s.Offset, s.EndOffset, options));
                line = line.NextLine;
            }
            return(html.ToString());
        }
        public static void Main(System.String[] args)
        {
            if (args.Length != 1)
            {
                System.Console.Out.WriteLine("Usage: XMLParser pipe_encoded_file");
                System.Environment.Exit(1);
            }

            //read and parse message from file
            try
            {
                PipeParser         parser      = new PipeParser();
                System.IO.FileInfo messageFile = new System.IO.FileInfo(args[0]);
                long fileLength          = SupportClass.FileLength(messageFile);
                System.IO.StreamReader r = new System.IO.StreamReader(messageFile.FullName, System.Text.Encoding.Default);
                char[] cbuf = new char[(int)fileLength];
                System.Console.Out.WriteLine("Reading message file ... " + r.Read((System.Char[])cbuf, 0, cbuf.Length) + " of " + fileLength + " chars");
                r.Close();
                System.String messString = System.Convert.ToString(cbuf);
                IMessage      mess       = parser.Parse(messString);
                System.Console.Out.WriteLine("Got message of type " + mess.GetType().FullName);

                NHapi.Base.Parser.XMLParser xp = new AnonymousClassXMLParser();

                //loop through segment children of message, encode, print to console
                System.String[] structNames = mess.Names;
                for (int i = 0; i < structNames.Length; i++)
                {
                    IStructure[] reps = mess.GetAll(structNames[i]);
                    for (int j = 0; j < reps.Length; j++)
                    {
                        if (typeof(ISegment).IsAssignableFrom(reps[j].GetType()))
                        {
                            //ignore groups
                            System.Xml.XmlDocument docBuilder = new System.Xml.XmlDocument();
                            System.Xml.XmlDocument doc        = new System.Xml.XmlDocument(); //new doc for each segment
                            System.Xml.XmlElement  root       = doc.CreateElement(reps[j].GetType().FullName);
                            doc.AppendChild(root);
                            xp.Encode((ISegment)reps[j], root);
                            System.IO.StringWriter out_Renamed = new System.IO.StringWriter();
                            System.Console.Out.WriteLine("Segment " + reps[j].GetType().FullName + ": \r\n" + doc.OuterXml);

                            System.Type[]   segmentConstructTypes = new System.Type[] { typeof(IMessage) };
                            System.Object[] segmentConstructArgs  = new System.Object[] { null };
                            ISegment        s = (ISegment)reps[j].GetType().GetConstructor(segmentConstructTypes).Invoke(segmentConstructArgs);
                            xp.Parse(s, root);
                            System.Xml.XmlDocument doc2  = new System.Xml.XmlDocument();
                            System.Xml.XmlElement  root2 = doc2.CreateElement(s.GetType().FullName);
                            doc2.AppendChild(root2);
                            xp.Encode(s, root2);
                            System.IO.StringWriter out2 = new System.IO.StringWriter();
                            System.Xml.XmlWriter   ser  = System.Xml.XmlWriter.Create(out2);
                            doc.WriteTo(ser);
                            if (out2.ToString().Equals(out_Renamed.ToString()))
                            {
                                System.Console.Out.WriteLine("Re-encode OK");
                            }
                            else
                            {
                                System.Console.Out.WriteLine("Warning: XML different after parse and re-encode: \r\n" + out2.ToString());
                            }
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                SupportClass.WriteStackTrace(e, Console.Error);
            }
        }
 public void VisitSegment(ISegment segment)
 {
     VisitChilderen(segment);
 }
Exemple #49
0
 public TreeSegment(ISegment segment) : this(segment.Offset, segment.Length)
 {
 }
Exemple #50
0
 public bool InterSection(ISegment seg)
 {
     return(getStartPoint() <= getEndPoint() && getStartPoint() <= seg.getEndPoint() &&
            seg.getStartPoint() <= getEndPoint() && seg.getStartPoint() <= seg.getEndPoint());
 }
Exemple #51
0
 public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
 {
     textArea.Document.Replace(completionSegment, this.Text);
 }
Exemple #52
0
        static int PasteFrom(Clipboard clipboard, TextEditorData data, bool preserveSelection, int insertionOffset, bool preserveState)
        {
            int result = -1;

            if (!data.CanEdit(data.Document.OffsetToLineNumber(insertionOffset)))
            {
                return(result);
            }
            if (clipboard.WaitIsTargetAvailable(CopyOperation.MD_ATOM))
            {
                clipboard.RequestContents(CopyOperation.MD_ATOM, delegate(Clipboard clp, SelectionData selectionData) {
                    if (selectionData.Length > 0)
                    {
                        byte[] selBytes = selectionData.Data;

                        string text     = System.Text.Encoding.UTF8.GetString(selBytes, 1, selBytes.Length - 1);
                        bool pasteBlock = (selBytes [0] & 1) == 1;
                        bool pasteLine  = (selBytes [0] & 2) == 2;
                        if (!pasteBlock && !pasteLine)
                        {
                            return;
                        }

                        data.Document.BeginAtomicUndo();
                        if (preserveSelection && data.IsSomethingSelected)
                        {
                            data.DeleteSelectedText();
                        }

                        data.Caret.PreserveSelection = true;
                        if (pasteBlock)
                        {
                            string[] lines = text.Split('\r');
                            int lineNr     = data.Document.OffsetToLineNumber(insertionOffset);
                            int col        = insertionOffset - data.Document.GetLine(lineNr).Offset;
                            int visCol     = data.Document.GetLine(lineNr).GetVisualColumn(data, col);
                            LineSegment curLine;
                            int lineCol = col;
                            result      = 0;
                            for (int i = 0; i < lines.Length; i++)
                            {
                                while (data.Document.LineCount <= lineNr + i)
                                {
                                    data.Insert(data.Document.Length, Environment.NewLine);
                                    result += Environment.NewLine.Length;
                                }
                                curLine = data.Document.GetLine(lineNr + i);
                                if (lines [i].Length > 0)
                                {
                                    lineCol = curLine.GetLogicalColumn(data, visCol);
                                    if (curLine.EditableLength + 1 < lineCol)
                                    {
                                        result += lineCol - curLine.EditableLength;
                                        data.Insert(curLine.Offset + curLine.EditableLength, new string (' ', lineCol - curLine.EditableLength));
                                    }
                                    data.Insert(curLine.Offset + lineCol, lines [i]);
                                    result += lines [i].Length;
                                }
                                if (!preserveState)
                                {
                                    data.Caret.Offset = curLine.Offset + lineCol + lines [i].Length;
                                }
                            }
                        }
                        else if (pasteLine)
                        {
                            result = text.Length;
                            LineSegment curLine = data.Document.GetLine(data.Caret.Line);
                            data.Insert(curLine.Offset, text + data.EolMarker);
                            if (!preserveState)
                            {
                                data.Caret.Offset += text.Length + data.EolMarker.Length;
                            }
                        }

                        /*				data.MainSelection = new Selection (data.Document.OffsetToLocation (insertionOffset),
                         *                                  data.Caret.Location,
                         *                                  lines.Length > 1 ? SelectionMode.Block : SelectionMode.Normal);*/
                        if (!preserveState)
                        {
                            data.ClearSelection();
                        }
                        data.Caret.PreserveSelection = false;
                        data.Document.EndAtomicUndo();
                    }
                });
            }

            if (result < 0 && clipboard.WaitIsTextAvailable())
            {
                clipboard.RequestText(delegate(Clipboard clp, string text) {
                    if (string.IsNullOrEmpty(text))
                    {
                        return;
                    }
                    data.Document.BeginAtomicUndo();
                    int caretPos = data.Caret.Offset;
                    if (data.IsSomethingSelected && data.MainSelection.SelectionMode == SelectionMode.Block)
                    {
                        data.Caret.PreserveSelection = true;
                        data.DeleteSelectedText(false);
                        int textLength = 0;
                        int column     = data.Caret.Column;
                        int minLine    = data.MainSelection.MinLine;
                        int maxLine    = data.MainSelection.MaxLine;
                        for (int lineNumber = minLine; lineNumber <= maxLine; lineNumber++)
                        {
                            int offset = data.Document.GetLine(lineNumber).Offset + column - 1;
                            textLength = data.Insert(offset, text);
                            data.PasteText(offset, text);
                        }

                        data.Caret.Offset           += textLength;
                        data.MainSelection.Anchor    = new DocumentLocation(System.Math.Max(DocumentLocation.MinLine, data.Caret.Line == minLine ? maxLine : minLine), System.Math.Max(DocumentLocation.MinColumn, data.Caret.Column - textLength));
                        data.MainSelection.Lead      = new DocumentLocation(data.Caret.Line, data.Caret.Column);
                        data.Caret.PreserveSelection = false;
                        data.Document.CommitMultipleLineUpdate(data.MainSelection.MinLine, data.MainSelection.MaxLine);
                    }
                    else
                    {
                        ISegment selection = data.SelectionRange;
                        if (preserveSelection && data.IsSomethingSelected)
                        {
                            data.DeleteSelectedText();
                        }
                        data.Caret.PreserveSelection = true;
                        //int oldLine = data.Caret.Line;
                        int textLength = data.Insert(insertionOffset, text);
                        result         = textLength;

                        if (data.IsSomethingSelected && data.SelectionRange.Offset >= insertionOffset)
                        {
                            data.SelectionRange.Offset += textLength;
                        }
                        if (data.IsSomethingSelected && data.MainSelection.GetAnchorOffset(data) >= insertionOffset)
                        {
                            data.MainSelection.Anchor = data.Document.OffsetToLocation(data.MainSelection.GetAnchorOffset(data) + textLength);
                        }

                        data.Caret.PreserveSelection = false;
                        if (!preserveState)
                        {
                            data.Caret.Offset += textLength;
                        }
                        else
                        {
                            if (caretPos >= insertionOffset)
                            {
                                data.Caret.Offset += textLength;
                            }
                            if (selection != null)
                            {
                                int offset = selection.Offset;
                                if (offset >= insertionOffset)
                                {
                                    offset += textLength;
                                }
                                data.SelectionRange = new Segment(offset, selection.Length);
                            }
                        }
                        data.PasteText(insertionOffset, text);
                    }
                    data.Document.EndAtomicUndo();
                });
            }

            return(result);
        }
 public VirtualSegment(ISegment physicalContents, uint virtualSize)
 {
     PhysicalContents = physicalContents;
     VirtualSize      = virtualSize;
 }
Exemple #54
0
 /// <summary>
 /// Make one.
 /// </summary>
 public LocatedAnalysisOccurrence(ISegment seg, int index, int beginOffset) : base(seg, index)
 {
     BeginOffset = beginOffset;
     EndOffset   = beginOffset + Analysis.GetForm(BaselineWs).Length;
 }
Exemple #55
0
 public AlignedSegment(ISegment segment, uint alignment)
 {
     Segment   = segment;
     Alignment = alignment;
 }
 /// <summary>Get the field at the specified index.</summary>
 /// <param name="ancestor">Ancestor element.</param>
 /// <param name="index">Index of the descendant.</param>
 /// <returns>Descendant element.</returns>
 public static IField Field(this ISegment ancestor, int index)
 {
     return(ancestor[index] as IField);
 }
Exemple #57
0
 /// <summary>
 /// Creates a new AnchorSegment that creates new anchors.
 /// </summary>
 public AnchorSegment(TextDocument document, ISegment segment)
     : this(document, ThrowUtil.CheckNotNull(segment, "segment").Offset, segment.Length)
 {
 }
Exemple #58
0
 public void CreateSegment(ISegment segment)
 {
     _segmentData.Create(segment);
 }
        public void UpdateSegmentListOnDocumentChange <T>(List <T> list, DocumentEventArgs e) where T : ISegment
        {
            int removedCharacters  = e.Length > 0 ? e.Length : 0;
            int insertedCharacters = e.Text != null ? e.Text.Length : 0;

            for (int i = 0; i < list.Count; ++i)
            {
                ISegment s            = list[i];
                int      segmentStart = s.Offset;
                int      segmentEnd   = s.Offset + s.Length;

                if (e.Offset <= segmentStart)
                {
                    segmentStart -= removedCharacters;
                    if (segmentStart < e.Offset)
                    {
                        segmentStart = e.Offset;
                    }
                }
                if (e.Offset < segmentEnd)
                {
                    segmentEnd -= removedCharacters;
                    if (segmentEnd < e.Offset)
                    {
                        segmentEnd = e.Offset;
                    }
                }

                if (segmentStart <= segmentEnd)     //DC
                {
                    return;
                }
                //Debug.Assert(segmentStart <= segmentEnd);//DC

                if (segmentStart == segmentEnd)
                {
                    list.RemoveAt(i);
                    --i;
                    continue;
                }

                if (e.Offset <= segmentStart)
                {
                    segmentStart += insertedCharacters;
                }
                if (e.Offset < segmentEnd)
                {
                    segmentEnd += insertedCharacters;
                }

                if (segmentStart < segmentEnd)      //DC
                {
                    return;
                }

                //Debug.Assert(segmentStart < segmentEnd);  //DC

                s.Offset = segmentStart;
                s.Length = segmentEnd - segmentStart;
            }
        }
Exemple #60
0
 public static IEnumerable <IDocumentLine> GetLinesForSegmentOnScreen(TextView textView, ISegment segment,
                                                                      bool extendToFullWidthAtLineEnd = false)
 {
     foreach (var tuple in GetOffsetForLinesInSegmentOnScreen(textView, segment, extendToFullWidthAtLineEnd))
     {
         yield return(textView.TextDocument.GetLineByOffset(tuple.Item1));
     }
 }