Beispiel #1
0
        internal void MoveCaretToFirstLine(Rect rect)
        {
            TextPointer tp      = Document.ContentStart;
            TextPointer last_tp = tp;

            Rect r = tp.GetCharacterRect(LogicalDirection.Forward);

            while (tp != null && r.X < rect.X && tp.CompareTo(Document.ContentEnd) != 0)
            {
                tp = tp.GetNextInsertionPosition(LogicalDirection.Forward);
                if (tp == null)
                {
                    break;
                }
                r       = tp.GetCharacterRect(LogicalDirection.Forward);
                last_tp = tp;
            }

            if (last_tp != null)
            {
                CaretPosition = last_tp;
            }

            // Workaround for bug in .NET 3.0
            if (!CaretPosition.IsAtLineStartPosition)
            {
                EditingCommands.MoveLeftByCharacter.Execute(null, this);
                EditingCommands.MoveRightByCharacter.Execute(null, this);
            }
            else if (CaretPosition.CompareTo(Document.ContentEnd) != 0)
            {
                EditingCommands.MoveRightByCharacter.Execute(null, this);
                EditingCommands.MoveLeftByCharacter.Execute(null, this);
            }
        }
Beispiel #2
0
 private string FindBreak(TextPointer pointer)
 {
     Rect rectAtStart = pointer.GetCharacterRect(LogicalDirection.Forward);
     pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward);
     Rect currentRect = pointer.GetCharacterRect(LogicalDirection.Forward);
     while (currentRect.Bottom == rectAtStart.Bottom)
     {
         pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward);
         currentRect = pointer.GetCharacterRect(LogicalDirection.Forward);
     }
     string textBeforeBreak = pointer.GetTextInRun(LogicalDirection.Backward);
     string textAfterBreak = pointer.GetTextInRun(LogicalDirection.Forward);
     return textAfterBreak;
 }
Beispiel #3
0
        // По координате получает указатель в тексте. Если координаты берутся мышиные, мышь нужно брать относительно
        // корневого элемента управления в котором сидит FlowDocument (как пример)
        public static TextPointer GetPositionFromPoint(this Run run, Point searchForPoint)
        {
            // Работает тормозно. Возможно стоит пробежаться 1 раз при перерисовке flowdocument-а и в какое нибудь дерево или чето подобное запихнуть все эти рект-ы
            // чтобы быстро находить букву по позиции

            TextPointer currentTextPointer = run.ContentStart;
            TextPointer nextTextPointer    = currentTextPointer.GetNextInsertionPosition(LogicalDirection.Forward);

            while (nextTextPointer != null)
            {
                Rect currentRect = currentTextPointer.GetCharacterRect(LogicalDirection.Forward);
                Rect nextRect    = nextTextPointer.GetCharacterRect(LogicalDirection.Backward);

                if (searchForPoint.X >= currentRect.X && searchForPoint.X <= nextRect.X &&
                    searchForPoint.Y >= currentRect.Top && searchForPoint.Y <= nextRect.Bottom)
                {
                    return(currentTextPointer);
                }

                currentTextPointer = nextTextPointer;
                nextTextPointer    = nextTextPointer.GetNextInsertionPosition(LogicalDirection.Forward);
            }

            return(null);
        }
Beispiel #4
0
        // This method is intended to listen for the ContextMenuOpening event from a RichTextBox.
        // It will position the custom context menu at the end of the current selection.
        void richTextBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            // Sender must be RichTextBox.
            RichTextBox rtb = sender as RichTextBox;

            if (rtb == null)
            {
                return;
            }

            ContextMenu contextMenu = rtb.ContextMenu;

            contextMenu.PlacementTarget = rtb;

            // This uses HorizontalOffset and VerticalOffset properties to position the menu,
            // relative to the upper left corner of the parent element (RichTextBox in this case).
            contextMenu.Placement = PlacementMode.RelativePoint;

            // Compute horizontal and vertical offsets to place the menu relative to selection end.
            TextPointer position = rtb.Selection.End;

            if (position == null)
            {
                return;
            }

            Rect positionRect = position.GetCharacterRect(LogicalDirection.Forward);

            contextMenu.HorizontalOffset = positionRect.X;
            contextMenu.VerticalOffset   = positionRect.Y;

            // Finally, mark the event has handled.
            contextMenu.IsOpen = true;
            e.Handled          = true;
        }
        /* This method isn't working yet */
        void outputLogTextBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            RichTextBox rtb = sender as RichTextBox;

            if (rtb == null)
            {
                return;
            }

            rtb.ContextMenu.PlacementTarget = rtb;

            // This uses HorizontalOffset and VerticalOffset properties to position the menu,
            // relative to the upper left corner of the parent element (RichTextBox in this case).
            rtb.ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.RelativePoint;

            // Compute horizontal and vertical offsets to place the menu relative to selection end.
            TextPointer textPosition = rtb.Selection.End;

            if (textPosition == null)
            {
                return;
            }
            Rect textPositionRect = textPosition.GetCharacterRect(LogicalDirection.Forward);

            rtb.ContextMenu.HorizontalOffset = textPositionRect.X;
            rtb.ContextMenu.VerticalOffset   = textPositionRect.Y;

            // Finally, mark the event has handled.
            rtb.ContextMenu.IsOpen = true;
            e.Handled = true;
        }
Beispiel #6
0
        // A ContextMenu displays Cut, Copy and Paste commands
        private void RichTB_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            // Convert to a RichTextBox and check for null
            RichTextBox rtb = sender as RichTextBox;

            if (rtb == null)
            {
                return;
            }

            // Create ContextMenu
            ContextMenu contextMenu = rtb.ContextMenu;

            contextMenu.PlacementTarget = rtb;

            // This will place the menu at the point where it is right clicked
            contextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.RelativePoint;

            TextPointer position = rtb.Selection.End;

            if (position == null)
            {
                return;
            }

            // Create the menu
            Rect positionRect = position.GetCharacterRect(LogicalDirection.Forward);

            contextMenu.HorizontalOffset = positionRect.X;
            contextMenu.VerticalOffset   = positionRect.Y;

            // Finally, mark the event as handled
            contextMenu.IsOpen = true;
            e.Handled          = true;
        }
