Exemplo n.º 1
0
        public string GetAnnoName(ITextSelection selectedTxt)
        {
            int start = selectedTxt.StartPosition;

            int foundLocation = sentenceService.CheckIfAnnoExists(CurrentSentence.ActiveSysSentence.Annotations, start);

            start = 0;
            if (foundLocation == -1)
            {
                return("No annotation");
            }
            else
            {
                return(CurrentSentence.ActiveSysSentence.Annotations.ElementAt(foundLocation).AnnoDim.Name);
            }


            //if (CurrentSentence != null)
            //{
            //    List<SysAnnotation> currentAnno = CurrentSentence.ActiveSysSentence.Annotations.
            //    Where(p => p.StartPosition == selectedTxt.StartPosition && p.EndPosition == selectedTxt.EndPosition).ToList();

            //    if (currentAnno.Any())
            //    {
            //        Dimension dim = currentAnno.ElementAt(0).AnnoDim;
            //        return " " + dim.Name;
            //    }
            //    else return " No annotation";
            //}
            //else return " No annotation";
        }
Exemplo n.º 2
0
 public MouseProcessor(IVimBuffer buffer, IMouseDevice mouseDevice)
 {
     _buffer = buffer;
     _selection = buffer.TextView.Selection;
     _mouseDevice = mouseDevice;
     _selection.SelectionChanged += OnSelectionChanged;
 }
        // Token: 0x06003885 RID: 14469 RVA: 0x000FD944 File Offset: 0x000FBB44
        private static bool MoveFocusToUiScope(TextEditor This)
        {
            long   contentChangeCounter = This._ContentChangeCounter;
            Visual visual = VisualTreeHelper.GetParent(This.UiScope) as Visual;

            while (visual != null && !(visual is ScrollViewer))
            {
                visual = (VisualTreeHelper.GetParent(visual) as Visual);
            }
            if (visual != null)
            {
                ((ScrollViewer)visual).AddHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(TextEditorMouse.OnScrollChangedDuringGotFocus));
            }
            ITextSelection selection = This.Selection;

            try
            {
                selection.Changed += TextEditorMouse.OnSelectionChangedDuringGotFocus;
                TextEditorMouse._selectionChanged = false;
                This.UiScope.Focus();
            }
            finally
            {
                selection.Changed -= TextEditorMouse.OnSelectionChangedDuringGotFocus;
                if (visual != null)
                {
                    ((ScrollViewer)visual).RemoveHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(TextEditorMouse.OnScrollChangedDuringGotFocus));
                }
            }
            return(This.UiScope == Keyboard.FocusedElement && contentChangeCounter == This._ContentChangeCounter && !TextEditorMouse._selectionChanged);
        }
Exemplo n.º 4
0
        private bool InvokeZenCoding(DTE dte)
        {
            Span zenSpan = GetSyntaxSpan(out string syntax);

            if (zenSpan.IsEmpty || _view.Selection.SelectedSpans[0].Length > 0 || !IsValidTextBuffer())
            {
                return(false);
            }

            var    parser = new Parser();
            string result = parser.Parse(syntax, ZenType.HTML);

            if (!string.IsNullOrEmpty(result))
            {
                Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
                {
                    using (var undo = _undoManager.TextBufferUndoHistory.CreateTransaction("ZenCoding"))
                    {
                        ITextSelection selection = UpdateTextBuffer(zenSpan, result);

                        Span newSpan = new Span(zenSpan.Start, selection.SelectedSpans[0].Length);

                        dte.ExecuteCommand("Edit.FormatSelection");
                        SetCaret(newSpan, false);

                        selection.Clear();
                        undo.Complete();
                    }
                }), DispatcherPriority.ApplicationIdle, null);

                return(true);
            }

            return(false);
        }
Exemplo n.º 5
0
        public static bool Contains(this TextSpan span, ITextSelection selection, bool inclusive)
        {
            var start = selection.Start.Position.Position;
            var end   = selection.End.Position.Position;

            return(span.Contains(start) && (span.Contains(end) || inclusive && span.End == end));
        }
Exemplo n.º 6
0
            // Token: 0x060085B9 RID: 34233 RVA: 0x0024A67C File Offset: 0x0024887C
            private void SourceDoDragDrop(ITextSelection selection, IDataObject dataObject)
            {
                DragDropEffects dragDropEffects = DragDropEffects.Copy;

                if (!this._textEditor.IsReadOnly)
                {
                    dragDropEffects |= DragDropEffects.Move;
                }
                DragDropEffects dragDropEffects2 = DragDropEffects.None;

                try
                {
                    dragDropEffects2 = DragDrop.DoDragDrop(this._textEditor.UiScope, dataObject, dragDropEffects);
                }
                catch (COMException ex) when(ex.HResult == -2147418113)
                {
                }
                if (!this._textEditor.IsReadOnly && dragDropEffects2 == DragDropEffects.Move && this._dragSourceTextRange != null && !this._dragSourceTextRange.IsEmpty)
                {
                    using (selection.DeclareChangeBlock())
                    {
                        this._dragSourceTextRange.Text = string.Empty;
                    }
                }
                this._dragSourceTextRange = null;
                if (!this._textEditor.IsReadOnly)
                {
                    BindingExpressionBase bindingExpressionBase = BindingOperations.GetBindingExpressionBase(this._textEditor.UiScope, TextBox.TextProperty);
                    if (bindingExpressionBase != null)
                    {
                        bindingExpressionBase.UpdateSource();
                        bindingExpressionBase.UpdateTarget();
                    }
                }
            }
Exemplo n.º 7
0
        bool IsAllSelectedLinesHaveComment(IWpfTextView wpfTextView)
        {
            ITextSnapshot snapshot = wpfTextView.TextSnapshot;

            int lineNumberFirstSelected = 0;
            int lineNumberLastSelected  = 0;

            if (wpfTextView.Selection.IsEmpty)
            {
                lineNumberLastSelected = lineNumberFirstSelected = snapshot.GetLineNumberFromPosition(wpfTextView.Caret.Position.BufferPosition);
            }
            else
            {
                ITextSelection textSelection = wpfTextView.Selection;
                lineNumberFirstSelected = snapshot.GetLineNumberFromPosition(textSelection.Start.Position);
                lineNumberLastSelected  = snapshot.GetLineNumberFromPosition(textSelection.End.Position - 1);
            }
            string            selectedText = "";
            ITextSnapshotLine textSnapshotLine;

            for (int i = lineNumberFirstSelected; i <= lineNumberLastSelected; ++i)
            {
                textSnapshotLine = snapshot.GetLineFromLineNumber(i);
                selectedText     = textSnapshotLine.GetText().Trim();
                if (selectedText.Length < 2 || selectedText.Substring(0, 2) != "//")
                {
                    return(false);
                }
            }
            return(true);
        }
Exemplo n.º 8
0
        internal SelectionHighlight(IWpfTextView view, ITextSearchService TextSearchService, ITagAggregator <ToDoTag> tagAggregator)
        {
            this._view                        = view;
            this._layer                       = view.GetAdornmentLayer("SelectionHighlight");
            this._selection                   = view.Selection;
            this._textSearchService           = TextSearchService;
            this._tagAggregator               = tagAggregator;
            this._view.LayoutChanged         += this.OnLayoutChanged;
            this._selection.SelectionChanged += new EventHandler(this.OnSelectionChanged);
            //不可启用,有可能会与StructureAdornmentManager 类中的注册的Closed事件冲突
            //this._view.Closed += TextView_Closed;

            ThreadHelper.ThrowIfNotOnUIThread();

            //选中单词区域背景色
            Brush brush = new SolidColorBrush(Colors.DarkOrchid);

            //Brush brush = new SolidColorBrush(Colors.OrangeRed);
            brush.Freeze();
            Brush brush2 = new SolidColorBrush(Colors.AliceBlue);

            brush2.Freeze();
            Pen pen = new Pen(brush2, 0.5);

            pen.Freeze();
            this._brush = brush;
            this._pen   = pen;
        }