Beispiel #7
0
 internal virtual Rect[] GetCharacterRects(TextPointer startPointer, TextPointer endPointer)
 {
     if (endPointer != null)
     {
         return new Rect[2] {
                    startPointer.GetCharacterRect(LogicalDirection.Forward), endPointer.GetCharacterRect(LogicalDirection.Backward)
         }
     }
     ;
     else
     {
         return new Rect[1] {
                    startPointer.GetCharacterRect(LogicalDirection.Forward)
         }
     };
 }
Beispiel #8
0
        }//end of Generate Doc

        private void RichTb_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            RichTextBox rtb = sender as RichTextBox;

            if (rtb == null)
            {
                return;
            }

            ContextMenu contextMenu = rtb.ContextMenu;

            //make it appaer when you right click it
            contextMenu.PlacementTarget = rtb;

            contextMenu.Placement = PlacementMode.RelativePoint;

            TextPointer position = rtb.Selection.End;

            if (position == null)
            {
                return;
            }

            Rect positionRect = position.GetCharacterRect(LogicalDirection.Forward);

            contextMenu.HorizontalOffset = positionRect.X;
            contextMenu.VerticalOffset   = positionRect.Y;

            contextMenu.IsOpen = true;
            e.Handled          = true;
        }
Beispiel #9
0
        //returns [0]=Rect of char at end of first line, [1]=Rect of char at start of second line
        internal static Rect[] FindStartEndOfVisualLineRects(TextPointer start, Rect startRect)
        {
            TextPointer next = start;
            Rect        nextRect;

            while ((next = next.GetNextInsertionPosition(LogicalDirection.Forward)) != null)
            {
                nextRect = next.GetCharacterRect(LogicalDirection.Forward);
                if (nextRect.Top != startRect.Top)
                {
                    return new Rect[2] {
                               next.GetCharacterRect(LogicalDirection.Backward), nextRect
                    }
                }
                ;                                                                                     //for some reason next.GetCharacterRect(LogicalDirection.Backward) is not the same as 'prior' (prev value of 'next')
            }
            return(null);
        }
Beispiel #10
0
        public static IntellisensePopupPresenter Build(UIElement parent, TextPointer positionPointer, TextPoiterChanged target)
        {
            var view = new IntellisensePopup {
                PlacementTarget    = parent,
                PlacementRectangle = positionPointer.GetCharacterRect(LogicalDirection.Forward)
            };

            view.presenter.PositionPointer = positionPointer;
            view.presenter.TargetVariable  = target;
            return(view.presenter);
        }
 private void _viewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
 {
     if (e.PropertyName == "SelectedSearchResult")
     {
         TextRange tr = _viewModel.SelectedSearchResult;
         if (tr != null)
         {
             MainTextBox.Selection.Select(tr.Start, tr.End);
             TextPointer t = MainTextBox.Selection.Start;
             Rect        r = t.GetCharacterRect(LogicalDirection.Backward);
             mainScrollViewer.ScrollToVerticalOffset(r.Y * MainTextBoxScaleTransform.ScaleY);
             MainTextBox.Focus();
         }
     }
 }
Beispiel #12
0
        private void ResetAssistListBoxLocation()
        {
            //Rect rect = this.CaretPosition.GetCharacterRect(LogicalDirection.Forward);
            //double left = rect.X >= 20? rect.X : 20;
            //double top = rect.Y >= 20 ? rect.Y + 20 : 20;
            ////left += this.Padding.Left;
            //top += 10;
            //AssistListBox.SetCurrentValue(ListBox.MarginProperty, new Thickness(left, top, 0, 0));
            TextPointer start = this.Selection.Start;

            System.Windows.Rect rect = start.GetCharacterRect(LogicalDirection.Forward);
            Point point = rect.BottomLeft;

            AssistPopup.HorizontalOffset = point.X + 160;
            AssistPopup.VerticalOffset   = -(AssistListBox.ActualHeight - point.Y) - 25;
        }
Beispiel #13
0
        private void GetCaretPosition(out int ColumnNumber, out int LineNumber)
        {
            TextPointer current = rtbConsole.CaretPosition;
            var         start   = current.GetEdgeTextPointer(LogicalDirection.Backward); // Word position before caret
            var         end     = current.GetEdgeTextPointer(LogicalDirection.Forward);  // Word position after caret

            current.GetCharacterRect(LogicalDirection.Forward);
            current.GetLineStartPosition(-int.MaxValue, out LineNumber);
            if (LineNumber < 0)
            {
                LineNumber *= -1;
            }
            LineNumber++;

            //var p = rtbConsole.Document.Blocks.ElementAt(lineNumber - 1) as Paragraph;
            ColumnNumber = start.GetLineStartPosition(0).GetOffsetToPosition(current) - 3;
        }
        public IViewTextPointer GetPositionFromPoint(Point point)
        {
            TextPointer textPointer     = this.FlowDocumentScrollViewer.Document.ContentStart;
            TextPointer platformPointer = (TextPointer)null;
            double      num             = double.MaxValue;

            for (; textPointer != null; textPointer = textPointer.GetPositionAtOffset(1))
            {
                Rect   characterRect = textPointer.GetCharacterRect(LogicalDirection.Forward);
                double length        = (new Point(characterRect.Left, (characterRect.Top + characterRect.Bottom) / 2.0) - point).Length;
                if (length < num)
                {
                    num             = length;
                    platformPointer = textPointer;
                }
            }
            return(this.WrapTextPointer(platformPointer));
        }
        private static void ConvertTextRangeToGeometry(TextRange textRange, FlowDirection flowDirection, List <PathGeometry> pathList)
        {
            TextPointer position1 = textRange.Start.GetInsertionPosition(LogicalDirection.Forward);

            for (TextPointer insertionPosition = position1.GetNextInsertionPosition(LogicalDirection.Forward); insertionPosition != null && insertionPosition.CompareTo(textRange.End) <= 0; insertionPosition = insertionPosition.GetNextInsertionPosition(LogicalDirection.Forward))
            {
                TextRange textRange1    = new TextRange(position1, insertionPosition);
                Rect      characterRect = position1.GetCharacterRect(LogicalDirection.Forward);
                characterRect.Union(insertionPosition.GetCharacterRect(LogicalDirection.Backward));
                FontFamily  fontFamily = (FontFamily)textRange1.GetPropertyValue(TextElement.FontFamilyProperty);
                FontStyle   style      = (FontStyle)textRange1.GetPropertyValue(TextElement.FontStyleProperty);
                FontWeight  weight     = (FontWeight)textRange1.GetPropertyValue(TextElement.FontWeightProperty);
                FontStretch stretch    = (FontStretch)textRange1.GetPropertyValue(TextElement.FontStretchProperty);
                double      emSize     = (double)textRange1.GetPropertyValue(TextElement.FontSizeProperty);
                Typeface    typeface   = new Typeface(fontFamily, style, weight, stretch);
                PathConversionHelper.ConvertFormattedTextToGeometry(new FormattedText(textRange1.Text, CultureInfo.CurrentCulture, flowDirection, typeface, emSize, (Brush)Brushes.Red), characterRect.TopLeft, pathList);
                position1 = insertionPosition;
            }
        }