Exemplo n.º 9
0
        internal TextParentUndoUnit(ITextSelection selection, ITextPointer anchorPosition, ITextPointer movingPosition)
            : base(String.Empty)
        {
            _selection = selection;

            _undoAnchorPositionOffset    = anchorPosition.Offset;
            _undoAnchorPositionDirection = anchorPosition.LogicalDirection;
            _undoMovingPositionOffset    = movingPosition.Offset;
            _undoMovingPositionDirection = movingPosition.LogicalDirection;

            // Bug 1706768: we are seeing unitialized values when the undo
            // undo is pulled off the undo stack. _redoAnchorPositionOffset
            // and _redoMovingPositionOffset are supposed to be initialized
            // with calls to RecordRedoSelectionState before that happens.
            //
            // This code path is being left enabled in DEBUG to help track down
            // the underlying bug post V1.
#if DEBUG
            _redoAnchorPositionOffset = -1;
            _redoMovingPositionOffset = -1;
#else
            _redoAnchorPositionOffset = 0;
            _redoMovingPositionOffset = 0;
#endif
        }
Exemplo n.º 10
0
        void SetTextStyle(Object sender, EventArgs e, String decoration)
        {
            ITextBuffer    _mybuffer  = CurrentUDNDocView.TextEditorView.TextBuffer;
            ITextSelection _selection = CurrentUDNDocView.TextEditorView.Selection;

            var start = _selection.Start.Position.Position;
            var end   = _selection.End.Position.Position;
            var preceedingCharacter = _mybuffer.CurrentSnapshot.GetText(start - 1, 1);

            if (preceedingCharacter != decoration.Substring(preceedingCharacter.Length - 1, 1))
            {
                if (_selection.Start.Position == _selection.End.Position)
                {
                    _mybuffer.Insert(_selection.Start.Position, decoration);
                }
                else
                {
                    _mybuffer.Insert(_selection.Start.Position, decoration);
                    _mybuffer.Insert(_selection.End.Position, decoration);
                }
                CurrentUDNDocView.TextEditorView.Selection.Select(
                    new SnapshotSpan(CurrentUDNDocView.TextEditorView.TextSnapshot, start + decoration.Length,
                                     end - start), false);
            }
            else
            {
                _mybuffer.Delete(new Span(start - decoration.Length, decoration.Length));
                _mybuffer.Delete(new Span(end - decoration.Length, decoration.Length));
            }
        }
Exemplo n.º 11
0
 // Token: 0x06003C64 RID: 15460 RVA: 0x00117220 File Offset: 0x00115420
 internal TextSelectionHighlightLayer(ITextSelection selection)
 {
     this._selection          = selection;
     this._selection.Changed += this.OnSelectionChanged;
     this._oldStart           = this._selection.Start;
     this._oldEnd             = this._selection.End;
 }
Exemplo n.º 12
0
        private void ExpandSelectionOnPartialTokenSelect(ITextSelection selection, ITextRange tokenRange)
        {
            switch (selection.Type)
            {
            case SelectionType.InsertionPoint:
                // Snap selection to token on click
                if (tokenRange.StartPosition < selection.StartPosition && selection.EndPosition < tokenRange.EndPosition)
                {
                    selection.Expand(TextRangeUnit.Link);
                    InvokeTokenSelected(selection);
                }

                break;

            case SelectionType.Normal:
                // We do not want user to partially select a token since pasting to a partial token can break
                // the token tracking system, which can result in unwanted character formatting issues.
                if ((tokenRange.StartPosition <= selection.StartPosition && selection.EndPosition < tokenRange.EndPosition) ||
                    (tokenRange.StartPosition < selection.StartPosition && selection.EndPosition <= tokenRange.EndPosition))
                {
                    // TODO: Figure out how to expand selection without breaking selection flow (with Shift select or pointer sweep select)
                    selection.Expand(TextRangeUnit.Link);
                    InvokeTokenSelected(selection);
                }

                break;
            }
        }
Exemplo n.º 13
0
        private void Create2(
            ModeKind kind = ModeKind.VisualCharacter,
            params string[] lines)
        {
            _textView   = CreateTextView(lines);
            _textBuffer = _textView.TextBuffer;
            var vimTextBuffer = Vim.CreateVimTextBuffer(_textBuffer);
            var vimBufferData = CreateVimBufferData(vimTextBuffer, _textView);
            var visualKind    = VisualKind.OfModeKind(kind).Value;

            _selection = _textView.Selection;
            _factory   = new MockRepository(MockBehavior.Strict);
            _tracker   = _factory.Create <ISelectionTracker>();
            _tracker.Setup(x => x.Start());
            _tracker.Setup(x => x.UpdateSelection());
            _tracker.Setup(x => x.RecordCaretTrackingPoint(It.IsAny <ModeArgument>()));
            _tracker.SetupGet(x => x.IsRunning).Returns(true);
            _operations = _factory.Create <ICommonOperations>();
            _operations.SetupGet(x => x.TextView).Returns(_textView);
            _operations.Setup(x => x.MoveCaretToPoint(It.IsAny <SnapshotPoint>(), ViewFlags.Standard));
            _commandUtil = _factory.Create <ICommandUtil>();
            var motionUtil = new MotionUtil(vimBufferData, _operations.Object);
            var capture    = new MotionCapture(vimBufferData, new IncrementalSearch(vimBufferData, _operations.Object, motionUtil));
            var runner     = new CommandRunner(
                vimBufferData,
                capture,
                _commandUtil.Object,
                VisualKind.Character,
                KeyRemapMode.Visual);

            _modeRaw = new VisualMode(vimBufferData, _operations.Object, motionUtil, visualKind, runner, capture, _tracker.Object);
            _mode    = _modeRaw;
            _mode.OnEnter(ModeArgument.None);
        }
Exemplo n.º 14
0
        private void Create2(
            ModeKind kind = ModeKind.VisualCharacter,
            params string[] lines)
        {
            _textView   = EditorUtil.CreateTextView(lines);
            _textBuffer = _textView.TextBuffer;
            var vimTextBuffer = Vim.CreateVimTextBuffer(_textBuffer);
            var vimBufferData = CreateVimBufferData(vimTextBuffer, _textView);

            _selection = _textView.Selection;
            _factory   = new MockRepository(MockBehavior.Strict);
            _tracker   = _factory.Create <ISelectionTracker>();
            _tracker.Setup(x => x.Start());
            _tracker.Setup(x => x.ResetCaret());
            _tracker.Setup(x => x.UpdateSelection());
            _operations = _factory.Create <ICommonOperations>();
            _operations.SetupGet(x => x.TextView).Returns(_textView);
            _commandUtil = _factory.Create <ICommandUtil>();
            var motionUtil = new MotionUtil(vimBufferData);
            var capture    = new MotionCapture(vimBufferData, new IncrementalSearch(vimBufferData, _operations.Object));
            var runner     = new CommandRunner(
                _textView,
                Vim.RegisterMap,
                capture,
                _commandUtil.Object,
                (new Mock <IStatusUtil>()).Object,
                VisualKind.Character);

            _modeRaw = new VisualMode(vimBufferData, _operations.Object, motionUtil, kind, runner, capture, _tracker.Object);
            _mode    = _modeRaw;
            _mode.OnEnter(ModeArgument.None);
        }
Exemplo n.º 15
0
        public static Mock <ITextView> CreateTextView(
            ITextBuffer textBuffer                = null,
            ITextCaret caret                      = null,
            ITextSelection selection              = null,
            ITextViewRoleSet textViewRoleSet      = null,
            ITextViewModel textViewModel          = null,
            IEditorOptions editorOptions          = null,
            IBufferGraph bufferGraph              = null,
            PropertyCollection propertyCollection = null,
            MockRepository factory                = null)
        {
            factory            = factory ?? new MockRepository(MockBehavior.Strict);
            textBuffer         = textBuffer ?? CreateTextBuffer(100, factory: factory).Object;
            caret              = caret ?? CreateCaret(factory: factory).Object;
            selection          = selection ?? CreateSelection(factory: factory).Object;
            propertyCollection = propertyCollection ?? new PropertyCollection();
            textViewRoleSet    = textViewRoleSet ?? CreateTextViewRoleSet(factory: factory).Object;
            editorOptions      = editorOptions ?? CreateEditorOptions(factory: factory).Object;
            bufferGraph        = bufferGraph ?? CreateBufferGraph(factory: factory).Object;
            textViewModel      = textViewModel ?? CreateTextViewModel(textBuffer: textBuffer, factory: factory).Object;
            var view = factory.Create <ITextView>();

            view.SetupGet(x => x.Caret).Returns(caret);
            view.SetupGet(x => x.Selection).Returns(selection);
            view.SetupGet(x => x.TextBuffer).Returns(textBuffer);
            view.SetupGet(x => x.TextSnapshot).Returns(() => textBuffer.CurrentSnapshot);
            view.SetupGet(x => x.Properties).Returns(propertyCollection);
            view.SetupGet(x => x.Roles).Returns(textViewRoleSet);
            view.SetupGet(x => x.Options).Returns(editorOptions);
            view.SetupGet(x => x.BufferGraph).Returns(bufferGraph);
            view.SetupGet(x => x.TextViewModel).Returns(textViewModel);
            return(view);
        }
Exemplo n.º 16
0
        private bool InvokeZenCoding()
        {
            Span zenSpan = GetText();

            if (zenSpan.Length == 0 || TextView.Selection.SelectedSpans[0].Length > 0 || !IsValidTextBuffer())
            {
                return(false);
            }

            string zenSyntax = TextView.TextBuffer.CurrentSnapshot.GetText(zenSpan);

            string result = XamlParser.Parse(zenSyntax);

            if (!string.IsNullOrEmpty(result))
            {
                Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
                {
                    ITextSelection selection = UpdateTextBuffer(zenSpan, result);

                    Span newSpan = new Span(zenSpan.Start, selection.SelectedSpans[0].Length);

                    vsXenPackage.ExecuteCommand("Edit.FormatSelection");
                    SetCaret(newSpan, false);

                    selection.Clear();
                }), DispatcherPriority.ApplicationIdle, null);

                return(true);
            }

            return(false);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Load RTF-Files where Richeditbox LoadeEvent is fired
        /// Tag-Value needs to be filled
        /// </summary>
        /// <param name="sender">UIElement Richeditbox</param>
        /// <param name="e">RoutedEventArgs</param>
        public async void rtb_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender is RichEditBox textbox)
                {
                    StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(((string)textbox.Tag).GetLocalized()));

                    if (file != null)
                    {
                        Windows.Storage.Streams.IRandomAccessStream randAccStream = await file.OpenAsync(FileAccessMode.Read);

                        // Load the file into the Document property of the RichEditBox.
                        textbox.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, randAccStream);

                        textbox.Document.Selection.SetRange(0, int.MaxValue);
                        ITextSelection selectedText = textbox.Document.Selection;
                        if (selectedText != null && textbox.Foreground is SolidColorBrush color)
                        {
                            selectedText.CharacterFormat.ForegroundColor = color.Color;
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 18
0
        // This method should only be called once (it is normally called from the ctor unless we're using
        // ITextEditorFactoryService2.CreateTextViewWithoutInitialization on the factory to delay initialization).
        internal void Initialize()
        {
            if (_hasInitializeBeenCalled)
            {
                throw new InvalidOperationException("Attempted to Initialize a WpfTextView twice");
            }

            _bufferGraph = _factoryService.BufferGraphFactoryService.CreateBufferGraph(this.TextViewModel.VisualBuffer);

            //_editorFormatMap = _factoryService.EditorFormatMapService.GetEditorFormatMap(this);

            _selection = new TextSelection(_textEditor, this);

            // Create caret
            _caret = new TextCaret(_textEditor, this);

            //			this.Loaded += OnLoaded;

            _connectionManager = new ConnectionManager(this, _factoryService.TextViewConnectionListeners, _factoryService.GuardedOperations);

            SubscribeToEvents();

            // Binding content type specific assets includes calling out to content-type
            // specific view creation listeners.  We need to do this as late as possible.
            this.BindContentTypeSpecificAssets(null, TextViewModel.DataModel.ContentType);

            //Subscribe now so that there is no chance that a layout could be forced by a text change.
            //_visualBuffer.ChangedLowPriority += OnVisualBufferChanged;
            //_visualBuffer.ContentTypeChanged += OnVisualBufferContentTypeChanged;

            _hasInitializeBeenCalled = true;
        }
Exemplo n.º 19
0
        public void Create2(
            ModeKind kind = ModeKind.VisualCharacter,
            params string[] lines)
        {
            _textView   = EditorUtil.CreateView(lines);
            _textBuffer = _textView.TextBuffer;
            _selection  = _textView.Selection;
            _factory    = new MockRepository(MockBehavior.Strict);
            _map        = VimUtil.CreateRegisterMap(MockObjectFactory.CreateClipboardDevice(_factory).Object);
            _markMap    = new MarkMap(new TrackingLineColumnService());
            _tracker    = _factory.Create <ISelectionTracker>();
            _tracker.Setup(x => x.Start());
            _tracker.Setup(x => x.ResetCaret());
            _tracker.Setup(x => x.UpdateSelection());
            _jumpList           = _factory.Create <IJumpList>(MockBehavior.Loose);
            _undoRedoOperations = _factory.Create <IUndoRedoOperations>();
            _foldManager        = _factory.Create <IFoldManager>();
            _editorOperations   = _factory.Create <IEditorOperations>();
            _operations         = _factory.Create <ICommonOperations>();
            _operations.SetupGet(x => x.FoldManager).Returns(_foldManager.Object);
            _operations.SetupGet(x => x.UndoRedoOperations).Returns(_undoRedoOperations.Object);
            _operations.SetupGet(x => x.EditorOperations).Returns(_editorOperations.Object);
            _operations.SetupGet(x => x.TextView).Returns(_textView);
            _host        = _factory.Create <IVimHost>(MockBehavior.Loose);
            _commandUtil = _factory.Create <ICommandUtil>();
            _commandUtil
            .Setup(x => x.RunCommand(It.Is <Command>(y => y.IsLegacyCommand)))
            .Returns <Command>(c => c.AsLegacyCommand().Item.Function.Invoke(null));
            _incrementalSearch = MockObjectFactory.CreateIncrementalSearch(factory: _factory);
            var globalSettings = new GlobalSettings();
            var localSettings  = new LocalSettings(globalSettings, _textView);
            var motionUtil     = VimUtil.CreateTextViewMotionUtil(
                _textView,
                _markMap,
                localSettings);

            _bufferData = MockObjectFactory.CreateVimBuffer(
                _textView,
                "test",
                MockObjectFactory.CreateVim(_map, host: _host.Object, settings: globalSettings).Object,
                incrementalSearch: _incrementalSearch.Object,
                jumpList: _jumpList.Object,
                motionUtil: motionUtil);
            var capture = new MotionCapture(
                _host.Object,
                _textView,
                _incrementalSearch.Object,
                localSettings);
            var runner = new CommandRunner(
                _textView,
                _map,
                capture,
                _commandUtil.Object,
                (new Mock <IStatusUtil>()).Object,
                VisualKind.Character);

            _modeRaw = new VisualMode(_bufferData.Object, _operations.Object, kind, runner, capture, _tracker.Object);
            _mode    = _modeRaw;
            _mode.OnEnter(ModeArgument.None);
        }
        // Token: 0x060062CF RID: 25295 RVA: 0x001BB61C File Offset: 0x001B981C
        private static Annotation CreateStickyNoteForSelection(AnnotationService service, XmlQualifiedName noteType, string author)
        {
            AnnotationHelper.CheckInputs(service);
            ITextSelection textSelection = AnnotationHelper.GetTextSelection((FrameworkElement)service.Root);

            Invariant.Assert(textSelection != null, "TextSelection is null");
            if (textSelection.IsEmpty)
            {
                throw new InvalidOperationException(SR.Get("EmptySelectionNotSupported"));
            }
            Annotation annotation = null;

            EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.CreateStickyNoteBegin);
            try
            {
                annotation = AnnotationHelper.CreateAnnotationForSelection(service, textSelection, noteType, author);
                Invariant.Assert(annotation != null, "CreateAnnotationForSelection returned null.");
                service.Store.AddAnnotation(annotation);
                textSelection.SetCaretToPosition(textSelection.MovingPosition, textSelection.MovingPosition.LogicalDirection, true, true);
            }
            finally
            {
                EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.CreateStickyNoteEnd);
            }
            return(annotation);
        }
        // Returns true if an ITextSelection isn't in a state where we want
        // to acknowledge spelling errors.
        private static bool IsSelectionIgnoringErrors(ITextSelection selection)
        {
            bool isSelectionIgnoringErrors = false;

            // If the selection spans more than a single Block, ignore spelling errors.
            if (selection.Start is TextPointer)
            {
                isSelectionIgnoringErrors = ((TextPointer)selection.Start).ParentBlock != ((TextPointer)selection.End).ParentBlock;
            }

            // If the selection is large, ignore spelling errors.
            if (!isSelectionIgnoringErrors)
            {
                isSelectionIgnoringErrors = selection.Start.GetOffsetToPosition(selection.End) >= 256;
            }

            // If the selection contains unicode line breaks, ignore spelling errors.
            if (!isSelectionIgnoringErrors)
            {
                string text = selection.Text;

                for (int i = 0; i < text.Length && !isSelectionIgnoringErrors; i++)
                {
                    isSelectionIgnoringErrors = TextPointerBase.IsCharUnicodeNewLine(text[i]);
                }
            }

            return(isSelectionIgnoringErrors);
        }