Beispiel #16
0
    public static bool PositionVisibleIs(RichTextBox rtb, TextPointer pos)
    {
        // Rectangle around the character to check
        Rect r = pos.GetCharacterRect(LogicalDirection.Forward);

        // Upper left corner of the rectangle ...
        Point upperLeftCorner = r.Location;

        HitTestResult result = VisualTreeHelper.HitTest(rtb, upperLeftCorner);

        // ... is visible?
        if (result != null)
        {
            return(true);
        }
        else
        {
            return(false);
        }
    }
Beispiel #17
0
        private void PositionHand()
        {
            Rect r;

            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                TextPointer tp = rta.GetPositionFromPoint(lastRTAMouseMove.GetPosition(rta));
                r = tp.GetCharacterRect(LogicalDirection.Forward);
            }
            else
            {
                r = rta.Selection.End.GetCharacterRect(LogicalDirection.Forward);
            }

            if (r != Rect.Empty)
            {
                Canvas.SetLeft(caretHand, r.Left);
                Canvas.SetTop(caretHand, r.Bottom);
            }
        }
Beispiel #18
0
        private async void ContextMenuCommand_OnExecuted(object sender, ExecutedRoutedEventArgs args)
        {
            TextPointer objCaretPosition = richTextBox.CaretPosition;

            string strLastWord = richTextBox.CaretPosition.GetTextInRun(LogicalDirection.Backward).Split(' ').LastOrDefault();

            InitContextMenu(await objHelper.GetWordAsync(strLastWord));
            if (contextMenu.Items.Count == 0)
            {
                return;
            }

            contextMenu.PlacementTarget = richTextBox;
            contextMenu.Placement       = PlacementMode.RelativePoint;
            Rect objRectPosition = objCaretPosition.GetCharacterRect(LogicalDirection.Forward);

            contextMenu.HorizontalOffset = objRectPosition.X;
            contextMenu.VerticalOffset   = objRectPosition.Y;
            contextMenu.IsOpen           = true;
        }
        public static TextPointer GetPositionFromPoint(Run thiz, Point searchForPoint)
        {
            TextPointer ptrCurCharcter  = thiz.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward);
            TextPointer ptrNextCharcter = ptrCurCharcter.GetNextInsertionPosition(LogicalDirection.Forward);

            while (ptrNextCharcter != null)
            {
                Rect charcterInsertionPointRectangle     = ptrCurCharcter.GetCharacterRect(LogicalDirection.Forward);
                Rect nextCharcterInsertionPointRectangle = ptrNextCharcter.GetCharacterRect(LogicalDirection.Backward);

                if (searchForPoint.X >= charcterInsertionPointRectangle.X &&
                    searchForPoint.X <= nextCharcterInsertionPointRectangle.X &&
                    searchForPoint.Y >= charcterInsertionPointRectangle.Top &&
                    searchForPoint.Y <= charcterInsertionPointRectangle.Bottom)
                {
                    return(ptrCurCharcter);
                }

                ptrCurCharcter  = ptrCurCharcter.GetNextInsertionPosition(LogicalDirection.Forward);
                ptrNextCharcter = ptrNextCharcter.GetNextInsertionPosition(LogicalDirection.Forward);
            }
            return(null);
        }
Beispiel #20
0
        void CalculatePopupLocation(TextPointer tpCaret)
        {
            var rect = tpCaret.GetCharacterRect(LogicalDirection.Backward);

            if (this._isPaste)
            {
                //如果是通过键盘复制的文本,需要重新计算@列表的弹出位置
                TextPointer tpEnd = this.richBox.Document.ContentEnd;
                var         range = new TextRange(tpCaret, tpEnd);

                string pasteText = Clipboard.GetText();

                if ((pasteText + "\r\n").Equals(range.Text))
                {
                    rect = tpCaret.GetNextContextPosition(LogicalDirection.Forward).GetCharacterRect(LogicalDirection.Backward);
                }
            }

            Point p = new Point(rect.X, rect.Y);

            this.ppMember.HorizontalOffset = p.X + 20;
            this.ppMember.VerticalOffset   = p.Y + 60;
        }