Exemplo n.º 22
0
        private bool InvokeZenCoding()
        {
            Span zenSpan = GetText();

            if (zenSpan.Length == 0 || TextView.Selection.SelectedSpans[0].Length > 0 || !IsValidTextBuffer())
            {
                return(false);
            }

            string zenSyntax = TextView.TextBuffer.CurrentSnapshot.GetText(zenSpan);

            Parser parser = new Parser();
            string result = parser.Parse(zenSyntax, ZenType.HTML);

            if (!string.IsNullOrEmpty(result))
            {
                EditorExtensionsPackage.DTE.UndoContext.Open("ZenCoding");

                ITextSelection selection = UpdateTextBuffer(zenSpan, result);
                Span           newSpan   = new Span(zenSpan.Start, selection.SelectedSpans[0].Length);

                selection.Clear();

                EditorExtensionsPackage.DTE.UndoContext.Close();

                Dispatcher.CurrentDispatcher.BeginInvoke(
                    new Action(() => SetCaret(newSpan, false)), DispatcherPriority.Normal, null);

                return(true);
            }

            return(false);
        }
Exemplo n.º 23
0
        private void SearchBox_QuerySubmitted(SearchBox sender, SearchBoxQuerySubmittedEventArgs args)
        {
            Display.Document.GetText(TextGetOptions.None, out string textStr);
            ClearSearchSelection(textStr);

            if (string.IsNullOrEmpty(args.QueryText))
            {
                return;
            }

            int myRichEditLength = textStr.Length;
            int i = 1;

            Display.Document.Selection.SetRange(0, myRichEditLength);

            while (i > 0)
            {
                i = Display.Document.Selection.FindText(args.QueryText, myRichEditLength, FindOptions.Case);
                ITextSelection selectedText = Display.Document.Selection;

                if (i != 0 && selectedText != null)
                {
                    selectedText.CharacterFormat.BackgroundColor = Windows.UI.Color.FromArgb(0, 255, 255, 0);
                }
            }
        }
Exemplo n.º 24
0
 public static ISelectionPainter CreatePainter(ITextSelection selection, IAdornmentLayer adornmentLayer, Dictionary <string, object> dictionary, SKColor defaultColor)
 {
     return(new SolidColorBrushSelectionPainter(selection, adornmentLayer, new SKPaint()
     {
         Color = defaultColor, IsStroke = false
     }));
 }
        internal TextParentUndoUnit(ITextSelection selection, ITextPointer anchorPosition, ITextPointer movingPosition)
            : base(String.Empty)
        {
            _selection = selection;

            _undoAnchorPositionOffset = anchorPosition.Offset;
            _undoAnchorPositionDirection = anchorPosition.LogicalDirection;
            _undoMovingPositionOffset = movingPosition.Offset;
            _undoMovingPositionDirection = movingPosition.LogicalDirection;

            // Bug 1706768: we are seeing unitialized values when the undo
            // undo is pulled off the undo stack. _redoAnchorPositionOffset
            // and _redoMovingPositionOffset are supposed to be initialized
            // with calls to RecordRedoSelectionState before that happens.
            //
            // This code path is being left enabled in DEBUG to help track down
            // the underlying bug post V1.
#if DEBUG
            _redoAnchorPositionOffset = -1;
            _redoMovingPositionOffset = -1;
#else
            _redoAnchorPositionOffset = 0;
            _redoMovingPositionOffset = 0;
#endif
        }
Exemplo n.º 26
0
        private bool InvokeZenCoding()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            Span zenSpan = GetSyntaxSpan(out string syntax);

            if (zenSpan.IsEmpty || _view.Selection.SelectedSpans[0].Length > 0 || !IsValidTextBuffer())
            {
                return(false);
            }

            var    parser = new Parser();
            string result = parser.Parse(syntax, ZenType.HTML);

            if (!string.IsNullOrEmpty(result))
            {
                using (ITextUndoTransaction undo = _undoManager.TextBufferUndoHistory.CreateTransaction("ZenCoding"))
                {
                    ITextSelection selection = UpdateTextBuffer(zenSpan, result);

                    var newSpan = new Span(zenSpan.Start, selection.SelectedSpans[0].Length);

                    _dte.ExecuteCommand("Edit.FormatSelection");
                    SetCaret(newSpan, false);

                    selection.Clear();
                    undo.Complete();
                }

                return(true);
            }

            return(false);
        }
Exemplo n.º 27
0
        // Constructor.
        internal TextSelectionHighlightLayer(ITextSelection selection)
        {
            _selection = selection;
            _selection.Changed += new EventHandler(OnSelectionChanged);

            _oldStart = _selection.Start;
            _oldEnd = _selection.End;
        }
Exemplo n.º 28
0
        private void ClearSearchSelection(string textStr)
        {
            Display.Document.Selection.StartPosition = 0;
            Display.Document.Selection.EndPosition   = textStr.Length;
            ITextSelection selectedText = Display.Document.Selection;

            selectedText.CharacterFormat.BackgroundColor = Windows.UI.Color.FromArgb(0, 255, 255, 255);
        }
        // Constructor.
        internal TextSelectionHighlightLayer(ITextSelection selection)
        {
            _selection          = selection;
            _selection.Changed += new EventHandler(OnSelectionChanged);

            _oldStart = _selection.Start;
            _oldEnd   = _selection.End;
        }
Exemplo n.º 30
0
 protected void Create(params string[] lines)
 {
     _vimBuffer = CreateVimBuffer(lines);
     _textView = _vimBuffer.TextView;
     _textBuffer = _vimBuffer.TextBuffer;
     _globalSettings = _vimBuffer.GlobalSettings;
     _globalSettings.SelectModeOptions = SelectModeOptions.Mouse | SelectModeOptions.Keyboard;
     _textSelection = _textView.Selection;
     _context = new TestableSynchronizationContext();
     _context.Install();
 }
Exemplo n.º 31
0
 protected virtual void Create(params string[] lines)
 {
     _vimBuffer = CreateVimBuffer(lines);
     _textView = _vimBuffer.TextView;
     _textBuffer = _vimBuffer.TextBuffer;
     _globalSettings = _vimBuffer.GlobalSettings;
     _globalSettings.SelectModeOptions = SelectModeOptions.Mouse | SelectModeOptions.Keyboard;
     _textSelection = _textView.Selection;
     _context = new TestableSynchronizationContext();
     _context.Install();
     _testableMouseDevice = (TestableMouseDevice)MouseDevice;
     _testableMouseDevice.IsLeftButtonPressed = true;
 }
Exemplo n.º 32
0
		public static SnapshotSpan GetLineAnchorSpan(ITextSelection textSelection) {
			if (textSelection == null)
				throw new ArgumentNullException(nameof(textSelection));
			if (textSelection.IsEmpty)
				return textSelection.TextView.Caret.ContainingTextViewLine.ExtentIncludingLineBreak;
			var anchorExtent = textSelection.TextView.GetTextViewLineContainingBufferPosition(textSelection.AnchorPoint.Position).ExtentIncludingLineBreak;
			var activeExtent = textSelection.TextView.GetTextViewLineContainingBufferPosition(textSelection.ActivePoint.Position).ExtentIncludingLineBreak;
			if (textSelection.AnchorPoint >= textSelection.ActivePoint) {
				if (new VirtualSnapshotPoint(anchorExtent.Start) == textSelection.AnchorPoint && textSelection.AnchorPoint.Position.Position != 0)
					anchorExtent = textSelection.TextView.GetTextViewLineContainingBufferPosition(textSelection.AnchorPoint.Position - 1).ExtentIncludingLineBreak;
			}
			return anchorExtent;
		}
Exemplo n.º 33
0
		public BoxSelectionHelper(ITextSelection textSelection) {
			Debug.Assert(textSelection.Mode == TextSelectionMode.Box);
			this.textSelection = textSelection;
			textSnapshot = textSelection.TextView.TextSnapshot;

			var anchorLine = textSelection.TextView.GetTextViewLineContainingBufferPosition(textSelection.AnchorPoint.Position);
			var activeLine = textSelection.TextView.GetTextViewLineContainingBufferPosition(textSelection.ActivePoint.Position);
			var anchorBounds = anchorLine.GetExtendedCharacterBounds(textSelection.AnchorPoint);
			var activeBounds = activeLine.GetExtendedCharacterBounds(textSelection.ActivePoint);
			if (anchorBounds.Left < activeBounds.Right) {
				xLeft = anchorBounds.Left;
				xRight = Math.Max(xLeft, activeBounds.Left);
			}
			else {
				xLeft = activeBounds.Left;
				xRight = Math.Max(xLeft, anchorBounds.Left);
			}
			Debug.Assert(xLeft <= xRight);
		}
Exemplo n.º 34
0
        //public XHighlight(IWpfTextView view, ITextSearchService TextSearchService, ITagAggregator<MatchTag> tagAggregator)
        public XHighlight(IWpfTextView view, ITextSearchService TextSearchService, IClassificationType ftype, IClassificationFormatMap fmap)
        {
            m_formatType = ftype;
            map = fmap;

            this._view = view;
            this._layer = view.GetAdornmentLayer("XHighlighter");
            this._selection = view.Selection;
            this._textSearchService = TextSearchService;
            //this._tagAggregator = tagAggregator;
            this._view.LayoutChanged += new EventHandler<TextViewLayoutChangedEventArgs>(this.OnLayoutChanged);
            this._selection.SelectionChanged += new EventHandler(this.OnSelectionChanged);
            Brush brush1 = (Brush)new SolidColorBrush(Colors.Yellow);
            brush1.Freeze();
            Brush brush2 = (Brush)new SolidColorBrush(Colors.AliceBlue);
            brush2.Freeze();
            Pen pen = new Pen(brush2, 0.5);
            pen.Freeze();
            this._brush = brush1;
            this._pen = pen;
        }
Exemplo n.º 35
0
        private void Create2(
            ModeKind kind = ModeKind.VisualCharacter,
            params string[] lines)
        {
            _textView = CreateTextView(lines);
            _textBuffer = _textView.TextBuffer;
            var vimTextBuffer = Vim.CreateVimTextBuffer(_textBuffer);
            var vimBufferData = CreateVimBufferData(vimTextBuffer, _textView);
            var visualKind = VisualKind.OfModeKind(kind).Value;

            _selection = _textView.Selection;
            _factory = new MockRepository(MockBehavior.Strict);
            _tracker = _factory.Create<ISelectionTracker>();
            _tracker.Setup(x => x.Start());
            _tracker.Setup(x => x.UpdateSelection());
            _tracker.Setup(x => x.RecordCaretTrackingPoint(It.IsAny<ModeArgument>()));
            _tracker.SetupGet(x => x.IsRunning).Returns(true);
            _operations = _factory.Create<ICommonOperations>();
            _operations.SetupGet(x => x.TextView).Returns(_textView);
            _operations.Setup(x => x.MoveCaretToPoint(It.IsAny<SnapshotPoint>(), ViewFlags.Standard));
            _commandUtil = _factory.Create<ICommandUtil>();
            var motionUtil = new MotionUtil(vimBufferData, _operations.Object);
            var capture = new MotionCapture(vimBufferData, new IncrementalSearch(vimBufferData, _operations.Object));
            var runner = new CommandRunner(
                _textView,
                Vim.RegisterMap,
                capture,
                vimBufferData.LocalSettings,
                _commandUtil.Object,
                (new Mock<IStatusUtil>()).Object,
                VisualKind.Character,
                KeyRemapMode.Visual);
            _modeRaw = new VisualMode(vimBufferData, _operations.Object, motionUtil, visualKind, runner, capture, _tracker.Object);
            _mode = _modeRaw;
            _mode.OnEnter(ModeArgument.None);
        }
Exemplo n.º 36
0
        // Helper for UpdateCaretState -- identifies caret position from text selection.
        private static ITextPointer IdentifyCaretPosition(ITextSelection currentTextSelection)
        {
            ITextPointer caretPosition = currentTextSelection.MovingPosition;

            if (!currentTextSelection.IsEmpty)
            {
                // Even when we do not draw the blinking caret, we need this position
                // for scrolling caret position into view.

                // Special case for nonempty selection extended beyond end of line
                if ((caretPosition.LogicalDirection == LogicalDirection.Backward && //
                     caretPosition.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.ElementStart) || //
                    TextPointerBase.IsAfterLastParagraph(caretPosition))
                {
                    // This means that selection has been expanded by ExtendToLineEnd/ExtendToDocumentEnd command.
                    // TextView in this case cannot give the rect from this position;
                    // we need to move backward to the end of content
                    caretPosition = caretPosition.CreatePointer();
                    caretPosition.MoveToNextInsertionPosition(LogicalDirection.Backward);
                    caretPosition.SetLogicalDirection(LogicalDirection.Forward);
                }
            }

            // TextView.GetRectangleFromTextPosition returns the end of character rect in case of Backward
            // logical direction at the start caret position of the docuemtn or paragraph, so we reset the
            // logical direction with Forward to get the right rect of caret at the start position of
            // document or paragraph.
            if (caretPosition.LogicalDirection == LogicalDirection.Backward && //
                caretPosition.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.ElementStart && //
                (caretPosition.GetNextInsertionPosition(LogicalDirection.Backward) == null || //
                 TextPointerBase.IsNextToAnyBreak(caretPosition, LogicalDirection.Backward)))
            {
                caretPosition = caretPosition.CreatePointer();
                caretPosition.SetLogicalDirection(LogicalDirection.Forward);
            }

            return caretPosition;
        }