Beispiel #21
0
        void RefreshData()
        {
            m_horizontalOffset         = m_scrollControl.HorizontalOffset;
            m_verticalOffset           = m_scrollControl.VerticalOffset;
            m_scrollViewerZoom         = m_scrollViewer.Zoom;
            m_scrollViewerActualWidth  = m_scrollViewer.ActualWidth;
            m_scrollViewerActualHeight = m_scrollViewer.ActualHeight;

            m_items.Clear();

            foreach (var inline in m_paragraph.Inlines)
            {
                Run run = inline as Run;

                if (run != null)
                {
                    TextPointer currentTextPointer = run.ContentStart;
                    TextPointer nextTextPointer    = currentTextPointer.GetNextInsertionPosition(LogicalDirection.Forward);

                    while (nextTextPointer != null)
                    {
                        Rect currentRect = currentTextPointer.GetCharacterRect(LogicalDirection.Forward);
                        Rect nextRect    = nextTextPointer.GetCharacterRect(LogicalDirection.Backward);

                        m_items.Add(new TextPointerWithRect()
                        {
                            rect            = new Rect(currentRect.X, currentRect.Top, nextRect.X - currentRect.X, nextRect.Bottom - currentRect.Top),
                            textPointer     = currentTextPointer,
                            nextTextPointer = nextTextPointer
                        });

                        currentTextPointer = nextTextPointer;
                        nextTextPointer    = nextTextPointer.GetNextInsertionPosition(LogicalDirection.Forward);
                    }
                }
            }
        }