Exemplo n.º 37
0
        //......................................................
        //
        //  Caret Support
        //
        //......................................................

        // Redraws a caret using current setting for italic - taking springload formatting into account.
        private static void RefreshCaret(TextEditor textEditor, ITextSelection textSelection)
        {
            object fontStylePropertyValue;
            bool italic;

            if (textSelection == null || textSelection.CaretElement == null)
            {
                return;
            }

            // NOTE: We are using GetCurrentValue to take springload formatting into account.
            fontStylePropertyValue = ((TextSelection)textSelection).GetCurrentValue(TextElement.FontStyleProperty);
            italic = (textEditor.AcceptsRichContent && fontStylePropertyValue != DependencyProperty.UnsetValue && (FontStyle)fontStylePropertyValue == FontStyles.Italic);

            textSelection.CaretElement.RefreshCaret(italic);
        }
Exemplo n.º 38
0
 internal static Mock<IWpfTextView> CreateWpfTextView(
     ITextBuffer buffer,
     ITextCaret caret = null,
     ITextSelection selection = null)
 {
     caret = caret ?? CreateCaret().Object;
     selection = selection ?? CreateSelection().Object;
     var view = new Mock<IWpfTextView>(MockBehavior.Strict);
     view.SetupGet(x => x.Caret).Returns(caret);
     view.SetupGet(x => x.Selection).Returns(selection);
     view.SetupGet(x => x.TextBuffer).Returns(buffer);
     view.SetupGet(x => x.TextSnapshot).Returns(() => buffer.CurrentSnapshot);
     return view;
 }
        //------------------------------------------------------
        //
        //  Constructors
        //
        //------------------------------------------------------

        #region Constructors

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="selection">
        /// TextSelection before executing the operation.
        /// </param>
        internal TextParentUndoUnit(ITextSelection selection)
            : this(selection, selection.AnchorPosition, selection.MovingPosition)
        {
        }
Exemplo n.º 40
0
 internal CompositionParentUndoUnit(ITextSelection selection, ITextPointer anchorPosition, ITextPointer movingPosition, bool isFirstCompositionUnit)
     : base(selection, anchorPosition, movingPosition)
 {
     _isFirstCompositionUnit = isFirstCompositionUnit;
 }
Exemplo n.º 41
0
        // Returns true if an ITextSelection isn't in a state where we want
        // to acknowledge spelling errors.
        private static bool IsSelectionIgnoringErrors(ITextSelection selection)
        {
            bool isSelectionIgnoringErrors = false;

            // If the selection spans more than a single Block, ignore spelling errors.
            if (selection.Start is TextPointer)
            {
                isSelectionIgnoringErrors = ((TextPointer)selection.Start).ParentBlock != ((TextPointer)selection.End).ParentBlock;
            }

            // If the selection is large, ignore spelling errors.
            if (!isSelectionIgnoringErrors)
            {
                isSelectionIgnoringErrors = selection.Start.GetOffsetToPosition(selection.End) >= 256;
            }

            // If the selection contains unicode line breaks, ignore spelling errors.
            if (!isSelectionIgnoringErrors)
            {
                string text = selection.Text;

                for (int i = 0; i < text.Length && !isSelectionIgnoringErrors; i++)
                {
                    isSelectionIgnoringErrors = TextPointerBase.IsCharUnicodeNewLine(text[i]);
                }
            }

            return isSelectionIgnoringErrors;
        }
Exemplo n.º 42
0
 public static Mock<ITextView> CreateTextView(
     ITextBuffer buffer = null,
     ITextCaret caret = null,
     ITextSelection selection = null,
     MockRepository factory = null)
 {
     factory = factory ?? new MockRepository(MockBehavior.Strict);
     buffer = buffer ?? CreateTextBuffer(100, factory: factory).Object;
     caret = caret ?? CreateCaret(factory: factory).Object;
     selection = selection ?? CreateSelection(factory: factory).Object;
     var view = factory.Create<ITextView>();
     view.SetupGet(x => x.Caret).Returns(caret);
     view.SetupGet(x => x.Selection).Returns(selection);
     view.SetupGet(x => x.TextBuffer).Returns(buffer);
     view.SetupGet(x => x.TextSnapshot).Returns(() => buffer.CurrentSnapshot);
     return view;
 }
Exemplo n.º 43
0
            // Table cell selection currently include the next adjacent cell start element so that
            // selection always contains the drop position even though the drop position is on the next cell.
            // This private method check the table range really contains the drop position or not.
            private bool IsSelectionContainsDropPosition(ITextSelection selection, ITextPointer dropPosition)
            {
                bool selectionContainedDropPosition = selection.Contains(dropPosition);

                if (selectionContainedDropPosition && selection.IsTableCellRange)
                {
                    for (int i = 0; i < selection.TextSegments.Count; i++)
                    {
                        TextSegment textSegment = selection._TextSegments[i];

                        if (dropPosition.CompareTo(textSegment.End) == 0)
                        {
                            selectionContainedDropPosition = false;
                            break;
                        }
                    }
                }

                return selectionContainedDropPosition;
            }
Exemplo n.º 44
0
            /// <summary>
            /// DragEnd event handler from DragDrop behavior.
            /// </summary>
            private void SourceDoDragDrop(ITextSelection selection, IDataObject dataObject)
            {
                // Run OLE drag-drop process. It will eat all user input until the drop
                DragDropEffects allowedDragDropEffects = DragDropEffects.Copy;
                if (!_textEditor.IsReadOnly)
                {
                    allowedDragDropEffects |= DragDropEffects.Move;
                }

                DragDropEffects resultingDragDropEffects = DragDrop.DoDragDrop( //
                    _textEditor.UiScope, // dragSource, 
                    dataObject, //
                    allowedDragDropEffects);

                // Remove source selection 
                if (!_textEditor.IsReadOnly && //
                    resultingDragDropEffects == DragDropEffects.Move && //
                    _dragSourceTextRange != null &&
                    !_dragSourceTextRange.IsEmpty)
                {
                    // Normally we delete the source selection from OnDrop event,
                    // unless source and target TextBoxes are different.
                    // In this case the source selection is still not empty,
                    // which means that target was in a different TextBox.
                    // So we still need to delete the selected content in the source one.
                    // This will create an undo unit different from a dropping one,
                    // which is ok, because it will be in different TextBox's undo stack.
                    using (selection.DeclareChangeBlock())
                    {
                        // This is end of Move - we need to delete source content
                        _dragSourceTextRange.Text = String.Empty;
                    }
                }

                // Clean up the text range.
                _dragSourceTextRange = null;

                // Check the data binding expression and update the source and target if the drag source
                // has the binding expression. Without this, data binding is broken after complete the 
                // drag-drop operation because Drop() paste the object then set the focus to the target.
                // The losting focus invoke the data binding expression's Update(), but the source isn't
                // updated yet before complete DoDragDrop.
                if (!_textEditor.IsReadOnly)
                {
                    BindingExpressionBase bindingExpression = BindingOperations.GetBindingExpressionBase(
                        _textEditor.UiScope, TextBox.TextProperty);
                    if (bindingExpression != null)
                    {
                        bindingExpression.UpdateSource();
                        bindingExpression.UpdateTarget();
                    }
                }
            }
Exemplo n.º 45
0
 public void Create2(
     ModeKind kind = ModeKind.VisualCharacter,
     params string[] lines)
 {
     _textView = EditorUtil.CreateTextView(lines);
     _textBuffer = _textView.TextBuffer;
     _selection = _textView.Selection;
     _factory = new MockRepository(MockBehavior.Strict);
     _map = VimUtil.CreateRegisterMap(MockObjectFactory.CreateClipboardDevice(_factory).Object);
     _markMap = new MarkMap(new TrackingLineColumnService());
     _tracker = _factory.Create<ISelectionTracker>();
     _tracker.Setup(x => x.Start());
     _tracker.Setup(x => x.ResetCaret());
     _tracker.Setup(x => x.UpdateSelection());
     _jumpList = _factory.Create<IJumpList>(MockBehavior.Loose);
     _undoRedoOperations = _factory.Create<IUndoRedoOperations>();
     _foldManager = _factory.Create<IFoldManager>();
     _editorOperations = _factory.Create<IEditorOperations>();
     _operations = _factory.Create<ICommonOperations>();
     _operations.SetupGet(x => x.UndoRedoOperations).Returns(_undoRedoOperations.Object);
     _operations.SetupGet(x => x.EditorOperations).Returns(_editorOperations.Object);
     _operations.SetupGet(x => x.TextView).Returns(_textView);
     _host = _factory.Create<IVimHost>(MockBehavior.Loose);
     _commandUtil = _factory.Create<ICommandUtil>();
     _incrementalSearch = MockObjectFactory.CreateIncrementalSearch(factory: _factory);
     var globalSettings = new GlobalSettings();
     var localSettings = new LocalSettings(globalSettings, EditorUtil.GetEditorOptions(_textView), _textView);
     var motionUtil = VimUtil.CreateTextViewMotionUtil(
         _textView,
         _markMap,
         localSettings);
     _bufferData = MockObjectFactory.CreateVimBuffer(
         _textView,
         "test",
         MockObjectFactory.CreateVim(_map, host: _host.Object, settings: globalSettings).Object,
         incrementalSearch: _incrementalSearch.Object,
         jumpList: _jumpList.Object,
         motionUtil: motionUtil);
     var capture = new MotionCapture(
         _host.Object,
         _textView,
         _incrementalSearch.Object,
         localSettings);
     var runner = new CommandRunner(
         _textView,
         _map,
         capture,
         _commandUtil.Object,
         (new Mock<IStatusUtil>()).Object,
         VisualKind.Character);
     _modeRaw = new VisualMode(_bufferData.Object, _operations.Object, kind, runner, capture, _tracker.Object);
     _mode = _modeRaw;
     _mode.OnEnter(ModeArgument.None);
 }
            private bool IsStreamSelectionInEditableBuffer(ITextSelection selection)
            {
                Debug.Assert(selection.Mode == TextSelectionMode.Stream);

                var editableBuffer = (ReadingStandardInput) ? StandardInputBuffer : CurrentLanguageBuffer;
                var selectedSpans = selection.SelectedSpans;

                foreach (var selectedSpan in selectedSpans)
                {
                    var spans = TextView.BufferGraph.MapDownToBuffer(selectedSpan, SpanTrackingMode.EdgeInclusive, editableBuffer);
                    if (spans.Count > 0)
                    {
                        return true;
                    }
                }
                return false;
            }
Exemplo n.º 47
0
			public SelectionState(ITextSelection selection) {
				state = (byte)((selection.IsEmpty ? 1 : 0) | (selection.Mode == TextSelectionMode.Box ? 2 : 0));
			}
Exemplo n.º 48
0
        // Helper for UpdateCaretState -- calculates caret rectangle from text selection.
        // regular (non-interim) case of caret positioning
        private static Rect CalculateCaretRectangle(ITextSelection currentTextSelection, ITextPointer caretPosition)
        {
            Transform caretTransform;
            Rect caretRectangle = currentTextSelection.TextView.GetRawRectangleFromTextPosition(caretPosition, out caretTransform);

            if (caretRectangle.IsEmpty)
            {
                // Caret is not at an insertion position, it has no geometry
                // and will not be displayed.
                return Rect.Empty;
            }

            // Convert to local coordiantes.
            caretRectangle = caretTransform.TransformBounds(caretRectangle);

            // We will use the system defined caret width later.
            caretRectangle.Width = 0;

            if (currentTextSelection.IsEmpty)
            {
                // Calculate caret height - from current font size (ignoring a rect returned by TextView,
                // as it can be a rect of embedded object, which should not affect caret height)
                double fontSize = (double)currentTextSelection.GetPropertyValue(TextElement.FontSizeProperty);
                FontFamily fontFamily = (FontFamily)currentTextSelection.GetPropertyValue(TextElement.FontFamilyProperty);
                double caretHeight = fontFamily.LineSpacing * fontSize;
                if (caretHeight < caretRectangle.Height)
                {
                    // Decrease the height of caret to the font height and lower the caret to keep its bottom
                    // staying on the baseline.
                    caretRectangle.Y += caretRectangle.Height - caretHeight;
                    caretRectangle.Height = caretHeight;
                }

                if (!caretTransform.IsIdentity)
                {
                    Point top = new Point(caretRectangle.X, caretRectangle.Y);
                    Point bottom = new Point(caretRectangle.X, caretRectangle.Y + caretRectangle.Height);
                    caretTransform.TryTransform(top, out top);
                    caretTransform.TryTransform(bottom, out bottom);
                    caretRectangle.Y += caretRectangle.Height - Math.Abs(bottom.Y - top.Y);
                    caretRectangle.Height = Math.Abs(bottom.Y - top.Y);
                }
            }

            return caretRectangle;
        }
Exemplo n.º 49
0
        // Helper for UpdateCaretState -- handles the korean interim caret.
        private static Rect CalculateInterimCaretRectangle(ITextSelection focusedTextSelection)
        {
            // 

            // Get the current flow direction on the selection of interim.
            // This is for getting the right size of distance on the interim character
            // whatever the current flow direction is.
            FlowDirection flowDirection = (FlowDirection)focusedTextSelection.Start.GetValue(FrameworkElement.FlowDirectionProperty);

            ITextPointer nextCharacterPosition;
            Rect nextCharacterRectangle;
            Rect caretRectangle;

            if (flowDirection != FlowDirection.RightToLeft)
            {
                // Flow direction is Left-to-Right
                // Get the rectangle for both interim selection start position and the next character
                // position.
                nextCharacterPosition = focusedTextSelection.Start.CreatePointer(LogicalDirection.Forward);
                caretRectangle = focusedTextSelection.TextView.GetRectangleFromTextPosition(nextCharacterPosition);

                // Get the next character position from the start position of the interim selection
                // on the left to right flow direction.
                nextCharacterPosition.MoveToNextInsertionPosition(LogicalDirection.Forward);
                nextCharacterPosition.SetLogicalDirection(LogicalDirection.Backward);
                nextCharacterRectangle = focusedTextSelection.TextView.GetRectangleFromTextPosition(nextCharacterPosition);
            }
            else
            {
                // Flow direction is Right-to-Left
                // Get the rectangle for both interim selection end position and the next character
                // position.
                nextCharacterPosition = focusedTextSelection.End.CreatePointer(LogicalDirection.Backward);
                caretRectangle = focusedTextSelection.TextView.GetRectangleFromTextPosition(nextCharacterPosition);

                // Get the next character position from the end position of the interim selection
                // on the right to left flow direction.
                nextCharacterPosition.MoveToNextInsertionPosition(LogicalDirection.Backward);
                nextCharacterPosition.SetLogicalDirection(LogicalDirection.Forward);
                nextCharacterRectangle = focusedTextSelection.TextView.GetRectangleFromTextPosition(nextCharacterPosition);
            }

            // The interim next character position should be great than the current interim position.
            // Otherwise, we show the caret as the normal state that use the system caret width.
            // In case of BiDi character, the next character position can be greater than the current position.
            if (!caretRectangle.IsEmpty && !nextCharacterRectangle.IsEmpty && nextCharacterRectangle.Left > caretRectangle.Left)
            {
                // Get the interim caret width to show the interim block caret.
                caretRectangle.Width = nextCharacterRectangle.Left - caretRectangle.Left;
            }

            return caretRectangle;
        }