Beispiel #22
0
        private static void refresh()
        {
            TextPointer currentWordStart = getTextPointerToWordStart(Editor.Selection);

            CurrentContext = getWordStartingAtDesignatedPos(currentWordStart);

            if (CurrentContext.Text.Length < 1 || !CurrentContext.Text.StartsWith(@"\"))
            {
                AutocompleteMenu.IsOpen = false;
                return;
            }

            Dictionary <String, String> options = findReplacementStrings(CurrentContext.Text);

            if (options.Count != 0)
            {
                ListBox lb = AutocompleteMenu.lb_actions;

                lb.Items.Clear();
                foreach (KeyValuePair <String, String> a in options)
                {
                    lb.Items.Add(a);
                }


                Rect pos = currentWordStart.GetCharacterRect(LogicalDirection.Backward);
                AutocompleteMenu.PlacementTarget    = Editor as UIElement;
                AutocompleteMenu.PlacementRectangle = pos;
                AutocompleteMenu.IsOpen             = true;
                lb.SelectedIndex = 0;
                AutocompleteMenu.Focus();
            }
            else
            {
                AutocompleteMenu.IsOpen = false;
            }
        }
    public static void ScrollToWord(
        this FlowDocument flowDocument,
        ScrollViewer scrollViewer,
        string word)
    {
        var currentText = flowDocument.ContentStart;

        while (true)
        {
            TextPointer nextText =
                currentText.GetNextContextPosition(
                    LogicalDirection.Forward);
            if (nextText == null)
            {
                return;
            }

            TextRange txt = new TextRange(currentText, nextText);

            int index = txt.Text.IndexOf(word, StringComparison.Ordinal);
            if (index > 0)
            {
                TextPointer start = currentText.GetPositionAtOffset(index);

                if (start != null)
                {
                    var rect = start.GetCharacterRect(
                        LogicalDirection.Forward);
                    scrollViewer.ScrollToVerticalOffset(rect.Y);
                }

                return;
            }

            currentText = nextText;
        }
    }
Beispiel #24
0
        private void Rtb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (IsDbgDisabled)
            {
                return;
            }
            if (ChangeEventHelper == null || ChangeEventHelper.IsInChange)
            {
                return;
            }
            if (!mShowWhitespaces)
            {
                return;
            }

            // invalidate some areas, but not too offen

            if (Environment.TickCount - PreviousTextChangedTime > 777)
            {
                var rtb = Rtb;

                foreach (var change in e.Changes)
                {
                    TextPointer start = rtb.Document.ContentStart.GetPositionAtOffset(change.Offset);
                    if (start == null)
                    {
                        continue;
                    }

                    TextPointer end = start.GetPositionAtOffset(Math.Max(change.RemovedLength, change.AddedLength));
                    if (end == null)
                    {
                        continue;
                    }

                    var start_rect  = start.GetCharacterRect(LogicalDirection.Forward);
                    var end_rect    = end.GetCharacterRect(LogicalDirection.Backward);
                    var change_rect = Rect.Union(start_rect, end_rect);
                    if (change_rect.IsEmpty)
                    {
                        continue;
                    }

                    //
                    change_rect = new Rect(change_rect.Left, change_rect.Top, rtb.ViewportWidth, change_rect.Height);
                    change_rect.Offset(rtb.HorizontalOffset, rtb.VerticalOffset);

                    lock (this)
                    {
                        for (int i = 0; i < PositionsSpaces.Count; ++i)
                        {
                            Rect r = PositionsSpaces[i];
                            if (r.IntersectsWith(change_rect))
                            {
                                PositionsSpaces[i] = Rect.Empty;
                            }
                        }

                        for (int i = 0; i < PositionsEols.Count; ++i)
                        {
                            Rect r = PositionsEols[i];
                            if (r.IntersectsWith(change_rect))
                            {
                                PositionsEols[i] = Rect.Empty;
                            }
                        }

                        if (PositionEof.IntersectsWith(change_rect))
                        {
                            PositionEof = Rect.Empty;
                        }
                    }
                }

                InvalidateVisual( );
            }

            PreviousTextChangedTime = Environment.TickCount;

            Loop.SendWaitAndExecute( );
        }
Beispiel #25
0
        //<SnippetHighlight>
        public void btnHighlight_Checked(object sender, RoutedEventArgs e)
        {
            if (btnHighlight.IsChecked.Value)
            {
                TextPointer tp       = rtb.ContentStart;
                TextPointer nextTp   = null;
                Rect        nextRect = Rect.Empty;
                Rect        tpRect   = tp.GetCharacterRect(LogicalDirection.Forward);
                Rect        lineRect = Rect.Empty;

                int lineCount = 1;

                while (tp != null)
                {
                    nextTp = tp.GetNextInsertionPosition(LogicalDirection.Forward);
                    if (nextTp != null && nextTp.IsAtInsertionPosition)
                    {
                        nextRect = nextTp.GetCharacterRect(LogicalDirection.Forward);
                        // this occurs for more than one line
                        if (nextRect.Top > tpRect.Top)
                        {
                            if (m_selectionRect.Count < lineCount)
                            {
                                m_selectionRect.Add(lineRect);
                            }
                            else
                            {
                                m_selectionRect[lineCount - 1] = lineRect;
                            }

                            lineCount++;

                            if (m_selectionRect.Count < lineCount)
                            {
                                m_selectionRect.Add(nextRect);
                            }

                            lineRect = nextRect;
                        }
                        else if (nextRect != Rect.Empty)
                        {
                            if (tpRect != Rect.Empty)
                            {
                                lineRect.Union(nextRect);
                            }
                            else
                            {
                                lineRect = nextRect;
                            }
                        }
                    }
                    tp     = nextTp;
                    tpRect = nextRect;
                }
                if (lineRect != Rect.Empty)
                {
                    if (m_selectionRect.Count < lineCount)
                    {
                        m_selectionRect.Add(lineRect);
                    }
                    else
                    {
                        m_selectionRect[lineCount - 1] = lineRect;
                    }
                }
                while (m_selectionRect.Count > lineCount)
                {
                    m_selectionRect.RemoveAt(m_selectionRect.Count - 1);
                }
            }
            else
            {
                if (highlightRect != null)
                {
                    highlightRect.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
        }
        /// <summary>
        /// Layout Text into two lines without any constraint and determine if a LineBreak occurs.
        /// </summary>
        /// <param name="secondLinePointer">TextPointer to where a LineBreak occurs</param>
        private void MeasureWithoutConstraint(out TextPointer secondLinePointer)
        {
            Debug.Assert(_textBlock1 != null && _textBlock2 != null);

            secondLinePointer = null;

            // Temporarily assign _textBlock1.Text to measure the length it would require
            _textBlock1.Text         = this.Text;
            _textBlock1.TextWrapping = TextWrapping.WrapWithOverflow;
            _textBlock1.Visibility   = Visibility.Visible;

            // This measures the TextBlock with infinite bounds to see what its ideal
            // (one-line) Width would be.  If this width is greater than the minimum
            // width for the label, we try halving its site to
            // spread the label to two lines.
            Size infinity = new Size(double.PositiveInfinity, double.PositiveInfinity);

            _textBlock1.Measure(infinity);

            double width     = _textBlock1.DesiredSize.Width;
            int    wordCount = string.IsNullOrEmpty(Text) ? 0 :  Text.Split().Length;

            if (wordCount > 1)
            {
                // Set the TextBlock's width to half of its desired with to spread it
                // to two lines, and re-run layout.
                _textBlock1.Width = Math.Max(1.0, width / 2.0);
                _textBlock1.Measure(infinity);
                _textBlock1.Arrange(new Rect(_textBlock1.DesiredSize));

                // If text flows into more than 2 lines
                TextPointer currentLinePointer = _textBlock1.ContentStart.GetLineStartPosition(2);
                if (currentLinePointer != null)
                {
                    double extraLength = 0.0;
                    Rect   lastCharacter, firstCharacter;

                    // Iterate through 3rd to (n-1)th line and add up their lengths.
                    TextPointer nextLinePointer = currentLinePointer.GetLineStartPosition(1);
                    while (nextLinePointer != null)
                    {
                        lastCharacter      = nextLinePointer.GetCharacterRect(LogicalDirection.Backward);
                        firstCharacter     = currentLinePointer.GetCharacterRect(LogicalDirection.Forward);
                        extraLength       += Math.Abs(lastCharacter.X - firstCharacter.X);
                        currentLinePointer = nextLinePointer;
                        nextLinePointer    = nextLinePointer.GetLineStartPosition(1);
                    }

                    // Add length of last line
                    lastCharacter  = _textBlock1.ContentEnd.GetCharacterRect(LogicalDirection.Backward);
                    firstCharacter = currentLinePointer.GetCharacterRect(LogicalDirection.Forward);
                    extraLength   += Math.Abs(lastCharacter.X - firstCharacter.X);

                    // Redistribute the extraLength among first two lines
                    _textBlock1.Width = _textBlock1.Width + extraLength / 2;
                    _textBlock1.Measure(infinity);
                    _textBlock1.Arrange(new Rect(_textBlock1.DesiredSize));
                }

                secondLinePointer = _textBlock1.ContentStart.GetLineStartPosition(1);

                // Clear the temporarily assigned values
                _textBlock1.ClearValue(TextBlock.WidthProperty);
            }

            _textBlock1.ClearValue(TextBlock.TextWrappingProperty);
        }
Beispiel #27
0
        bool CollectEols(ICancellable cnc, TextData td, Rect clip_rect, int top_index)
        {
            if (cnc.IsCancellationRequested)
            {
                return(false);
            }

            var rtb = Rtb;

            List <Rect> positions_eols = new List <Rect>( );

            // lines with no right-to-left segments

            var matches = EolRegex.Matches(td.Text);

            for (int i = 0; i < matches.Count; ++i)
            {
                if (cnc.IsCancellationRequested)
                {
                    return(false);
                }

                int index = matches[i].Index;

                if (index < top_index)
                {
                    continue;
                }

                int previous_index = i == 0 ? 0 : matches[i - 1].Index;

                bool has_RTL = false;

                for (int k = previous_index; k < index; ++k)
                {
                    if (cnc.IsCancellationRequested)
                    {
                        return(false);
                    }

                    if (UnicodeUtilities.IsRTL(td.Text[k]))
                    {
                        has_RTL = true;
                        break;
                    }
                }

                if (has_RTL)
                {
                    // RTL needs more navigation to find the rightmost X

                    Rect   left_rect = Rect.Empty;
                    double max_x     = double.NaN;

                    bool should_continue = false;
                    bool should_break    = false;

                    UITaskHelper.Invoke(rtb,
                                        () =>
                    {
                        TextPointer left = td.TextPointers.GetTextPointer(index);

                        left_rect = left.GetCharacterRect(LogicalDirection.Forward);

                        if (left_rect.Bottom < clip_rect.Top)
                        {
                            should_continue = true; return;
                        }
                        if (left_rect.Top > clip_rect.Bottom)
                        {
                            should_break = true; return;
                        }

                        max_x = left_rect.Left;

                        for (var tp = left.GetInsertionPosition(LogicalDirection.Backward); ;)
                        {
                            if (cnc.IsCancellationRequested)
                            {
                                return;
                            }

                            tp = tp.GetNextInsertionPosition(LogicalDirection.Backward);
                            if (tp == null)
                            {
                                break;
                            }

                            // WORKAROUND for lines like "0ראל", when "0" is matched and highlighted
                            tp = tp.GetInsertionPosition(LogicalDirection.Forward);

                            var rect_b = tp.GetCharacterRect(LogicalDirection.Backward);
                            var rect_f = tp.GetCharacterRect(LogicalDirection.Forward);

                            if (cnc.IsCancellationRequested)
                            {
                                return;
                            }

                            if (rect_b.Bottom < left_rect.Top && rect_f.Bottom < left_rect.Top)
                            {
                                break;
                            }

                            if (rect_b.Bottom > left_rect.Top)
                            {
                                if (max_x < rect_b.Left)
                                {
                                    max_x = rect_b.Left;
                                }
                            }

                            if (rect_f.Bottom > left_rect.Top)
                            {
                                if (max_x < rect_f.Left)
                                {
                                    max_x = rect_f.Left;
                                }
                            }
                        }
                    });

                    if (cnc.IsCancellationRequested)
                    {
                        return(false);
                    }
                    if (should_continue)
                    {
                        continue;
                    }
                    if (should_break)
                    {
                        break;
                    }

                    Rect eol_rect = new Rect(new Point(max_x, left_rect.Top), left_rect.Size);
                    eol_rect.Offset(rtb.HorizontalOffset, rtb.VerticalOffset);

                    positions_eols.Add(eol_rect);
                }
                else
                {
                    // no RTL; quick answer

                    Rect eol_rect = Rect.Empty;

                    UITaskHelper.Invoke(rtb,
                                        () =>
                    {
                        TextPointer left = td.TextPointers.GetTextPointer(index);

                        eol_rect = left.GetCharacterRect(LogicalDirection.Forward);
                    });

                    if (eol_rect.Bottom < clip_rect.Top)
                    {
                        continue;
                    }
                    if (eol_rect.Top > clip_rect.Bottom)
                    {
                        break;
                    }

                    eol_rect.Offset(rtb.HorizontalOffset, rtb.VerticalOffset);

                    positions_eols.Add(eol_rect);
                }
            }

            if (cnc.IsCancellationRequested)
            {
                return(false);
            }

            lock (this)
            {
                PositionsEols = positions_eols;
            }

            DelayedInvalidateVisual( );

            return(true);
        }
Beispiel #28
0
        private void UpdateCurrentTemplate()
        {
            var viewModel = ViewModel;

            if (viewModel == null)
            {
                return;
            }

            // update all views according to current template
            UpdateStack();
            UpdateAttributes();
            viewModel.Bytecode       = _currentFrame.Template.impl.Disassemble();
            TemplateTextBox.Document = new FlowDocument(new Paragraph(new Run(_currentFrame.Template.impl.Template)
            {
                FontFamily = new FontFamily("Consolas")
            }));
            viewModel.Ast = _currentFrame.Template.impl.Ast;

            #region new stuff

            // update tree view of template hierarchy and select assoc. text substring

            // compute path from root to currentST, create TreePath for tree widget
            //		List<ST> pathST = currentST.getEnclosingInstanceStack(true);
            ////		System.out.println("path="+pathST);
            //		Object[] path = new Object[pathST.size()];
            //		int j = 0;
            //		for (ST s : pathST) path[j++] = new JTreeSTModel.Node(s, interp.getDebugState(s));
            //		m.tree.setSelectionPath(new TreePath(path));

            // highlight output text and, if {...} subtemplate, region in ST src
            // get last event for currentST; it's the event that captures ST eval
            EvalExprEvent exprEvent = _currentEvent as EvalExprEvent;
            if (exprEvent != null)
            {
                Highlight(OutputTextBox.Document, exprEvent.OutputInterval);
                Highlight(TemplateTextBox.Document, exprEvent.SourceInterval);
            }
            else
            {
                EvalTemplateEvent templateEvent = _currentEvent as EvalTemplateEvent;
                if (templateEvent == null)
                {
                    List <InterpEvent> events = _currentFrame.GetDebugState().Events;
                    templateEvent = events[events.Count - 1] as EvalTemplateEvent;
                }

                //m.output.moveCaretPosition(e.outputStartChar);
                if (templateEvent != null)
                {
                    TextPointer position = Highlight(OutputTextBox.Document, templateEvent.OutputInterval);
                    if (position != null)
                    {
                        Rect rect = position.GetCharacterRect(LogicalDirection.Forward);
                        //OutputTextBox.ScrollToVerticalOffset(rect.Top);
                    }
                }

                if (_currentFrame.Template.IsAnonymousSubtemplate)
                {
                    Interval r = _currentFrame.Template.impl.TemplateRange;
                    //				System.out.println("currentST src range="+r);
                    //m.template.moveCaretPosition(r.a);
                    //TemplateTextBox.CaretPosition.
                    Highlight(TemplateTextBox.Document, r);
                }
            }

            #endregion

#if false
            // update tree view of template hierarchy and select assoc. text substring
            viewModel.Ast = currentTemplate.impl.ast;

            SetSelectionPath(viewModel.TemplateCallHierarchy[0], currentTemplate.GetEnclosingInstanceStack(true));

            Interval r = currentTemplate.impl.TemplateRange;
            if (currentTemplate.EnclosingInstance != null)
            {
                int i = GetIndexOfChild(currentTemplate.EnclosingInstance, currentTemplate);
                if (i == -1)
                {
                    Highlight(OutputTextBox.Document, null);
                    Highlight(TemplateTextBox.Document, r);
                }
                else
                {
                    InterpEvent e = ViewModel.Visualizer.Interpreter.GetEvents(currentTemplate.EnclosingInstance)[i];
                    if (e is EvalTemplateEvent)
                    {
                        if (currentTemplate.IsAnonymousSubtemplate)
                        {
                            Highlight(TemplateTextBox.Document, r);
                        }

                        Highlight(OutputTextBox.Document, e.OutputInterval);
                    }
                }
            }
            else
            {
                Highlight(OutputTextBox.Document, null);
                Highlight(TemplateTextBox.Document, r);
            }
#endif
        }
Beispiel #29
0
        private Tuple <List <TextRange>, List <double[]> > get_range(Point p, double w, double h) // 上下k行
        {
            List <TextRange> select = new List <TextRange>();

            var pos = richTextBox.GetPositionFromPoint(p, true);

            if (pos == null)
            {
                return(new Tuple <List <TextRange>, List <double[]> >(select, new List <double[]>()));
            }
            TextPointer begin = pos.GetLineStartPosition(-1);

            //  TextPointer lastEnd = poz.DocumentEnd.GetLineStartPosition(-3);
            if (begin == null)
            {
                begin = pos.DocumentStart;
            }
            if (begin.CompareTo(pos.DocumentEnd) < -1)
            {
                begin = pos.DocumentStart;
            }

            /*if (begin != null && lastEnd != null && begin.CompareTo(lastEnd) > 0)
             * {
             *  begin = lastEnd;
             * }*/
            TextPointer end = pos.GetLineStartPosition(1);

            begin = begin.GetPositionAtOffset(2);  //?? Magic 2
            Rect            beginR    = begin.GetCharacterRect(LogicalDirection.Forward);
            List <double[]> arrayPos  = new List <double[]>();
            TextPointer     lineBegin = begin;

            //Console.WriteLine("========================");
            while (begin != null)
            {
                if (end != null && begin.CompareTo(end) > -1)
                {
                    break;
                }
                if (begin.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    string   text       = begin.GetTextInRun(LogicalDirection.Forward);
                    string[] words      = text.Split(' ');
                    int      startIndex = 0;

                    foreach (var word in words)
                    {
                        if (word.Length > 0)
                        {
                            // Console.WriteLine("startIndes:{0}, word.length:{1}", startIndex, word.Length);
                            TextPointer headP = lineBegin.GetPositionAtOffset(startIndex, LogicalDirection.Forward);
                            TextPointer tailP = lineBegin.GetPositionAtOffset(startIndex + word.Length, LogicalDirection.Forward);
                            // Console.WriteLine(new TextRange(headP, tailP).Text + "|");
                            //Console.WriteLine(new TextRange(headP, lineBegin.GetPositionAtOffset(startIndex+word.Length+1, LogicalDirection.Forward)).Text + "|");
                            //Console.WriteLine(new TextRange(headP, lineBegin.GetPositionAtOffset(startIndex + word.Length + 2, LogicalDirection.Forward)).Text + "|");
                            bool dealed = false;
                            // Console.WriteLine("{0}", headP.GetLineStartPosition(0).CompareTo(lineBegin.GetLineStartPosition(0)));
                            if (headP.GetLineStartPosition(0).CompareTo(lineBegin.GetLineStartPosition(0)) != 0 /*||
                                                                                                                 * (headP.GetLineStartPosition(0).CompareTo(lineBegin.GetLineStartPosition(0)) == 0 &&
                                                                                                                 * beginR.X + (startIndex + word.Length) * Config.fontWidth > richTextBox.ActualWidth)*/)
                            {
                                dealed = true;
                                //beginR = headP.GetCharacterRect(LogicalDirection.Forward);
                                beginR.Y  += beginR.Height;
                                beginR.X   = 0;
                                lineBegin  = headP;
                                startIndex = 0;
                            }

                            //Rect head = headP.GetCharacterRect(LogicalDirection.Forward);
                            //Rect tail = tailP.GetCharacterRect(LogicalDirection.Backward);
                            Rect head = new Rect();
                            Rect tail = new Rect();
                            head.X      = beginR.X + startIndex * Config.fontWidth;
                            head.Y      = beginR.Y;
                            head.Height = beginR.Height;
                            tail.X      = beginR.X + (startIndex + word.Length) * Config.fontWidth;
                            tail.Y      = beginR.Y;
                            tail.Height = beginR.Height;
                            if (tailP.GetLineStartPosition(0).CompareTo(headP.GetLineStartPosition(0)) != 0 && !dealed) //如果换行
                            {
                                //Rect tp = tailP.GetCharacterRect(LogicalDirection.Backward);
                                //tail = tp;
                                head.X     = 0;
                                head.Y    += head.Height;
                                tail.X     = (word.Length * Config.fontWidth);
                                tail.Y    += head.Height;
                                lineBegin  = tailP;
                                beginR.Y  += head.Height;
                                beginR.X   = tail.X;
                                startIndex = -(word.Length);
                                //if (tp.X > 0)
                                //{
                                //    head.Y = tp.Y;
                                //    head.X = 0;
                                //    head.Height = tp.Height;
                                //}
                            }
                            //Console.WriteLine("{0},{1},{2}, {3}", word, head.X, tail.X, tailP.GetLineStartPosition(0).CompareTo(headP.GetLineStartPosition(0)));
                            if (!(head.X > (p.X + w) || tail.X < (p.X - w)) && !(head.Y > (p.Y + h + head.Height + 5) || head.Y - head.Height < (p.Y - h - head.Height - 5)))
                            {
                                if ((arrayPos.Count == 0) || Math.Abs(arrayPos.Last()[0] - head.Y) > Double.Epsilon)
                                {
                                    arrayPos.Add(new double[3]);
                                    arrayPos.Last()[0] = head.Y;
                                    arrayPos.Last()[1] = head.X;
                                    arrayPos.Last()[2] = tail.X;
                                }
                                else
                                {
                                    arrayPos.Last()[1] = Math.Min(arrayPos.Last()[1], head.X);
                                    arrayPos.Last()[2] = Math.Max(arrayPos.Last()[2], tail.X);
                                }
                                select.Add(new TextRange(headP, tailP));
                                //Console.WriteLine("in:" + textRange.Text);
                            }
                        }
                        startIndex += (word.Length + 1);
                    }
                }
                begin = begin.GetNextContextPosition(LogicalDirection.Forward);
            }



            /*if (end != null)
             * {
             *  end = poz.DocumentEnd;
             * }*/
            //List<TextRange> allTextRanges = GetAllWordRanges(begin, end).ToList();

            // Console.WriteLine(arrayPos);
            return(new Tuple <List <TextRange>, List <double[]> >(select, arrayPos));
        }
Beispiel #30
0
        private bool ImportComment(EjpLib.BaseClasses.ejpCAComment comment)
        {
            TextPointer commentStart = this._textArea.Document.ContentStart.GetPositionAtOffset(Math.Abs((int)comment.OriginalPositionX));

            if (commentStart == null)
            {
                return(false);
            }
            TextPointer commentEnd = commentStart.GetPositionAtOffset(Math.Abs((int)comment.OriginalPositionY));

            if (commentEnd == null)
            {
                return(false);
            }
            Point commmentInsertPoint = commentStart.GetCharacterRect(LogicalDirection.Forward).TopLeft;

            KnowledgeMapComment commentToAdd = new KnowledgeMapComment()
            {
                OriginalAuthorId   = comment.AuthorId,
                OriginalAuthorName = comment.AuthorName,
                CurrentAuthorId    = this.CurrentOwnerId,
                CurrentAuthorName  = this.CurrentOwnerName,
                CommentId          = comment.CommentId,
                Width  = 200,
                Height = 300,
                CommentTextInDocument = comment.CommentedTextInDocument,
                OriginalCoordinates   = new Point(comment.OriginalPositionX, comment.OriginalPositionY),
                CommentedTextStart    = commentStart
            };

            commentToAdd.DisableReturnToOriginalPosition();

            foreach (EjpLib.BaseClasses.ejpCACommentMessage message in comment.Messages)
            {
                commentToAdd.Messages.Add(
                    new CommentMessage()
                {
                    Author   = message.Author,
                    AuthorId = message.AuthorId,
                    Date     = message.Date,
                    Message  = message.Message
                }
                    );
            }

            this._c_FakeAdornerLayer.Children.Add(commentToAdd);

            Point p =
                commentToAdd.CommentedTextStart.GetCharacterRect(
                    LogicalDirection.Forward).TopLeft;

            if (((p.Y - 10) + 300) < this._c_FakeAdornerLayer.ActualHeight)
            {
                Canvas.SetTop(commentToAdd, p.Y - 10);
            }
            else
            {
                Canvas.SetTop(commentToAdd, (p.Y - 10) - 300);
            }

            if ((p.X + 200) < this._c_FakeAdornerLayer.ActualWidth)
            {
                Canvas.SetLeft(commentToAdd, p.X);
            }
            else
            {
                Canvas.SetLeft(commentToAdd, p.X - 178);
            }

            commentToAdd.OnDeleteComment   += new DeleteKnowledgeMapComment(comment_OnDeleteComment);
            commentToAdd.OnMinimizeComment += new KnowledgeMapCommentViewStateChanged(comment_OnMinimizeComment);
            commentToAdd.OnMaximizeComment += new KnowledgeMapCommentViewStateChanged(comment_OnMaximizeComment);

            //this._comments.Add(commentToAdd);


            //090126
            Rect tStartRect = commentStart.GetCharacterRect(LogicalDirection.Forward);
            Rect tEndRect   = commentEnd.GetCharacterRect(LogicalDirection.Forward);

            DrawingBrush lineHandleSBrush = this.Resources["commentLineHandleS_default"] as DrawingBrush;
            DrawingBrush lineHandleEBrush = this.Resources["commentLineHandleE_default"] as DrawingBrush;

            commentToAdd.StartHandleRectangle = new Rectangle()
            {
                Fill = lineHandleSBrush
            };
            commentToAdd.StartHandleRectangle.Width  = 9;
            commentToAdd.StartHandleRectangle.Height = (tStartRect.Height < 5) ? 10 : tStartRect.Height;;
            commentToAdd.EndHandleRectangle          = new Rectangle()
            {
                Fill = lineHandleEBrush
            };
            commentToAdd.EndHandleRectangle.Width  = 9;
            commentToAdd.EndHandleRectangle.Height = (tEndRect.Height < 5) ? 10 : tEndRect.Height;
            commentToAdd.StartHandleRectangle.SetValue(Canvas.TopProperty, tStartRect.TopLeft.Y);
            commentToAdd.StartHandleRectangle.SetValue(Canvas.LeftProperty, tStartRect.TopLeft.X);
            commentToAdd.EndHandleRectangle.SetValue(Canvas.TopProperty, tEndRect.TopLeft.Y);
            commentToAdd.EndHandleRectangle.SetValue(Canvas.LeftProperty, tEndRect.TopLeft.X);

            this._c_FakeAdornerLayer.Children.Insert(0, commentToAdd.StartHandleRectangle);
            this._c_FakeAdornerLayer.Children.Insert(0, commentToAdd.EndHandleRectangle);

            this._comments.Add(commentToAdd);
            return(true);
        }