Exemplo n.º 50
0
 public static Mock<ITextView> CreateTextView(
     ITextBuffer textBuffer = null,
     ITextCaret caret = null,
     ITextSelection selection = null,
     ITextViewRoleSet textViewRoleSet = null,
     ITextViewModel textViewModel = null,
     IEditorOptions editorOptions = null,
     IBufferGraph bufferGraph = null,
     PropertyCollection propertyCollection = null,
     MockRepository factory = null)
 {
     factory = factory ?? new MockRepository(MockBehavior.Strict);
     textBuffer = textBuffer ?? CreateTextBuffer(100, factory: factory).Object;
     caret = caret ?? CreateCaret(factory: factory).Object;
     selection = selection ?? CreateSelection(factory: factory).Object;
     propertyCollection = propertyCollection ?? new PropertyCollection();
     textViewRoleSet = textViewRoleSet ?? CreateTextViewRoleSet(factory: factory).Object;
     editorOptions = editorOptions ?? CreateEditorOptions(factory: factory).Object;
     bufferGraph = bufferGraph ?? CreateBufferGraph(factory: factory).Object;
     textViewModel = textViewModel ?? CreateTextViewModel(textBuffer: textBuffer, factory: factory).Object;
     var view = factory.Create<ITextView>();
     view.SetupGet(x => x.Caret).Returns(caret);
     view.SetupGet(x => x.Selection).Returns(selection);
     view.SetupGet(x => x.TextBuffer).Returns(textBuffer);
     view.SetupGet(x => x.TextSnapshot).Returns(() => textBuffer.CurrentSnapshot);
     view.SetupGet(x => x.Properties).Returns(propertyCollection);
     view.SetupGet(x => x.Roles).Returns(textViewRoleSet);
     view.SetupGet(x => x.Options).Returns(editorOptions);
     view.SetupGet(x => x.BufferGraph).Returns(bufferGraph);
     view.SetupGet(x => x.TextViewModel).Returns(textViewModel);
     return view;
 }
Exemplo n.º 51
0
        public IRHistoryWindowVisualComponent GetOrCreateVisualComponent(IRHistoryVisualComponentContainerFactory visualComponentContainerFactory, int instanceId = 0) { 
            if (VisualComponent != null) {
                return VisualComponent;
            }

            VisualComponent = visualComponentContainerFactory.GetOrCreate(_historyTextBuffer).Component;
            _textViewSelection = VisualComponent.TextView.Selection;
            _editorOperations = _editorOperationsFactory.GetEditorOperations(VisualComponent.TextView);
            return VisualComponent;
        }
Exemplo n.º 52
0
        /// <summary> 
        /// Process the case of Empty selection for the different annotation types
        /// </summary> 
        /// <param name="selection">the selection</param>
        /// <param name="anchor">annotation anchor</param>
        /// <param name="type">annotation type</param>
        /// <returns></returns> 
        private static bool CheckCaret(ITextSelection selection, TextAnchor anchor, XmlQualifiedName type)
        { 
            //selection must be empty 
            if (!selection.IsEmpty)
                return false; 

            if (((anchor.Start.CompareTo(selection.Start) == 0) &&
                 (selection.Start.LogicalDirection == LogicalDirection.Forward)) ||
               ((anchor.End.CompareTo(selection.End) == 0) && 
                (selection.End.LogicalDirection == LogicalDirection.Backward)))
                return true; 
 
            return false;
 
        }
Exemplo n.º 53
0
        //-------------------------------------------------------------------
        //
        //  Private Methods
        //
        //-------------------------------------------------------------------

        #region Private Methods

        /// <summary>
        /// Returns whether TextSelection is valid for document - As this is flow document, we require the text containers to be equal
        /// to allow it as a valid selection.
        /// </summary>
        private bool IsValidTextSelectionForDocument(ITextSelection textSelection, FlowDocument flowDocument)
        {
            if(textSelection.Start != null && textSelection.Start.TextContainer == flowDocument.StructuralCache.TextContainer)
            {
                return true;
            }

            return false;
        }
Exemplo n.º 54
0
        private void Create2(
            ModeKind kind = ModeKind.VisualCharacter,
            params string[] lines)
        {
            _textView = CreateTextView(lines);
            _textBuffer = _textView.TextBuffer;
            var vimTextBuffer = Vim.CreateVimTextBuffer(_textBuffer);
            var vimBufferData = CreateVimBufferData(vimTextBuffer, _textView);

            _selection = _textView.Selection;
            _factory = new MockRepository(MockBehavior.Strict);
            _tracker = _factory.Create<ISelectionTracker>();
            _tracker.Setup(x => x.Start());
            _tracker.Setup(x => x.UpdateSelection());
            _tracker.SetupGet(x => x.IsRunning).Returns(true);
            _operations = _factory.Create<ICommonOperations>();
            _operations.SetupGet(x => x.TextView).Returns(_textView);
            _commandUtil = _factory.Create<ICommandUtil>();
            var motionUtil = new MotionUtil(vimBufferData);
            var capture = new MotionCapture(vimBufferData, new IncrementalSearch(vimBufferData, _operations.Object));
            var runner = new CommandRunner(
                _textView,
                Vim.RegisterMap,
                capture,
                _commandUtil.Object,
                (new Mock<IStatusUtil>()).Object,
                VisualKind.Character);
            _modeRaw = new VisualMode(vimBufferData, _operations.Object, motionUtil, kind, runner, capture, _tracker.Object);
            _mode = _modeRaw;
            _mode.OnEnter(ModeArgument.None);
        }
Exemplo n.º 55
0
        public static SnapshotSpan? MapSelectionToPrimaryBuffer(ITextSelection selection)
        {
            var span = selection.StreamSelectionSpan.SnapshotSpan;

              ITextView view = selection.TextView;
              var buffer = GetPrimaryBuffer(view);

              var locations = view.BufferGraph.MapDownToBuffer(
            span, SpanTrackingMode.EdgeInclusive, buffer
              );
              if ( locations.Count > 0 ) {
            span = new SnapshotSpan(locations[0].Start, locations[locations.Count - 1].End);
              }
              return span;
        }
Exemplo n.º 56
0
        private static IList<IAttachedAnnotation> GetSpannedAnnotationsForFlow(AnnotationService service, ITextSelection selection)
        {
            Invariant.Assert(service != null); 

            // Expand the range to get annotations that sit just outside the selection - important for merging 
            ITextPointer start = selection.Start.CreatePointer(); 
            ITextPointer end = selection.End.CreatePointer();
            start.MoveToNextInsertionPosition(LogicalDirection.Backward); 
            end.MoveToNextInsertionPosition(LogicalDirection.Forward);
            ITextRange textRange = new TextRange(start, end);

            // Create locator that reflects all spanned annotations for the current selection 
            IList<ContentLocatorBase> locators = service.LocatorManager.GenerateLocators(textRange);
            Invariant.Assert(locators != null && locators.Count > 0); 
 
            TextSelectionProcessor rangeProcessor = service.LocatorManager.GetSelectionProcessor(typeof(TextRange)) as TextSelectionProcessor;
            TextSelectionProcessor anchorProcessor = service.LocatorManager.GetSelectionProcessor(typeof(TextAnchor)) as TextSelectionProcessor; 
            Invariant.Assert(rangeProcessor != null, "TextSelectionProcessor should be available for TextRange if we are processing flow content.");
            Invariant.Assert(anchorProcessor != null, "TextSelectionProcessor should be available for TextAnchor if we are processing flow content.");

            IList<IAttachedAnnotation> attachedAnnotations = null; 
            IList<Annotation> annotations = null;
            try 
            { 
                // Turn resolving for non-visible content on
                rangeProcessor.Clamping = false; 
                anchorProcessor.Clamping = false;

                ContentLocator locator = locators[0] as ContentLocator;
                Invariant.Assert(locator != null, "Locators for selection in Flow should always be ContentLocators.  ContentLocatorSets not supported."); 

                // Make sure we get all annotations that overlap with the selection 
                locator.Parts[locator.Parts.Count - 1].NameValuePairs.Add(TextSelectionProcessor.IncludeOverlaps, Boolean.TrueString); 

                // Query for the annotations 
                annotations = service.Store.GetAnnotations(locator);

                //
                attachedAnnotations = ResolveAnnotations(service, annotations); 
            }
            finally 
            { 
                // Turn resolving of non-visible content off again
                rangeProcessor.Clamping = true; 
                anchorProcessor.Clamping = true;
            }

            return attachedAnnotations; 
        }